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

392 行
18KB

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