您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

376 行
17KB

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