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.

273 lines
12KB

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