You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.8KB

  1. """
  2. wechat channel
  3. """
  4. import itchat
  5. import json
  6. from itchat.content import *
  7. from channel.channel import Channel
  8. from concurrent.futures import ThreadPoolExecutor
  9. from common.log import logger
  10. thead_pool = ThreadPoolExecutor(max_workers=8)
  11. @itchat.msg_register(TEXT)
  12. def handler_single_msg(msg):
  13. WechatChannel().handle(msg)
  14. @itchat.msg_register(TEXT, isGroupChat=True)
  15. def handler_group_msg(msg):
  16. WechatChannel().handle_group(msg)
  17. group_white_list = ['测试群1', '测试群2']
  18. class WechatChannel(Channel):
  19. def __init__(self):
  20. pass
  21. def startup(self):
  22. # login by scan QRCode
  23. itchat.auto_login(enableCmdQR=2)
  24. # start message listener
  25. itchat.run()
  26. def handle(self, msg):
  27. logger.info("[WX]receive msg: " + json.dumps(msg, ensure_ascii=False))
  28. from_user_id = msg['FromUserName']
  29. other_user_id = msg['User']['UserName']
  30. content = msg['Text']
  31. if from_user_id == other_user_id and (content.lower().startswith('bot') or content.lower().startswith('@bot')):
  32. str_list = content.split('bot', 1)
  33. if len(str_list) == 2:
  34. content = str_list[1].strip()
  35. thead_pool.submit(self._do_send, content, from_user_id)
  36. def handle_group(self, msg):
  37. logger.info("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  38. group_id = msg['User']['UserName']
  39. group_name = msg['User'].get('NickName', None)
  40. if not group_name:
  41. return ""
  42. origin_content = msg['Content']
  43. content = msg['Content']
  44. content_list = content.split(' ', 1)
  45. context_special_list = content.split('\u2005', 1)
  46. if len(context_special_list) == 2:
  47. content = context_special_list[1]
  48. elif len(content_list) == 2:
  49. content = content_list[1]
  50. if group_name in group_white_list and (msg['IsAt'] or origin_content.lower().startswith('@bot')):
  51. thead_pool.submit(self._do_send_group, content, msg)
  52. def send(self, msg, receiver):
  53. # time.sleep(random.randint(1, 3))
  54. logger.info('[WX] sendMsg={}, receiver={}'.format(msg, receiver))
  55. itchat.send(msg, toUserName=receiver)
  56. def _do_send(self, send_msg, reply_user_id):
  57. context = dict()
  58. context['from_user_id'] = reply_user_id
  59. content = super().build_reply_content(send_msg, context)
  60. if content:
  61. self.send("[bot] " + content, reply_user_id)
  62. def _do_send_group(self, content, msg):
  63. context = dict()
  64. context['from_user_id'] = msg['ActualUserName']
  65. reply_text = super().build_reply_content(content, context)
  66. reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text
  67. if reply_text:
  68. self.send(reply_text, msg['User']['UserName'])