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.

335 lines
16KB

  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. @itchat.msg_register(VOICE, isGroupChat=True)
  39. def handler_group_voice(msg):
  40. WechatChannel().handle_group_voice(msg)
  41. return None
  42. class WechatChannel(Channel):
  43. def __init__(self):
  44. self.userName = None
  45. self.nickName = None
  46. def startup(self):
  47. itchat.instance.receivingRetryCount = 600 # 修改断线超时时间
  48. # login by scan QRCode
  49. hotReload = conf().get('hot_reload', False)
  50. try:
  51. itchat.auto_login(enableCmdQR=2, hotReload=hotReload)
  52. except Exception as e:
  53. if hotReload:
  54. logger.error("Hot reload failed, try to login without hot reload")
  55. itchat.logout()
  56. os.remove("itchat.pkl")
  57. itchat.auto_login(enableCmdQR=2, hotReload=hotReload)
  58. else:
  59. raise e
  60. self.userName = itchat.instance.storageClass.userName
  61. self.nickName = itchat.instance.storageClass.nickName
  62. logger.info("Wechat login success, username: {}, nickname: {}".format(self.userName, self.nickName))
  63. # start message listener
  64. itchat.run()
  65. # handle_* 系列函数处理收到的消息后构造Context,然后传入handle函数中处理Context和发送回复
  66. # Context包含了消息的所有信息,包括以下属性
  67. # type 消息类型, 包括TEXT、VOICE、IMAGE_CREATE
  68. # content 消息内容,如果是TEXT类型,content就是文本内容,如果是VOICE类型,content就是语音文件名,如果是IMAGE_CREATE类型,content就是图片生成命令
  69. # kwargs 附加参数字典,包含以下的key:
  70. # session_id: 会话id
  71. # isgroup: 是否是群聊
  72. # receiver: 需要回复的对象
  73. # msg: itchat的原始消息对象
  74. def handle_voice(self, msg):
  75. if conf().get('speech_recognition') != True:
  76. return
  77. logger.debug("[WX]receive voice msg: " + msg['FileName'])
  78. to_user_id = msg['ToUserName']
  79. from_user_id = msg['FromUserName']
  80. try:
  81. other_user_id = msg['User']['UserName'] # 对手方id
  82. except Exception as e:
  83. logger.warn("[WX]get other_user_id failed: " + str(e))
  84. if from_user_id == self.userName:
  85. other_user_id = to_user_id
  86. else:
  87. other_user_id = from_user_id
  88. if from_user_id == other_user_id:
  89. context = Context(ContextType.VOICE,msg['FileName'])
  90. context.kwargs = {'isgroup': False, 'msg': msg, 'receiver': other_user_id, 'session_id': other_user_id}
  91. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  92. @time_checker
  93. def handle_text(self, msg):
  94. logger.debug("[WX]receive text msg: " + json.dumps(msg, ensure_ascii=False))
  95. content = msg['Text']
  96. from_user_id = msg['FromUserName']
  97. to_user_id = msg['ToUserName'] # 接收人id
  98. try:
  99. other_user_id = msg['User']['UserName'] # 对手方id
  100. except Exception as e:
  101. logger.warn("[WX]get other_user_id failed: " + str(e))
  102. if from_user_id == self.userName:
  103. other_user_id = to_user_id
  104. else:
  105. other_user_id = from_user_id
  106. create_time = msg['CreateTime'] # 消息时间
  107. match_prefix = check_prefix(content, conf().get('single_chat_prefix'))
  108. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: #跳过1分钟前的历史消息
  109. logger.debug("[WX]history message skipped")
  110. return
  111. if "」\n- - - - - - - - - - - - - - -" in content:
  112. logger.debug("[WX]reference query skipped")
  113. return
  114. if match_prefix:
  115. content = content.replace(match_prefix, '', 1).strip()
  116. elif match_prefix is None:
  117. return
  118. context = Context()
  119. context.kwargs = {'isgroup': False, 'msg': msg, 'receiver': other_user_id, 'session_id': other_user_id}
  120. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  121. if img_match_prefix:
  122. content = content.replace(img_match_prefix, '', 1).strip()
  123. context.type = ContextType.IMAGE_CREATE
  124. else:
  125. context.type = ContextType.TEXT
  126. context.content = content
  127. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  128. @time_checker
  129. def handle_group(self, msg):
  130. logger.debug("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  131. group_name = msg['User'].get('NickName', None)
  132. group_id = msg['User'].get('UserName', None)
  133. create_time = msg['CreateTime'] # 消息时间
  134. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: #跳过1分钟前的历史消息
  135. logger.debug("[WX]history group message skipped")
  136. return
  137. if not group_name:
  138. return ""
  139. origin_content = msg['Content']
  140. content = msg['Content']
  141. content_list = content.split(' ', 1)
  142. context_special_list = content.split('\u2005', 1)
  143. if len(context_special_list) == 2:
  144. content = context_special_list[1]
  145. elif len(content_list) == 2:
  146. content = content_list[1]
  147. if "」\n- - - - - - - - - - - - - - -" in content:
  148. logger.debug("[WX]reference query skipped")
  149. return ""
  150. config = conf()
  151. match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or check_prefix(origin_content, config.get('group_chat_prefix')) \
  152. or check_contain(origin_content, config.get('group_chat_keyword'))
  153. 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:
  154. context = Context()
  155. context.kwargs = { 'isgroup': True, 'msg': msg, 'receiver': group_id}
  156. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  157. if img_match_prefix:
  158. content = content.replace(img_match_prefix, '', 1).strip()
  159. context.type = ContextType.IMAGE_CREATE
  160. else:
  161. context.type = ContextType.TEXT
  162. context.content = content
  163. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  164. if ('ALL_GROUP' in group_chat_in_one_session or
  165. group_name in group_chat_in_one_session or
  166. check_contain(group_name, group_chat_in_one_session)):
  167. context['session_id'] = group_id
  168. else:
  169. context['session_id'] = msg['ActualUserName']
  170. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  171. def handle_group_voice(self, msg):
  172. if conf().get('group_speech_recognition', False) != True:
  173. return
  174. logger.debug("[WX]receive voice for group msg: " + msg['FileName'])
  175. group_name = msg['User'].get('NickName', None)
  176. group_id = msg['User'].get('UserName', None)
  177. create_time = msg['CreateTime'] # 消息时间
  178. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: #跳过1分钟前的历史消息
  179. logger.debug("[WX]history group voice skipped")
  180. return
  181. # 验证群名
  182. if not group_name:
  183. return ""
  184. if ('ALL_GROUP' in conf().get('group_name_white_list') or group_name in conf().get('group_name_white_list') or check_contain(group_name, conf().get('group_name_keyword_white_list'))):
  185. context = Context(ContextType.VOICE,msg['FileName'])
  186. context.kwargs = {'isgroup': True, 'msg': msg, 'receiver': group_id}
  187. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  188. if ('ALL_GROUP' in group_chat_in_one_session or
  189. group_name in group_chat_in_one_session or
  190. check_contain(group_name, group_chat_in_one_session)):
  191. context['session_id'] = group_id
  192. else:
  193. context['session_id'] = msg['ActualUserName']
  194. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  195. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  196. def send(self, reply : Reply, receiver):
  197. if reply.type == ReplyType.TEXT:
  198. itchat.send(reply.content, toUserName=receiver)
  199. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  200. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  201. itchat.send(reply.content, toUserName=receiver)
  202. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  203. elif reply.type == ReplyType.VOICE:
  204. itchat.send_file(reply.content, toUserName=receiver)
  205. logger.info('[WX] sendFile={}, receiver={}'.format(reply.content, receiver))
  206. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  207. img_url = reply.content
  208. pic_res = requests.get(img_url, stream=True)
  209. image_storage = io.BytesIO()
  210. for block in pic_res.iter_content(1024):
  211. image_storage.write(block)
  212. image_storage.seek(0)
  213. itchat.send_image(image_storage, toUserName=receiver)
  214. logger.info('[WX] sendImage url={}, receiver={}'.format(img_url,receiver))
  215. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  216. image_storage = reply.content
  217. image_storage.seek(0)
  218. itchat.send_image(image_storage, toUserName=receiver)
  219. logger.info('[WX] sendImage, receiver={}'.format(receiver))
  220. # 处理消息 TODO: 如果wechaty解耦,此处逻辑可以放置到父类
  221. def handle(self, context):
  222. reply = Reply()
  223. logger.debug('[WX] ready to handle context: {}'.format(context))
  224. # reply的构建步骤
  225. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {'channel' : self, 'context': context, 'reply': reply}))
  226. reply = e_context['reply']
  227. if not e_context.is_pass():
  228. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  229. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  230. reply = super().build_reply_content(context.content, context)
  231. elif context.type == ContextType.VOICE: # 语音消息
  232. msg = context['msg']
  233. file_name = TmpDir().path() + context.content
  234. msg.download(file_name)
  235. reply = super().build_voice_to_text(file_name)
  236. if reply.type == ReplyType.TEXT:
  237. content = reply.content # 语音转文字后,将文字内容作为新的context
  238. # 如果是群消息,判断是否触发关键字
  239. if context['isgroup']:
  240. match_prefix = check_prefix(content, conf().get('group_chat_prefix'))
  241. match_contain = check_contain(content, conf().get('group_chat_keyword'))
  242. logger.debug('[WX] group chat prefix match: {}'.format(match_prefix))
  243. if match_prefix is None and match_contain is None:
  244. return
  245. else:
  246. if match_prefix:
  247. content = content.replace(match_prefix, '', 1).strip()
  248. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  249. if img_match_prefix:
  250. content = content.replace(img_match_prefix, '', 1).strip()
  251. context.type = ContextType.IMAGE_CREATE
  252. else:
  253. context.type = ContextType.TEXT
  254. context.content = content
  255. reply = super().build_reply_content(context.content, context)
  256. if reply.type == ReplyType.TEXT:
  257. if conf().get('voice_reply_voice'):
  258. reply = super().build_text_to_voice(reply.content)
  259. else:
  260. logger.error('[WX] unknown context type: {}'.format(context.type))
  261. return
  262. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  263. # reply的包装步骤
  264. if reply and reply.type:
  265. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {'channel' : self, 'context': context, 'reply': reply}))
  266. reply=e_context['reply']
  267. if not e_context.is_pass() and reply and reply.type:
  268. if reply.type == ReplyType.TEXT:
  269. reply_text = reply.content
  270. if context['isgroup']:
  271. reply_text = '@' + context['msg']['ActualNickName'] + ' ' + reply_text.strip()
  272. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  273. else:
  274. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  275. reply.content = reply_text
  276. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  277. reply.content = str(reply.type)+":\n" + reply.content
  278. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  279. pass
  280. else:
  281. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  282. return
  283. # reply的发送步骤
  284. if reply and reply.type:
  285. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {'channel' : self, 'context': context, 'reply': reply}))
  286. reply=e_context['reply']
  287. if not e_context.is_pass() and reply and reply.type:
  288. logger.debug('[WX] ready to send reply: {} to {}'.format(reply, context['receiver']))
  289. self.send(reply, context['receiver'])
  290. def check_prefix(content, prefix_list):
  291. for prefix in prefix_list:
  292. if content.startswith(prefix):
  293. return prefix
  294. return None
  295. def check_contain(content, keyword_list):
  296. if not keyword_list:
  297. return None
  298. for ky in keyword_list:
  299. if content.find(ky) != -1:
  300. return True
  301. return None