選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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