Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

257 lines
11KB

  1. # encoding:utf-8
  2. """
  3. wechat channel
  4. """
  5. import itchat
  6. import json
  7. from itchat.content import *
  8. from bridge.reply import *
  9. from bridge.context import *
  10. from channel.channel import Channel
  11. from concurrent.futures import ThreadPoolExecutor
  12. from common.log import logger
  13. from common.tmp_dir import TmpDir
  14. from config import conf
  15. from plugins import *
  16. import requests
  17. import io
  18. import time
  19. thread_pool = ThreadPoolExecutor(max_workers=8)
  20. def thread_pool_callback(worker):
  21. worker_exception = worker.exception()
  22. if worker_exception:
  23. logger.exception("Worker return exception: {}".format(worker_exception))
  24. @itchat.msg_register(TEXT)
  25. def handler_single_msg(msg):
  26. WechatChannel().handle_text(msg)
  27. return None
  28. @itchat.msg_register(TEXT, isGroupChat=True)
  29. def handler_group_msg(msg):
  30. WechatChannel().handle_group(msg)
  31. return None
  32. @itchat.msg_register(VOICE)
  33. def handler_single_voice(msg):
  34. WechatChannel().handle_voice(msg)
  35. return None
  36. class WechatChannel(Channel):
  37. def __init__(self):
  38. pass
  39. def startup(self):
  40. # login by scan QRCode
  41. itchat.auto_login(enableCmdQR=2, hotReload=conf().get('hot_reload', False))
  42. # start message listener
  43. itchat.run()
  44. # handle_* 系列函数处理收到的消息后构造context,然后调用handle函数处理context
  45. # context是一个字典,包含了消息的所有信息,包括以下key
  46. # type 消息类型, 包括TEXT、VOICE、IMAGE_CREATE
  47. # content 消息内容,如果是TEXT类型,content就是文本内容,如果是VOICE类型,content就是语音文件名,如果是IMAGE_CREATE类型,content就是图片生成命令
  48. # session_id: 会话id
  49. # isgroup: 是否是群聊
  50. # msg: 原始消息对象
  51. # receiver: 需要回复的对象
  52. def handle_voice(self, msg):
  53. if conf().get('speech_recognition') != True:
  54. return
  55. logger.debug("[WX]receive voice msg: " + msg['FileName'])
  56. from_user_id = msg['FromUserName']
  57. other_user_id = msg['User']['UserName']
  58. if from_user_id == other_user_id:
  59. context = Context(ContextType.VOICE,msg['FileName'])
  60. context.kwargs = {'isgroup': False, 'msg': msg, 'receiver': other_user_id, 'session_id': other_user_id}
  61. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  62. def handle_text(self, msg):
  63. logger.debug("[WX]receive text msg: " + json.dumps(msg, ensure_ascii=False))
  64. content = msg['Text']
  65. from_user_id = msg['FromUserName']
  66. to_user_id = msg['ToUserName'] # 接收人id
  67. other_user_id = msg['User']['UserName'] # 对手方id
  68. create_time = msg['CreateTime'] # 消息时间
  69. match_prefix = check_prefix(content, conf().get('single_chat_prefix'))
  70. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: #跳过1分钟前的历史消息
  71. logger.debug("[WX]history message skipped")
  72. return
  73. if "」\n- - - - - - - - - - - - - - -" in content:
  74. logger.debug("[WX]reference query skipped")
  75. return
  76. if match_prefix:
  77. content = content.replace(match_prefix, '', 1).strip()
  78. else:
  79. return
  80. context = Context()
  81. context.kwargs = {'isgroup': False, 'msg': msg, 'receiver': other_user_id, 'session_id': other_user_id}
  82. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  83. if img_match_prefix:
  84. content = content.replace(img_match_prefix, '', 1).strip()
  85. context.type = ContextType.IMAGE_CREATE
  86. else:
  87. context.type = ContextType.TEXT
  88. context.content = content
  89. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  90. def handle_group(self, msg):
  91. logger.debug("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  92. group_name = msg['User'].get('NickName', None)
  93. group_id = msg['User'].get('UserName', None)
  94. create_time = msg['CreateTime'] # 消息时间
  95. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: #跳过1分钟前的历史消息
  96. logger.debug("[WX]history group message skipped")
  97. return
  98. if not group_name:
  99. return ""
  100. origin_content = msg['Content']
  101. content = msg['Content']
  102. content_list = content.split(' ', 1)
  103. context_special_list = content.split('\u2005', 1)
  104. if len(context_special_list) == 2:
  105. content = context_special_list[1]
  106. elif len(content_list) == 2:
  107. content = content_list[1]
  108. if "」\n- - - - - - - - - - - - - - -" in content:
  109. logger.debug("[WX]reference query skipped")
  110. return ""
  111. config = conf()
  112. match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or check_prefix(origin_content, config.get('group_chat_prefix')) \
  113. or check_contain(origin_content, config.get('group_chat_keyword'))
  114. if ('ALL_GROUP' in config.get('group_name_white_list') or group_name in config.get('group_name_white_list') or check_contain(group_name, config.get('group_name_keyword_white_list'))) and match_prefix:
  115. context = Context()
  116. context.kwargs = { 'isgroup': True, 'msg': msg, 'receiver': group_id}
  117. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  118. if img_match_prefix:
  119. content = content.replace(img_match_prefix, '', 1).strip()
  120. context.type = ContextType.IMAGE_CREATE
  121. else:
  122. context.type = ContextType.TEXT
  123. context.content = content
  124. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  125. if ('ALL_GROUP' in group_chat_in_one_session or
  126. group_name in group_chat_in_one_session or
  127. check_contain(group_name, group_chat_in_one_session)):
  128. context['session_id'] = group_id
  129. else:
  130. context['session_id'] = msg['ActualUserName']
  131. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  132. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  133. def send(self, reply : Reply, receiver):
  134. if reply.type == ReplyType.TEXT:
  135. itchat.send(reply.content, toUserName=receiver)
  136. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  137. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  138. itchat.send(reply.content, toUserName=receiver)
  139. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  140. elif reply.type == ReplyType.VOICE:
  141. itchat.send_file(reply.content, toUserName=receiver)
  142. logger.info('[WX] sendFile={}, receiver={}'.format(reply.content, receiver))
  143. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  144. img_url = reply.content
  145. pic_res = requests.get(img_url, stream=True)
  146. image_storage = io.BytesIO()
  147. for block in pic_res.iter_content(1024):
  148. image_storage.write(block)
  149. image_storage.seek(0)
  150. itchat.send_image(image_storage, toUserName=receiver)
  151. logger.info('[WX] sendImage url=, receiver={}'.format(img_url,receiver))
  152. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  153. image_storage = reply.content
  154. image_storage.seek(0)
  155. itchat.send_image(image_storage, toUserName=receiver)
  156. logger.info('[WX] sendImage, receiver={}'.format(receiver))
  157. # 处理消息 TODO: 如果wechaty解耦,此处逻辑可以放置到父类
  158. def handle(self, context):
  159. reply = Reply()
  160. logger.debug('[WX] ready to handle context: {}'.format(context))
  161. # reply的构建步骤
  162. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {'channel' : self, 'context': context, 'reply': reply}))
  163. reply = e_context['reply']
  164. if not e_context.is_pass():
  165. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  166. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE:
  167. reply = super().build_reply_content(context.content, context)
  168. elif context.type == ContextType.VOICE:
  169. msg = context['msg']
  170. file_name = TmpDir().path() + context.content
  171. msg.download(file_name)
  172. reply = super().build_voice_to_text(file_name)
  173. if reply.type != ReplyType.ERROR and reply.type != ReplyType.INFO:
  174. context.content = reply.content # 语音转文字后,将文字内容作为新的context
  175. context.type = ContextType.TEXT
  176. reply = super().build_reply_content(context.content, context)
  177. if reply.type == ReplyType.TEXT:
  178. if conf().get('voice_reply_voice'):
  179. reply = super().build_text_to_voice(reply.content)
  180. else:
  181. logger.error('[WX] unknown context type: {}'.format(context.type))
  182. return
  183. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  184. # reply的包装步骤
  185. if reply and reply.type:
  186. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {'channel' : self, 'context': context, 'reply': reply}))
  187. reply=e_context['reply']
  188. if not e_context.is_pass() and reply and reply.type:
  189. if reply.type == ReplyType.TEXT:
  190. reply_text = reply.content
  191. if context['isgroup']:
  192. reply_text = '@' + context['msg']['ActualNickName'] + ' ' + reply_text.strip()
  193. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  194. else:
  195. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  196. reply.content = reply_text
  197. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  198. reply.content = str(reply.type)+":\n" + reply.content
  199. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  200. pass
  201. else:
  202. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  203. return
  204. # reply的发送步骤
  205. if reply and reply.type:
  206. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {'channel' : self, 'context': context, 'reply': reply}))
  207. reply=e_context['reply']
  208. if not e_context.is_pass() and reply and reply.type:
  209. logger.debug('[WX] ready to send reply: {} to {}'.format(reply, context['receiver']))
  210. self.send(reply, context['receiver'])
  211. def check_prefix(content, prefix_list):
  212. for prefix in prefix_list:
  213. if content.startswith(prefix):
  214. return prefix
  215. return None
  216. def check_contain(content, keyword_list):
  217. if not keyword_list:
  218. return None
  219. for ky in keyword_list:
  220. if content.find(ky) != -1:
  221. return True
  222. return None