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.

357 lines
16KB

  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. 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,
  120. 'receiver': other_user_id, 'session_id': other_user_id}
  121. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  122. if img_match_prefix:
  123. content = content.replace(img_match_prefix, '', 1).strip()
  124. context.type = ContextType.IMAGE_CREATE
  125. else:
  126. context.type = ContextType.TEXT
  127. context.content = content
  128. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  129. @time_checker
  130. def handle_group(self, msg):
  131. logger.debug("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  132. group_name = msg['User'].get('NickName', None)
  133. group_id = msg['User'].get('UserName', None)
  134. create_time = msg['CreateTime'] # 消息时间
  135. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息
  136. logger.debug("[WX]history group message skipped")
  137. return
  138. if not group_name:
  139. return ""
  140. origin_content = msg['Content']
  141. content = msg['Content']
  142. content_list = content.split(' ', 1)
  143. context_special_list = content.split('\u2005', 1)
  144. if len(context_special_list) == 2:
  145. content = context_special_list[1]
  146. elif len(content_list) == 2:
  147. content = content_list[1]
  148. if "」\n- - - - - - - - - - - - - - -" in content:
  149. logger.debug("[WX]reference query skipped")
  150. return ""
  151. config = conf()
  152. match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or check_prefix(origin_content, config.get('group_chat_prefix')) \
  153. or check_contain(origin_content, config.get('group_chat_keyword'))
  154. 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:
  155. context = Context()
  156. context.kwargs = { 'isgroup': True, 'msg': msg, 'receiver': group_id}
  157. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  158. if img_match_prefix:
  159. content = content.replace(img_match_prefix, '', 1).strip()
  160. context.type = ContextType.IMAGE_CREATE
  161. else:
  162. context.type = ContextType.TEXT
  163. context.content = content
  164. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  165. if ('ALL_GROUP' in group_chat_in_one_session or
  166. group_name in group_chat_in_one_session or
  167. check_contain(group_name, group_chat_in_one_session)):
  168. context['session_id'] = group_id
  169. else:
  170. context['session_id'] = msg['ActualUserName']
  171. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  172. def handle_group_voice(self, msg):
  173. if conf().get('group_speech_recognition', False) != True:
  174. return
  175. logger.debug("[WX]receive voice for group msg: " + msg['FileName'])
  176. group_name = msg['User'].get('NickName', None)
  177. group_id = msg['User'].get('UserName', None)
  178. create_time = msg['CreateTime'] # 消息时间
  179. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: #跳过1分钟前的历史消息
  180. logger.debug("[WX]history group voice skipped")
  181. return
  182. # 验证群名
  183. if not group_name:
  184. return ""
  185. 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'))):
  186. context = Context(ContextType.VOICE,msg['FileName'])
  187. context.kwargs = {'isgroup': True, 'msg': msg, 'receiver': group_id}
  188. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  189. if ('ALL_GROUP' in group_chat_in_one_session or
  190. group_name in group_chat_in_one_session or
  191. check_contain(group_name, group_chat_in_one_session)):
  192. context['session_id'] = group_id
  193. else:
  194. context['session_id'] = msg['ActualUserName']
  195. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  196. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  197. def send(self, reply: Reply, receiver):
  198. if reply.type == ReplyType.TEXT:
  199. itchat.send(reply.content, toUserName=receiver)
  200. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  201. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  202. itchat.send(reply.content, toUserName=receiver)
  203. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  204. elif reply.type == ReplyType.VOICE:
  205. itchat.send_file(reply.content, toUserName=receiver)
  206. logger.info('[WX] sendFile={}, receiver={}'.format(reply.content, receiver))
  207. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  208. img_url = reply.content
  209. pic_res = requests.get(img_url, stream=True)
  210. image_storage = io.BytesIO()
  211. for block in pic_res.iter_content(1024):
  212. image_storage.write(block)
  213. image_storage.seek(0)
  214. itchat.send_image(image_storage, toUserName=receiver)
  215. logger.info('[WX] sendImage url={}, receiver={}'.format(img_url,receiver))
  216. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  217. image_storage = reply.content
  218. image_storage.seek(0)
  219. itchat.send_image(image_storage, toUserName=receiver)
  220. logger.info('[WX] sendImage, receiver={}'.format(receiver))
  221. # 处理消息 TODO: 如果wechaty解耦,此处逻辑可以放置到父类
  222. def handle(self, context):
  223. if not context.content:
  224. return
  225. reply = Reply()
  226. logger.debug('[WX] ready to handle context: {}'.format(context))
  227. # reply的构建步骤
  228. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {
  229. 'channel': self, 'context': context, 'reply': reply}))
  230. reply = e_context['reply']
  231. if not e_context.is_pass():
  232. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  233. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  234. reply = super().build_reply_content(context.content, context)
  235. elif context.type == ContextType.VOICE: # 语音消息
  236. msg = context['msg']
  237. mp3_path = TmpDir().path() + context.content
  238. msg.download(mp3_path)
  239. # mp3转wav
  240. wav_path = os.path.splitext(mp3_path)[0] + '.wav'
  241. from voice.audio_convert import mp3_to_wav
  242. mp3_to_wav(mp3_path=mp3_path, wav_path=wav_path)
  243. # 语音识别
  244. reply = super().build_voice_to_text(wav_path)
  245. # 删除临时文件
  246. os.remove(wav_path)
  247. os.remove(mp3_path)
  248. if reply.type != ReplyType.ERROR and reply.type != ReplyType.INFO:
  249. content = reply.content # 语音转文字后,将文字内容作为新的context
  250. context.type = ContextType.TEXT
  251. if context["isgroup"]:
  252. # 校验关键字
  253. match_prefix = check_prefix(content, conf().get('group_chat_prefix'))
  254. match_contain = check_contain(content, conf().get('group_chat_keyword'))
  255. if match_prefix is not None or match_contain is not None:
  256. # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容,用于实现类似自定义+前缀触发生成AI图片的功能
  257. if match_prefix:
  258. content = content.replace(match_prefix, '', 1).strip()
  259. else:
  260. logger.info("[WX]receive voice, checkprefix didn't match")
  261. return
  262. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  263. if img_match_prefix:
  264. content = content.replace(img_match_prefix, '', 1).strip()
  265. context.type = ContextType.IMAGE_CREATE
  266. else:
  267. context.type = ContextType.TEXT
  268. context.content = content
  269. reply = super().build_reply_content(context.content, context)
  270. if reply.type == ReplyType.TEXT:
  271. if conf().get('voice_reply_voice'):
  272. reply = super().build_text_to_voice(reply.content)
  273. else:
  274. logger.error('[WX] unknown context type: {}'.format(context.type))
  275. return
  276. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  277. # reply的包装步骤
  278. if reply and reply.type:
  279. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {
  280. 'channel': self, 'context': context, 'reply': reply}))
  281. reply = e_context['reply']
  282. if not e_context.is_pass() and reply and reply.type:
  283. if reply.type == ReplyType.TEXT:
  284. reply_text = reply.content
  285. if context['isgroup']:
  286. reply_text = '@' + context['msg']['ActualNickName'] + ' ' + reply_text.strip()
  287. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  288. else:
  289. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  290. reply.content = reply_text
  291. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  292. reply.content = str(reply.type)+":\n" + reply.content
  293. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  294. pass
  295. else:
  296. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  297. return
  298. # reply的发送步骤
  299. if reply and reply.type:
  300. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {
  301. 'channel': self, 'context': context, 'reply': reply}))
  302. reply = e_context['reply']
  303. if not e_context.is_pass() and reply and reply.type:
  304. logger.debug('[WX] ready to send reply: {} to {}'.format(reply, context['receiver']))
  305. self.send(reply, context['receiver'])
  306. def check_prefix(content, prefix_list):
  307. for prefix in prefix_list:
  308. if content.startswith(prefix):
  309. return prefix
  310. return None
  311. def check_contain(content, keyword_list):
  312. if not keyword_list:
  313. return None
  314. for ky in keyword_list:
  315. if content.find(ky) != -1:
  316. return True
  317. return None