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.

45 lines
1.2KB

  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. thead_pool = ThreadPoolExecutor(max_workers=8)
  10. @itchat.msg_register([TEXT])
  11. def handler_receive_msg(msg):
  12. WechatChannel().handle(msg)
  13. class WechatChannel(Channel):
  14. def __init__(self):
  15. pass
  16. def startup(self):
  17. # login by scan QRCode
  18. itchat.auto_login(enableCmdQR=2)
  19. # start message listener
  20. itchat.run()
  21. def handle(self, msg):
  22. # print("handle: ", msg)
  23. print("[WX]receive msg: " + json.dumps(msg, ensure_ascii=False))
  24. from_user_id = msg['FromUserName']
  25. other_user_id = msg['User']['UserName']
  26. if from_user_id == other_user_id:
  27. thead_pool.submit(self._do_send, msg['Text'], from_user_id)
  28. def send(self, msg, receiver):
  29. # time.sleep(random.randint(1, 3))
  30. print(msg, receiver)
  31. itchat.send(msg + " [bot]", toUserName=receiver)
  32. def _do_send(self, send_msg, reply_user_id):
  33. context = dict()
  34. context['from_user_id'] = reply_user_id
  35. self.send(super().build_reply_content(send_msg, context), reply_user_id)