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.

340 lines
15KB

  1. # encoding:utf-8
  2. """
  3. wechat channel
  4. """
  5. import os
  6. import requests
  7. import io
  8. import time
  9. from lib import itchat
  10. import json
  11. from lib.itchat.content import *
  12. from bridge.reply import *
  13. from bridge.context import *
  14. from channel.channel import Channel
  15. from concurrent.futures import ThreadPoolExecutor
  16. from common.log import logger
  17. from common.tmp_dir import TmpDir
  18. from config import conf
  19. from common.time_check import time_checker
  20. from plugins import *
  21. from voice.audio_convert import mp3_to_wav
  22. thread_pool = ThreadPoolExecutor(max_workers=8)
  23. def thread_pool_callback(worker):
  24. worker_exception = worker.exception()
  25. if worker_exception:
  26. logger.exception("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. mp3_path = TmpDir().path() + context.content
  219. msg.download(mp3_path)
  220. # mp3转wav
  221. wav_path = os.path.splitext(mp3_path)[0] + '.wav'
  222. mp3_to_wav(mp3_path=mp3_path, wav_path=wav_path)
  223. # 语音识别
  224. reply = super().build_voice_to_text(wav_path)
  225. # 删除临时文件
  226. os.remove(wav_path)
  227. os.remove(mp3_path)
  228. if reply.type != ReplyType.ERROR and reply.type != ReplyType.INFO:
  229. context.content = reply.content # 语音转文字后,将文字内容作为新的context
  230. context.type = ContextType.TEXT
  231. if (context["isgroup"] == True):
  232. # 校验关键字
  233. match_prefix = self.check_prefix(context.content, conf().get('group_chat_prefix')) \
  234. or self.check_contain(context.content, conf().get('group_chat_keyword'))
  235. # Wechaty判断is_at为True,返回的内容是过滤掉@之后的内容;而is_at为False,则会返回完整的内容
  236. if match_prefix is not None:
  237. # 故判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容,用于实现类似自定义+前缀触发生成AI图片的功能
  238. prefixes = conf().get('group_chat_prefix')
  239. for prefix in prefixes:
  240. if context.content.startswith(prefix):
  241. context.content = context.content.replace(
  242. prefix, '', 1).strip()
  243. break
  244. else:
  245. logger.info("[WX]receive voice check prefix: " + 'False')
  246. return
  247. reply = super().build_reply_content(context.content, context)
  248. if reply.type == ReplyType.TEXT:
  249. if conf().get('voice_reply_voice'):
  250. reply = super().build_text_to_voice(reply.content)
  251. else:
  252. logger.error('[WX] unknown context type: {}'.format(context.type))
  253. return
  254. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  255. # reply的包装步骤
  256. if reply and reply.type:
  257. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {
  258. 'channel': self, 'context': context, 'reply': reply}))
  259. reply = e_context['reply']
  260. if not e_context.is_pass() and reply and reply.type:
  261. if reply.type == ReplyType.TEXT:
  262. reply_text = reply.content
  263. if context['isgroup']:
  264. reply_text = '@' + \
  265. context['msg']['ActualNickName'] + \
  266. ' ' + reply_text.strip()
  267. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  268. else:
  269. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  270. reply.content = reply_text
  271. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  272. reply.content = str(reply.type)+":\n" + reply.content
  273. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  274. pass
  275. else:
  276. logger.error(
  277. '[WX] unknown reply type: {}'.format(reply.type))
  278. return
  279. # reply的发送步骤
  280. if reply and reply.type:
  281. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {
  282. 'channel': self, 'context': context, 'reply': reply}))
  283. reply = e_context['reply']
  284. if not e_context.is_pass() and reply and reply.type:
  285. logger.debug('[WX] ready to send reply: {} to {}'.format(
  286. reply, context['receiver']))
  287. self.send(reply, context['receiver'])
  288. def check_prefix(content, prefix_list):
  289. for prefix in prefix_list:
  290. if content.startswith(prefix):
  291. return prefix
  292. return None
  293. def check_contain(content, keyword_list):
  294. if not keyword_list:
  295. return None
  296. for ky in keyword_list:
  297. if content.find(ky) != -1:
  298. return True
  299. return None