Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

366 lines
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):
  202. if reply.type == ReplyType.TEXT:
  203. itchat.send(reply.content, toUserName=receiver)
  204. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  205. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  206. itchat.send(reply.content, toUserName=receiver)
  207. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  208. elif reply.type == ReplyType.VOICE:
  209. itchat.send_file(reply.content, toUserName=receiver)
  210. logger.info('[WX] sendFile={}, receiver={}'.format(reply.content, receiver))
  211. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  212. img_url = reply.content
  213. pic_res = requests.get(img_url, stream=True)
  214. image_storage = io.BytesIO()
  215. for block in pic_res.iter_content(1024):
  216. image_storage.write(block)
  217. image_storage.seek(0)
  218. itchat.send_image(image_storage, toUserName=receiver)
  219. logger.info('[WX] sendImage url={}, receiver={}'.format(img_url,receiver))
  220. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  221. image_storage = reply.content
  222. image_storage.seek(0)
  223. itchat.send_image(image_storage, toUserName=receiver)
  224. logger.info('[WX] sendImage, receiver={}'.format(receiver))
  225. # 处理消息 TODO: 如果wechaty解耦,此处逻辑可以放置到父类
  226. def handle(self, context):
  227. if not context.content:
  228. return
  229. reply = Reply()
  230. logger.debug('[WX] ready to handle context: {}'.format(context))
  231. # reply的构建步骤
  232. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {
  233. 'channel': self, 'context': context, 'reply': reply}))
  234. reply = e_context['reply']
  235. if not e_context.is_pass():
  236. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  237. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  238. reply = super().build_reply_content(context.content, context)
  239. elif context.type == ContextType.VOICE: # 语音消息
  240. msg = context['msg']
  241. mp3_path = TmpDir().path() + context.content
  242. msg.download(mp3_path)
  243. # mp3转wav
  244. wav_path = os.path.splitext(mp3_path)[0] + '.wav'
  245. mp3_to_wav(mp3_path=mp3_path, wav_path=wav_path)
  246. # 语音识别
  247. reply = super().build_voice_to_text(wav_path)
  248. # 删除临时文件
  249. try:
  250. os.remove(wav_path)
  251. os.remove(mp3_path)
  252. except Exception as e:
  253. logger.warning("[WX]delete temp file error: " + str(e))
  254. if reply.type != ReplyType.ERROR and reply.type != ReplyType.INFO:
  255. content = reply.content # 语音转文字后,将文字内容作为新的context
  256. context.type = ContextType.TEXT
  257. if context["isgroup"]: # 群聊
  258. # 校验关键字
  259. match_prefix = check_prefix(content, conf().get('group_chat_prefix'))
  260. match_contain = check_contain(content, conf().get('group_chat_keyword'))
  261. if match_prefix is not None or match_contain is not None:
  262. # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容,用于实现类似自定义+前缀触发生成AI图片的功能
  263. if match_prefix:
  264. content = content.replace(match_prefix, '', 1).strip()
  265. else:
  266. logger.info("[WX]receive voice, checkprefix didn't match")
  267. return
  268. else: # 单聊
  269. match_prefix = check_prefix(content, conf().get('single_chat_prefix'))
  270. if match_prefix: # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容
  271. content = content.replace(match_prefix, '', 1).strip()
  272. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  273. if img_match_prefix:
  274. content = content.replace(img_match_prefix, '', 1).strip()
  275. context.type = ContextType.IMAGE_CREATE
  276. else:
  277. context.type = ContextType.TEXT
  278. context.content = content
  279. reply = super().build_reply_content(context.content, context)
  280. if reply.type == ReplyType.TEXT:
  281. if conf().get('voice_reply_voice'):
  282. reply = super().build_text_to_voice(reply.content)
  283. else:
  284. logger.error('[WX] unknown context type: {}'.format(context.type))
  285. return
  286. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  287. # reply的包装步骤
  288. if reply and reply.type:
  289. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {
  290. 'channel': self, 'context': context, 'reply': reply}))
  291. reply = e_context['reply']
  292. if not e_context.is_pass() and reply and reply.type:
  293. if reply.type == ReplyType.TEXT:
  294. reply_text = reply.content
  295. if context['isgroup']:
  296. reply_text = '@' + context['msg']['ActualNickName'] + ' ' + reply_text.strip()
  297. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  298. else:
  299. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  300. reply.content = reply_text
  301. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  302. reply.content = str(reply.type)+":\n" + reply.content
  303. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  304. pass
  305. else:
  306. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  307. return
  308. # reply的发送步骤
  309. if reply and reply.type:
  310. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {
  311. 'channel': self, 'context': context, 'reply': reply}))
  312. reply = e_context['reply']
  313. if not e_context.is_pass() and reply and reply.type:
  314. logger.debug('[WX] ready to send reply: {} to {}'.format(reply, context['receiver']))
  315. self.send(reply, context['receiver'])
  316. def check_prefix(content, prefix_list):
  317. for prefix in prefix_list:
  318. if content.startswith(prefix):
  319. return prefix
  320. return None
  321. def check_contain(content, keyword_list):
  322. if not keyword_list:
  323. return None
  324. for ky in keyword_list:
  325. if content.find(ky) != -1:
  326. return True
  327. return None