Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

292 lines
13KB

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