You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

222 lines
9.5KB

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