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 18KB

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