Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

83 lignes
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. thead_pool = ThreadPoolExecutor(max_workers=8)
  10. @itchat.msg_register(TEXT)
  11. def handler_single_msg(msg):
  12. WechatChannel().handle(msg)
  13. @itchat.msg_register(TEXT, isGroupChat=True)
  14. def handler_group_msg(msg):
  15. WechatChannel().handle_group(msg)
  16. class WechatChannel(Channel):
  17. def __init__(self):
  18. pass
  19. def startup(self):
  20. # login by scan QRCode
  21. itchat.auto_login(enableCmdQR=2)
  22. # start message listener
  23. itchat.run()
  24. def handle(self, msg):
  25. print("[WX]receive msg: " + json.dumps(msg, ensure_ascii=False))
  26. from_user_id = msg['FromUserName']
  27. other_user_id = msg['User']['UserName']
  28. content = msg['Text']
  29. if from_user_id == other_user_id and (content.lower().startswith('bot') or content.lower().startswith('@bot')):
  30. str_list = content.split('bot', 1)
  31. if len(str_list) == 2:
  32. content = str_list[1].strip()
  33. thead_pool.submit(self._do_send, content, from_user_id)
  34. def handle_group(self, msg):
  35. group_white_list = ['学就完事了', '小宝群', '全天乱斗模式', '戒赌吧', '命苦还要快乐','攒钱让姐妹当小三的组织']
  36. print("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
  37. group_id = msg['User']['UserName']
  38. group_name = msg['User'].get('NickName', None)
  39. if not group_name:
  40. return ""
  41. origin_content = msg['Content']
  42. content = msg['Content']
  43. content_list = content.split(' ', 1)
  44. context_special_list = content.split('\u2005', 1)
  45. if len(context_special_list) == 2:
  46. content = context_special_list[1]
  47. elif len(content_list) == 2:
  48. content = content_list[1]
  49. if group_name in group_white_list and (msg['IsAt'] or origin_content.lower().startswith('@bot')):
  50. thead_pool.submit(self._do_send_group, content, msg)
  51. def send(self, msg, receiver):
  52. # time.sleep(random.randint(1, 3))
  53. print('[WX] sendMsg={}, receiver={}'.format(msg, receiver))
  54. itchat.send(msg, toUserName=receiver)
  55. def _do_send(self, send_msg, reply_user_id):
  56. context = dict()
  57. context['from_user_id'] = reply_user_id
  58. content = super().build_reply_content(send_msg, context)
  59. if content:
  60. self.send("[bot] " + content, reply_user_id)
  61. def _do_send_group(self, content, msg):
  62. context = dict()
  63. context['from_user_id'] = msg['ActualUserName']
  64. reply_text = super().build_reply_content(content, context)
  65. reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text
  66. if reply_text:
  67. self.send(reply_text, msg['User']['UserName'])