您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

passive_reply.py 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import asyncio
  2. import time
  3. import web
  4. from wechatpy import parse_message
  5. from wechatpy.replies import ImageReply, VoiceReply, create_reply
  6. from bridge.context import *
  7. from bridge.reply import *
  8. from channel.wechatmp.common import *
  9. from channel.wechatmp.wechatmp_channel import WechatMPChannel
  10. from channel.wechatmp.wechatmp_message import WeChatMPMessage
  11. from common.log import logger
  12. from config import conf
  13. # This class is instantiated once per query
  14. class Query:
  15. def GET(self):
  16. return verify_server(web.input())
  17. def POST(self):
  18. try:
  19. args = web.input()
  20. verify_server(args)
  21. request_time = time.time()
  22. channel = WechatMPChannel()
  23. message = web.data()
  24. encrypt_func = lambda x: x
  25. if args.get("encrypt_type") == "aes":
  26. logger.debug("[wechatmp] Receive encrypted post data:\n" + message.decode("utf-8"))
  27. if not channel.crypto:
  28. raise Exception("Crypto not initialized, Please set wechatmp_aes_key in config.json")
  29. message = channel.crypto.decrypt_message(message, args.msg_signature, args.timestamp, args.nonce)
  30. encrypt_func = lambda x: channel.crypto.encrypt_message(x, args.nonce, args.timestamp)
  31. else:
  32. logger.debug("[wechatmp] Receive post data:\n" + message.decode("utf-8"))
  33. msg = parse_message(message)
  34. if msg.type in ["text", "voice", "image"]:
  35. wechatmp_msg = WeChatMPMessage(msg, client=channel.client)
  36. from_user = wechatmp_msg.from_user_id
  37. content = wechatmp_msg.content
  38. message_id = wechatmp_msg.msg_id
  39. supported = True
  40. if "【收到不支持的消息类型,暂无法显示】" in content:
  41. supported = False # not supported, used to refresh
  42. # New request
  43. if (
  44. from_user not in channel.cache_dict
  45. and from_user not in channel.running
  46. or content.startswith("#")
  47. and message_id not in channel.request_cnt # insert the godcmd
  48. ):
  49. # The first query begin
  50. if msg.type == "voice" and wechatmp_msg.ctype == ContextType.TEXT and conf().get("voice_reply_voice", False):
  51. context = channel._compose_context(wechatmp_msg.ctype, content, isgroup=False, desire_rtype=ReplyType.VOICE, msg=wechatmp_msg)
  52. else:
  53. context = channel._compose_context(wechatmp_msg.ctype, content, isgroup=False, msg=wechatmp_msg)
  54. logger.debug("[wechatmp] context: {} {} {}".format(context, wechatmp_msg, supported))
  55. if supported and context:
  56. # set private openai_api_key
  57. # if from_user is not changed in itchat, this can be placed at chat_channel
  58. user_data = conf().get_user_data(from_user)
  59. context["openai_api_key"] = user_data.get("openai_api_key")
  60. channel.running.add(from_user)
  61. channel.produce(context)
  62. else:
  63. trigger_prefix = conf().get("single_chat_prefix", [""])[0]
  64. if trigger_prefix or not supported:
  65. if trigger_prefix:
  66. reply_text = textwrap.dedent(
  67. f"""\
  68. 请输入'{trigger_prefix}'接你想说的话跟我说话。
  69. 例如:
  70. {trigger_prefix}你好,很高兴见到你。"""
  71. )
  72. else:
  73. reply_text = textwrap.dedent(
  74. """\
  75. 你好,很高兴见到你。
  76. 请跟我说话吧。"""
  77. )
  78. else:
  79. logger.error(f"[wechatmp] unknown error")
  80. reply_text = textwrap.dedent(
  81. """\
  82. 未知错误,请稍后再试"""
  83. )
  84. replyPost = create_reply(reply_text, msg)
  85. return encrypt_func(replyPost.render())
  86. # Wechat official server will request 3 times (5 seconds each), with the same message_id.
  87. # Because the interval is 5 seconds, here assumed that do not have multithreading problems.
  88. request_cnt = channel.request_cnt.get(message_id, 0) + 1
  89. channel.request_cnt[message_id] = request_cnt
  90. logger.info(
  91. "[wechatmp] Request {} from {} {} {}:{}\n{}".format(
  92. request_cnt, from_user, message_id, web.ctx.env.get("REMOTE_ADDR"), web.ctx.env.get("REMOTE_PORT"), content
  93. )
  94. )
  95. task_running = True
  96. waiting_until = request_time + 4
  97. while time.time() < waiting_until:
  98. if from_user in channel.running:
  99. time.sleep(0.1)
  100. else:
  101. task_running = False
  102. break
  103. reply_text = ""
  104. if task_running:
  105. if request_cnt < 3:
  106. # waiting for timeout (the POST request will be closed by Wechat official server)
  107. time.sleep(2)
  108. # and do nothing, waiting for the next request
  109. return "success"
  110. else: # request_cnt == 3:
  111. # return timeout message
  112. reply_text = "【正在思考中,回复任意文字尝试获取回复】"
  113. replyPost = create_reply(reply_text, msg)
  114. return encrypt_func(replyPost.render())
  115. # reply is ready
  116. channel.request_cnt.pop(message_id)
  117. # no return because of bandwords or other reasons
  118. if from_user not in channel.cache_dict and from_user not in channel.running:
  119. return "success"
  120. # Only one request can access to the cached data
  121. try:
  122. (reply_type, reply_content) = channel.cache_dict.pop(from_user)
  123. except KeyError:
  124. return "success"
  125. if reply_type == "text":
  126. if len(reply_content.encode("utf8")) <= MAX_UTF8_LEN:
  127. reply_text = reply_content
  128. else:
  129. continue_text = "\n【未完待续,回复任意文字以继续】"
  130. splits = split_string_by_utf8_length(
  131. reply_content,
  132. MAX_UTF8_LEN - len(continue_text.encode("utf-8")),
  133. max_split=1,
  134. )
  135. reply_text = splits[0] + continue_text
  136. channel.cache_dict[from_user] = ("text", splits[1])
  137. logger.info(
  138. "[wechatmp] Request {} do send to {} {}: {}\n{}".format(
  139. request_cnt,
  140. from_user,
  141. message_id,
  142. content,
  143. reply_text,
  144. )
  145. )
  146. replyPost = create_reply(reply_text, msg)
  147. return encrypt_func(replyPost.render())
  148. elif reply_type == "voice":
  149. media_id = reply_content
  150. asyncio.run_coroutine_threadsafe(channel.delete_media(media_id), channel.delete_media_loop)
  151. logger.info(
  152. "[wechatmp] Request {} do send to {} {}: {} voice media_id {}".format(
  153. request_cnt,
  154. from_user,
  155. message_id,
  156. content,
  157. media_id,
  158. )
  159. )
  160. replyPost = VoiceReply(message=msg)
  161. replyPost.media_id = media_id
  162. return encrypt_func(replyPost.render())
  163. elif reply_type == "image":
  164. media_id = reply_content
  165. asyncio.run_coroutine_threadsafe(channel.delete_media(media_id), channel.delete_media_loop)
  166. logger.info(
  167. "[wechatmp] Request {} do send to {} {}: {} image media_id {}".format(
  168. request_cnt,
  169. from_user,
  170. message_id,
  171. content,
  172. media_id,
  173. )
  174. )
  175. replyPost = ImageReply(message=msg)
  176. replyPost.media_id = media_id
  177. return encrypt_func(replyPost.render())
  178. elif msg.type == "event":
  179. logger.info("[wechatmp] Event {} from {}".format(msg.event, msg.source))
  180. if msg.event in ["subscribe", "subscribe_scan"]:
  181. reply_text = subscribe_msg()
  182. replyPost = create_reply(reply_text, msg)
  183. return encrypt_func(replyPost.render())
  184. else:
  185. return "success"
  186. else:
  187. logger.info("暂且不处理")
  188. return "success"
  189. except Exception as exc:
  190. logger.exception(exc)
  191. return exc