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 14KB

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