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.

215 lines
7.9KB

  1. # encoding:utf-8
  2. """
  3. wechat channel
  4. """
  5. import os
  6. import itchat
  7. import json
  8. from itchat.content import *
  9. from channel.channel import Channel
  10. from concurrent.futures import ThreadPoolExecutor
  11. from common.log import logger
  12. from config import conf
  13. import requests
  14. import io
  15. thread_pool = ThreadPoolExecutor(max_workers=8)
  16. @itchat.msg_register(TEXT)
  17. def handler_single_msg(msg):
  18. WechatChannel().handle_text(msg)
  19. return None
  20. @itchat.msg_register(TEXT, isGroupChat=True)
  21. def handler_group_msg(msg):
  22. WechatChannel().handle_group(msg)
  23. return None
  24. @itchat.msg_register(VOICE)
  25. def handler_single_voice(msg):
  26. WechatChannel().handle_voice(msg)
  27. return None
  28. class WechatChannel(Channel):
  29. tmpFilePath = './tmp/'
  30. def __init__(self):
  31. isExists = os.path.exists(self.tmpFilePath)
  32. if not isExists:
  33. os.makedirs(self.tmpFilePath)
  34. def startup(self):
  35. # login by scan QRCode
  36. itchat.auto_login(enableCmdQR=2)
  37. # start message listener
  38. itchat.run()
  39. def handle_voice(self, msg):
  40. if conf().get('speech_recognition') != True :
  41. return
  42. logger.debug("[WX]receive voice msg: " + msg['FileName'])
  43. thread_pool.submit(self._do_handle_voice, msg)
  44. def _do_handle_voice(self, msg):
  45. fileName = self.tmpFilePath+msg['FileName']
  46. msg.download(fileName)
  47. content = super().build_voice_to_text(fileName)
  48. self._handle_single_msg(msg, content, False)
  49. def handle_text(self, msg):
  50. logger.debug("[WX]receive text msg: " + json.dumps(msg, ensure_ascii=False))
  51. content = msg['Text']
  52. self._handle_single_msg(msg, content, False)
  53. def _handle_single_msg(self, msg, content, is_voice):
  54. from_user_id = msg['FromUserName']
  55. to_user_id = msg['ToUserName'] # 接收人id
  56. other_user_id = msg['User']['UserName'] # 对手方id
  57. match_prefix = self.check_prefix(content, conf().get('single_chat_prefix'))
  58. if "」\n- - - - - - - - - - - - - - -" in content:
  59. logger.debug("[WX]reference query skipped")
  60. return
  61. if from_user_id == other_user_id and match_prefix is not None:
  62. # 好友向自己发送消息
  63. if match_prefix != '':
  64. str_list = content.split(match_prefix, 1)
  65. if len(str_list) == 2:
  66. content = str_list[1].strip()
  67. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  68. if img_match_prefix:
  69. content = content.split(img_match_prefix, 1)[1].strip()
  70. thread_pool.submit(self._do_send_img, content, from_user_id)
  71. elif is_voice:
  72. thread_pool.submit(self._do_send_voice, content, from_user_id)
  73. else :
  74. thread_pool.submit(self._do_send_text, content, from_user_id)
  75. elif to_user_id == other_user_id and match_prefix:
  76. # 自己给好友发送消息
  77. str_list = content.split(match_prefix, 1)
  78. if len(str_list) == 2:
  79. content = str_list[1].strip()
  80. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  81. if img_match_prefix:
  82. content = content.split(img_match_prefix, 1)[1].strip()
  83. thread_pool.submit(self._do_send_img, content, to_user_id)
  84. elif is_voice:
  85. thread_pool.submit(self._do_send_voice, content, to_user_id)
  86. else:
  87. thread_pool.submit(self._do_send_text, content, to_user_id)
  88. def handle_group(self, msg):
  89. logger.debug("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  90. group_name = msg['User'].get('NickName', None)
  91. group_id = msg['User'].get('UserName', None)
  92. if not group_name:
  93. return ""
  94. origin_content = msg['Content']
  95. content = msg['Content']
  96. content_list = content.split(' ', 1)
  97. context_special_list = content.split('\u2005', 1)
  98. if len(context_special_list) == 2:
  99. content = context_special_list[1]
  100. elif len(content_list) == 2:
  101. content = content_list[1]
  102. if "」\n- - - - - - - - - - - - - - -" in content:
  103. logger.debug("[WX]reference query skipped")
  104. return ""
  105. config = conf()
  106. match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or self.check_prefix(origin_content, config.get('group_chat_prefix')) \
  107. or self.check_contain(origin_content, config.get('group_chat_keyword'))
  108. if ('ALL_GROUP' in config.get('group_name_white_list') or group_name in config.get('group_name_white_list') or self.check_contain(group_name, config.get('group_name_keyword_white_list'))) and match_prefix:
  109. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  110. if img_match_prefix:
  111. content = content.split(img_match_prefix, 1)[1].strip()
  112. thread_pool.submit(self._do_send_img, content, group_id)
  113. else:
  114. thread_pool.submit(self._do_send_group, content, msg)
  115. def send(self, msg, receiver):
  116. itchat.send(msg, toUserName=receiver)
  117. logger.info('[WX] sendMsg={}, receiver={}'.format(msg, receiver))
  118. def _do_send_voice(self, query, reply_user_id):
  119. try:
  120. if not query:
  121. return
  122. context = dict()
  123. context['from_user_id'] = reply_user_id
  124. reply_text = super().build_reply_content(query, context)
  125. if reply_text:
  126. replyFile = super().build_text_to_voice(reply_text)
  127. itchat.send_file(replyFile, toUserName=reply_user_id)
  128. logger.info('[WX] sendFile={}, receiver={}'.format(replyFile, reply_user_id))
  129. except Exception as e:
  130. logger.exception(e)
  131. def _do_send_text(self, query, reply_user_id):
  132. try:
  133. if not query:
  134. return
  135. context = dict()
  136. context['from_user_id'] = reply_user_id
  137. reply_text = super().build_reply_content(query, context)
  138. if reply_text:
  139. self.send(conf().get("single_chat_reply_prefix") + reply_text, reply_user_id)
  140. except Exception as e:
  141. logger.exception(e)
  142. def _do_send_img(self, query, reply_user_id):
  143. try:
  144. if not query:
  145. return
  146. context = dict()
  147. context['type'] = 'IMAGE_CREATE'
  148. img_url = super().build_reply_content(query, context)
  149. if not img_url:
  150. return
  151. # 图片下载
  152. pic_res = requests.get(img_url, stream=True)
  153. image_storage = io.BytesIO()
  154. for block in pic_res.iter_content(1024):
  155. image_storage.write(block)
  156. image_storage.seek(0)
  157. # 图片发送
  158. itchat.send_image(image_storage, reply_user_id)
  159. logger.info('[WX] sendImage, receiver={}'.format(reply_user_id))
  160. except Exception as e:
  161. logger.exception(e)
  162. def _do_send_group(self, query, msg):
  163. if not query:
  164. return
  165. context = dict()
  166. context['from_user_id'] = msg['ActualUserName']
  167. reply_text = super().build_reply_content(query, context)
  168. if reply_text:
  169. reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text.strip()
  170. self.send(conf().get("group_chat_reply_prefix", "") + reply_text, msg['User']['UserName'])
  171. def check_prefix(self, content, prefix_list):
  172. for prefix in prefix_list:
  173. if content.startswith(prefix):
  174. return prefix
  175. return None
  176. def check_contain(self, content, keyword_list):
  177. if not keyword_list:
  178. return None
  179. for ky in keyword_list:
  180. if content.find(ky) != -1:
  181. return True
  182. return None