Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

wechat_channel.py 16KB

2 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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,
  93. 'receiver': other_user_id, 'session_id': other_user_id}
  94. thread_pool.submit(self.handle, context).add_done_callback(
  95. thread_pool_callback)
  96. @time_checker
  97. def handle_text(self, msg):
  98. logger.debug("[WX]receive text msg: " +
  99. json.dumps(msg, ensure_ascii=False))
  100. content = msg['Text']
  101. from_user_id = msg['FromUserName']
  102. to_user_id = msg['ToUserName'] # 接收人id
  103. try:
  104. other_user_id = msg['User']['UserName'] # 对手方id
  105. except Exception as e:
  106. logger.warn("[WX]get other_user_id failed: " + str(e))
  107. if from_user_id == self.userName:
  108. other_user_id = to_user_id
  109. else:
  110. other_user_id = from_user_id
  111. create_time = msg['CreateTime'] # 消息时间
  112. match_prefix = check_prefix(content, conf().get('single_chat_prefix'))
  113. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息
  114. logger.debug("[WX]history message skipped")
  115. return
  116. if "」\n- - - - - - - - - - - - - - -" in content:
  117. logger.debug("[WX]reference query skipped")
  118. return
  119. if match_prefix:
  120. content = content.replace(match_prefix, '', 1).strip()
  121. elif match_prefix is None:
  122. return
  123. context = Context()
  124. context.kwargs = {'isgroup': False, 'msg': msg,
  125. 'receiver': other_user_id, 'session_id': other_user_id}
  126. img_match_prefix = check_prefix(
  127. content, conf().get('image_create_prefix'))
  128. if img_match_prefix:
  129. content = content.replace(img_match_prefix, '', 1).strip()
  130. context.type = ContextType.IMAGE_CREATE
  131. else:
  132. context.type = ContextType.TEXT
  133. context.content = content
  134. thread_pool.submit(self.handle, context).add_done_callback(
  135. thread_pool_callback)
  136. @time_checker
  137. def handle_group(self, msg):
  138. logger.debug("[WX]receive group msg: " +
  139. json.dumps(msg, ensure_ascii=False))
  140. group_name = msg['User'].get('NickName', None)
  141. group_id = msg['User'].get('UserName', None)
  142. create_time = msg['CreateTime'] # 消息时间
  143. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息
  144. logger.debug("[WX]history group message skipped")
  145. return
  146. if not group_name:
  147. return ""
  148. origin_content = msg['Content']
  149. content = msg['Content']
  150. content_list = content.split(' ', 1)
  151. context_special_list = content.split('\u2005', 1)
  152. if len(context_special_list) == 2:
  153. content = context_special_list[1]
  154. elif len(content_list) == 2:
  155. content = content_list[1]
  156. if "」\n- - - - - - - - - - - - - - -" in content:
  157. logger.debug("[WX]reference query skipped")
  158. return ""
  159. config = conf()
  160. match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or check_prefix(origin_content, config.get('group_chat_prefix')) \
  161. or check_contain(origin_content, config.get('group_chat_keyword'))
  162. 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:
  163. context = Context()
  164. context.kwargs = {'isgroup': True,
  165. 'msg': msg, 'receiver': group_id}
  166. img_match_prefix = check_prefix(
  167. content, conf().get('image_create_prefix'))
  168. if img_match_prefix:
  169. content = content.replace(img_match_prefix, '', 1).strip()
  170. context.type = ContextType.IMAGE_CREATE
  171. else:
  172. context.type = ContextType.TEXT
  173. context.content = content
  174. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  175. if ('ALL_GROUP' in group_chat_in_one_session or
  176. group_name in group_chat_in_one_session or
  177. check_contain(group_name, group_chat_in_one_session)):
  178. context['session_id'] = group_id
  179. else:
  180. context['session_id'] = msg['ActualUserName']
  181. thread_pool.submit(self.handle, context).add_done_callback(
  182. thread_pool_callback)
  183. def handle_group_voice(self, msg):
  184. if conf().get('group_speech_recognition') != True:
  185. return
  186. logger.debug("[WX]receive group voice msg: " + msg['FileName'])
  187. group_name = msg['User'].get('NickName', None)
  188. group_id = msg['User'].get('UserName', None)
  189. from_user_id = msg['ActualUserName']
  190. context = Context(ContextType.VOICE, msg['FileName'])
  191. context.kwargs = {'isgroup': True, 'msg': msg,
  192. 'receiver': group_id, 'session_id': from_user_id}
  193. thread_pool.submit(self.handle, context).add_done_callback(
  194. thread_pool_callback)
  195. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  196. def send(self, reply: Reply, receiver):
  197. if reply.type == ReplyType.TEXT:
  198. itchat.send(reply.content, toUserName=receiver)
  199. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  200. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  201. itchat.send(reply.content, toUserName=receiver)
  202. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  203. elif reply.type == ReplyType.VOICE:
  204. itchat.send_file(reply.content, toUserName=receiver)
  205. logger.info('[WX] sendFile={}, receiver={}'.format(
  206. reply.content, receiver))
  207. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  208. img_url = reply.content
  209. pic_res = requests.get(img_url, stream=True)
  210. image_storage = io.BytesIO()
  211. for block in pic_res.iter_content(1024):
  212. image_storage.write(block)
  213. image_storage.seek(0)
  214. itchat.send_image(image_storage, toUserName=receiver)
  215. logger.info('[WX] sendImage url={}, receiver={}'.format(
  216. 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. reply = Reply()
  225. logger.debug('[WX] ready to handle context: {}'.format(context))
  226. # reply的构建步骤
  227. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {
  228. 'channel': self, 'context': context, 'reply': reply}))
  229. reply = e_context['reply']
  230. if not e_context.is_pass():
  231. logger.debug('[WX] ready to handle context: type={}, content={}'.format(
  232. context.type, context.content))
  233. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE:
  234. reply = super().build_reply_content(context.content, context)
  235. elif context.type == ContextType.VOICE:
  236. msg = context['msg']
  237. mp3_path = TmpDir().path() + context.content
  238. msg.download(mp3_path)
  239. # mp3转wav
  240. wav_path = os.path.splitext(mp3_path)[0] + '.wav'
  241. mp3_to_wav(mp3_path=mp3_path, wav_path=wav_path)
  242. # 语音识别
  243. reply = super().build_voice_to_text(wav_path)
  244. # 删除临时文件
  245. os.remove(wav_path)
  246. os.remove(mp3_path)
  247. if reply.type != ReplyType.ERROR and reply.type != ReplyType.INFO:
  248. context.content = reply.content # 语音转文字后,将文字内容作为新的context
  249. context.type = ContextType.TEXT
  250. if (context["isgroup"] == True):
  251. # 校验关键字
  252. match_prefix = self.check_prefix(context.content, conf().get('group_chat_prefix')) \
  253. or self.check_contain(context.content, conf().get('group_chat_keyword'))
  254. # Wechaty判断is_at为True,返回的内容是过滤掉@之后的内容;而is_at为False,则会返回完整的内容
  255. if match_prefix is not None:
  256. # 故判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容,用于实现类似自定义+前缀触发生成AI图片的功能
  257. prefixes = conf().get('group_chat_prefix')
  258. for prefix in prefixes:
  259. if context.content.startswith(prefix):
  260. context.content = context.content.replace(
  261. prefix, '', 1).strip()
  262. break
  263. else:
  264. logger.info("[WX]receive voice check prefix: " + 'False')
  265. return
  266. reply = super().build_reply_content(context.content, context)
  267. if reply.type == ReplyType.TEXT:
  268. if conf().get('voice_reply_voice'):
  269. reply = super().build_text_to_voice(reply.content)
  270. else:
  271. logger.error('[WX] unknown context type: {}'.format(context.type))
  272. return
  273. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  274. # reply的包装步骤
  275. if reply and reply.type:
  276. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {
  277. 'channel': self, 'context': context, 'reply': reply}))
  278. reply = e_context['reply']
  279. if not e_context.is_pass() and reply and reply.type:
  280. if reply.type == ReplyType.TEXT:
  281. reply_text = reply.content
  282. if context['isgroup']:
  283. reply_text = '@' + \
  284. context['msg']['ActualNickName'] + \
  285. ' ' + reply_text.strip()
  286. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  287. else:
  288. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  289. reply.content = reply_text
  290. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  291. reply.content = str(reply.type)+":\n" + reply.content
  292. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  293. pass
  294. else:
  295. logger.error(
  296. '[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(
  305. reply, context['receiver']))
  306. self.send(reply, context['receiver'])
  307. def check_prefix(content, prefix_list):
  308. for prefix in prefix_list:
  309. if content.startswith(prefix):
  310. return prefix
  311. return None
  312. def check_contain(content, keyword_list):
  313. if not keyword_list:
  314. return None
  315. for ky in keyword_list:
  316. if content.find(ky) != -1:
  317. return True
  318. return None