Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

357 lignes
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. 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. self.userName = None
  46. self.nickName = None
  47. def startup(self):
  48. itchat.instance.receivingRetryCount = 600 # 修改断线超时时间
  49. # login by scan QRCode
  50. hotReload = conf().get('hot_reload', False)
  51. try:
  52. itchat.auto_login(enableCmdQR=2, hotReload=hotReload)
  53. except Exception as e:
  54. if hotReload:
  55. logger.error("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. self.userName = itchat.instance.storageClass.userName
  62. self.nickName = itchat.instance.storageClass.nickName
  63. logger.info("Wechat login success, username: {}, nickname: {}".format(self.userName, self.nickName))
  64. # start message listener
  65. itchat.run()
  66. # handle_* 系列函数处理收到的消息后构造Context,然后传入handle函数中处理Context和发送回复
  67. # Context包含了消息的所有信息,包括以下属性
  68. # type 消息类型, 包括TEXT、VOICE、IMAGE_CREATE
  69. # content 消息内容,如果是TEXT类型,content就是文本内容,如果是VOICE类型,content就是语音文件名,如果是IMAGE_CREATE类型,content就是图片生成命令
  70. # kwargs 附加参数字典,包含以下的key:
  71. # session_id: 会话id
  72. # isgroup: 是否是群聊
  73. # receiver: 需要回复的对象
  74. # msg: itchat的原始消息对象
  75. def handle_voice(self, msg):
  76. if conf().get('speech_recognition') != True:
  77. return
  78. logger.debug("[WX]receive voice msg: " + msg['FileName'])
  79. to_user_id = msg['ToUserName']
  80. from_user_id = msg['FromUserName']
  81. try:
  82. other_user_id = msg['User']['UserName'] # 对手方id
  83. except Exception as e:
  84. logger.warn("[WX]get other_user_id failed: " + str(e))
  85. if from_user_id == self.userName:
  86. other_user_id = to_user_id
  87. else:
  88. other_user_id = from_user_id
  89. if from_user_id == other_user_id:
  90. context = Context(ContextType.VOICE,msg['FileName'])
  91. context.kwargs = {'isgroup': False, 'msg': msg, 'receiver': other_user_id, 'session_id': other_user_id}
  92. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  93. @time_checker
  94. def handle_text(self, msg):
  95. logger.debug("[WX]receive text msg: " + json.dumps(msg, ensure_ascii=False))
  96. content = msg['Text']
  97. from_user_id = msg['FromUserName']
  98. to_user_id = msg['ToUserName'] # 接收人id
  99. try:
  100. other_user_id = msg['User']['UserName'] # 对手方id
  101. except Exception as e:
  102. logger.warn("[WX]get other_user_id failed: " + str(e))
  103. if from_user_id == self.userName:
  104. other_user_id = to_user_id
  105. else:
  106. other_user_id = from_user_id
  107. create_time = msg['CreateTime'] # 消息时间
  108. match_prefix = check_prefix(content, conf().get('single_chat_prefix'))
  109. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息
  110. logger.debug("[WX]history message skipped")
  111. return
  112. if "」\n- - - - - - - - - - - - - - -" in content:
  113. logger.debug("[WX]reference query skipped")
  114. return
  115. if match_prefix:
  116. content = content.replace(match_prefix, '', 1).strip()
  117. elif match_prefix is None:
  118. return
  119. context = Context()
  120. context.kwargs = {'isgroup': False, 'msg': msg,
  121. 'receiver': other_user_id, 'session_id': other_user_id}
  122. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  123. if img_match_prefix:
  124. content = content.replace(img_match_prefix, '', 1).strip()
  125. context.type = ContextType.IMAGE_CREATE
  126. else:
  127. context.type = ContextType.TEXT
  128. context.content = content
  129. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  130. @time_checker
  131. def handle_group(self, msg):
  132. logger.debug("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  133. group_name = msg['User'].get('NickName', None)
  134. group_id = msg['User'].get('UserName', None)
  135. create_time = msg['CreateTime'] # 消息时间
  136. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息
  137. logger.debug("[WX]history group message skipped")
  138. return
  139. if not group_name:
  140. return ""
  141. origin_content = msg['Content']
  142. content = msg['Content']
  143. content_list = content.split(' ', 1)
  144. context_special_list = content.split('\u2005', 1)
  145. if len(context_special_list) == 2:
  146. content = context_special_list[1]
  147. elif len(content_list) == 2:
  148. content = content_list[1]
  149. if "」\n- - - - - - - - - - - - - - -" in content:
  150. logger.debug("[WX]reference query skipped")
  151. return ""
  152. config = conf()
  153. match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or check_prefix(origin_content, config.get('group_chat_prefix')) \
  154. or check_contain(origin_content, config.get('group_chat_keyword'))
  155. 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:
  156. context = Context()
  157. context.kwargs = { 'isgroup': True, 'msg': msg, 'receiver': group_id}
  158. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  159. if img_match_prefix:
  160. content = content.replace(img_match_prefix, '', 1).strip()
  161. context.type = ContextType.IMAGE_CREATE
  162. else:
  163. context.type = ContextType.TEXT
  164. context.content = content
  165. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  166. if ('ALL_GROUP' in group_chat_in_one_session or
  167. group_name in group_chat_in_one_session or
  168. check_contain(group_name, group_chat_in_one_session)):
  169. context['session_id'] = group_id
  170. else:
  171. context['session_id'] = msg['ActualUserName']
  172. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  173. def handle_group_voice(self, msg):
  174. if conf().get('group_speech_recognition', False) != True:
  175. return
  176. logger.debug("[WX]receive voice for group msg: " + msg['FileName'])
  177. group_name = msg['User'].get('NickName', None)
  178. group_id = msg['User'].get('UserName', None)
  179. create_time = msg['CreateTime'] # 消息时间
  180. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: #跳过1分钟前的历史消息
  181. logger.debug("[WX]history group voice skipped")
  182. return
  183. # 验证群名
  184. if not group_name:
  185. return ""
  186. 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'))):
  187. context = Context(ContextType.VOICE,msg['FileName'])
  188. context.kwargs = {'isgroup': True, 'msg': msg, 'receiver': group_id}
  189. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  190. if ('ALL_GROUP' in group_chat_in_one_session or
  191. group_name in group_chat_in_one_session or
  192. check_contain(group_name, group_chat_in_one_session)):
  193. context['session_id'] = group_id
  194. else:
  195. context['session_id'] = msg['ActualUserName']
  196. thread_pool.submit(self.handle, context).add_done_callback(thread_pool_callback)
  197. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  198. def send(self, reply: Reply, receiver):
  199. if reply.type == ReplyType.TEXT:
  200. itchat.send(reply.content, toUserName=receiver)
  201. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  202. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  203. itchat.send(reply.content, toUserName=receiver)
  204. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  205. elif reply.type == ReplyType.VOICE:
  206. itchat.send_file(reply.content, toUserName=receiver)
  207. logger.info('[WX] sendFile={}, receiver={}'.format(reply.content, receiver))
  208. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  209. img_url = reply.content
  210. pic_res = requests.get(img_url, stream=True)
  211. image_storage = io.BytesIO()
  212. for block in pic_res.iter_content(1024):
  213. image_storage.write(block)
  214. image_storage.seek(0)
  215. itchat.send_image(image_storage, toUserName=receiver)
  216. logger.info('[WX] sendImage url={}, receiver={}'.format(img_url,receiver))
  217. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  218. image_storage = reply.content
  219. image_storage.seek(0)
  220. itchat.send_image(image_storage, toUserName=receiver)
  221. logger.info('[WX] sendImage, receiver={}'.format(receiver))
  222. # 处理消息 TODO: 如果wechaty解耦,此处逻辑可以放置到父类
  223. def handle(self, context):
  224. if not context.content:
  225. return
  226. reply = Reply()
  227. logger.debug('[WX] ready to handle context: {}'.format(context))
  228. # reply的构建步骤
  229. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {
  230. 'channel': self, 'context': context, 'reply': reply}))
  231. reply = e_context['reply']
  232. if not e_context.is_pass():
  233. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  234. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  235. reply = super().build_reply_content(context.content, context)
  236. elif context.type == ContextType.VOICE: # 语音消息
  237. msg = context['msg']
  238. mp3_path = TmpDir().path() + context.content
  239. msg.download(mp3_path)
  240. # mp3转wav
  241. wav_path = os.path.splitext(mp3_path)[0] + '.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