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.

wechat_channel.py 3.5KB

2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
2 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. from config import conf
  11. thead_pool = ThreadPoolExecutor(max_workers=8)
  12. @itchat.msg_register(TEXT)
  13. def handler_single_msg(msg):
  14. WechatChannel().handle(msg)
  15. @itchat.msg_register(TEXT, isGroupChat=True)
  16. def handler_group_msg(msg):
  17. WechatChannel().handle_group(msg)
  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. to_user_id = msg['ToUserName']
  30. other_user_id = msg['User']['UserName']
  31. content = msg['Text']
  32. if from_user_id == other_user_id and \
  33. self.check_prefix(content, conf().get('single_chat_prefix')):
  34. str_list = content.split('bot', 1)
  35. if len(str_list) == 2:
  36. content = str_list[1].strip()
  37. thead_pool.submit(self._do_send, content, from_user_id)
  38. elif to_user_id == other_user_id and \
  39. self.check_prefix(content, conf().get('single_chat_prefix')):
  40. str_list = content.split('bot', 1)
  41. if len(str_list) == 2:
  42. content = str_list[1].strip()
  43. thead_pool.submit(self._do_send, content, to_user_id)
  44. def handle_group(self, msg):
  45. logger.info("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  46. group_name = msg['User'].get('NickName', None)
  47. if not group_name:
  48. return ""
  49. origin_content = msg['Content']
  50. content = msg['Content']
  51. content_list = content.split(' ', 1)
  52. context_special_list = content.split('\u2005', 1)
  53. if len(context_special_list) == 2:
  54. content = context_special_list[1]
  55. elif len(content_list) == 2:
  56. content = content_list[1]
  57. config = conf()
  58. if group_name in config.get('group_name_white_list') \
  59. and (msg['IsAt'] or self.check_prefix(origin_content, config.get('group_chat_prefix'))):
  60. thead_pool.submit(self._do_send_group, content, msg)
  61. def send(self, msg, receiver):
  62. # time.sleep(random.randint(1, 3))
  63. logger.info('[WX] sendMsg={}, receiver={}'.format(msg, receiver))
  64. itchat.send(msg, toUserName=receiver)
  65. def _do_send(self, query, reply_user_id):
  66. if not query:
  67. return
  68. context = dict()
  69. context['from_user_id'] = reply_user_id
  70. reply_text = super().build_reply_content(query, context).strip()
  71. if reply_text:
  72. self.send(conf().get("single_chat_reply_prefix") + reply_text, reply_user_id)
  73. def _do_send_group(self, query, msg):
  74. if not query:
  75. return
  76. context = dict()
  77. context['from_user_id'] = msg['ActualUserName']
  78. reply_text = super().build_reply_content(query, context)
  79. reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text.strip()
  80. if reply_text:
  81. self.send(reply_text, msg['User']['UserName'])
  82. def check_prefix(self, content, prefix_list):
  83. for prefix in prefix_list:
  84. if content.lower().startswith(prefix):
  85. return True
  86. return False