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.

261 rinda
12KB

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