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.

wechat_channel.py 11KB

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