Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

210 rindas
9.6KB

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