Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

195 lines
7.0KB

  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. fileName = msg['FileName']
  44. msg.download(self.tmpFilePath+fileName)
  45. content = super().build_void_text(self.tmpFilePath+fileName)
  46. self._handle_single_msg(msg, content)
  47. def handle_text(self, msg):
  48. logger.debug("[WX]receive text msg: " + json.dumps(msg, ensure_ascii=False))
  49. content = msg['Text']
  50. self._handle_single_msg(msg, content)
  51. def _handle_single_msg(self, msg, content):
  52. from_user_id = msg['FromUserName']
  53. to_user_id = msg['ToUserName'] # 接收人id
  54. other_user_id = msg['User']['UserName'] # 对手方id
  55. match_prefix = self.check_prefix(content, conf().get('single_chat_prefix'))
  56. if "」\n- - - - - - - - - - - - - - -" in content:
  57. logger.debug("[WX]reference query skipped")
  58. return
  59. if from_user_id == other_user_id and match_prefix is not None:
  60. # 好友向自己发送消息
  61. if match_prefix != '':
  62. str_list = content.split(match_prefix, 1)
  63. if len(str_list) == 2:
  64. content = str_list[1].strip()
  65. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  66. if img_match_prefix:
  67. content = content.split(img_match_prefix, 1)[1].strip()
  68. thread_pool.submit(self._do_send_img, content, from_user_id)
  69. else:
  70. thread_pool.submit(self._do_send, content, from_user_id)
  71. elif to_user_id == other_user_id and match_prefix:
  72. # 自己给好友发送消息
  73. str_list = content.split(match_prefix, 1)
  74. if len(str_list) == 2:
  75. content = str_list[1].strip()
  76. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  77. if img_match_prefix:
  78. content = content.split(img_match_prefix, 1)[1].strip()
  79. thread_pool.submit(self._do_send_img, content, to_user_id)
  80. else:
  81. thread_pool.submit(self._do_send, content, to_user_id)
  82. def handle_group(self, msg):
  83. logger.debug("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  84. group_name = msg['User'].get('NickName', None)
  85. group_id = msg['User'].get('UserName', None)
  86. if not group_name:
  87. return ""
  88. origin_content = msg['Content']
  89. content = msg['Content']
  90. content_list = content.split(' ', 1)
  91. context_special_list = content.split('\u2005', 1)
  92. if len(context_special_list) == 2:
  93. content = context_special_list[1]
  94. elif len(content_list) == 2:
  95. content = content_list[1]
  96. if "」\n- - - - - - - - - - - - - - -" in content:
  97. logger.debug("[WX]reference query skipped")
  98. return ""
  99. config = conf()
  100. match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or self.check_prefix(origin_content, config.get('group_chat_prefix')) \
  101. or self.check_contain(origin_content, config.get('group_chat_keyword'))
  102. 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:
  103. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  104. if img_match_prefix:
  105. content = content.split(img_match_prefix, 1)[1].strip()
  106. thread_pool.submit(self._do_send_img, content, group_id)
  107. else:
  108. thread_pool.submit(self._do_send_group, content, msg)
  109. def send(self, msg, receiver):
  110. logger.info('[WX] sendMsg={}, receiver={}'.format(msg, receiver))
  111. itchat.send(msg, toUserName=receiver)
  112. def _do_send(self, query, reply_user_id):
  113. try:
  114. if not query:
  115. return
  116. context = dict()
  117. context['from_user_id'] = reply_user_id
  118. reply_text = super().build_reply_content(query, context)
  119. if reply_text:
  120. self.send(conf().get("single_chat_reply_prefix") + reply_text, reply_user_id)
  121. except Exception as e:
  122. logger.exception(e)
  123. def _do_send_img(self, query, reply_user_id):
  124. try:
  125. if not query:
  126. return
  127. context = dict()
  128. context['type'] = 'IMAGE_CREATE'
  129. img_url = super().build_reply_content(query, context)
  130. if not img_url:
  131. return
  132. # 图片下载
  133. pic_res = requests.get(img_url, stream=True)
  134. image_storage = io.BytesIO()
  135. for block in pic_res.iter_content(1024):
  136. image_storage.write(block)
  137. image_storage.seek(0)
  138. # 图片发送
  139. logger.info('[WX] sendImage, receiver={}'.format(reply_user_id))
  140. itchat.send_image(image_storage, reply_user_id)
  141. except Exception as e:
  142. logger.exception(e)
  143. def _do_send_group(self, query, msg):
  144. if not query:
  145. return
  146. context = dict()
  147. context['from_user_id'] = msg['ActualUserName']
  148. reply_text = super().build_reply_content(query, context)
  149. if reply_text:
  150. reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text.strip()
  151. self.send(conf().get("group_chat_reply_prefix", "") + reply_text, msg['User']['UserName'])
  152. def check_prefix(self, content, prefix_list):
  153. for prefix in prefix_list:
  154. if content.startswith(prefix):
  155. return prefix
  156. return None
  157. def check_contain(self, content, keyword_list):
  158. if not keyword_list:
  159. return None
  160. for ky in keyword_list:
  161. if content.find(ky) != -1:
  162. return True
  163. return None