Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

176 lines
7.3KB

  1. # encoding:utf-8
  2. """
  3. wechat channel
  4. """
  5. import os
  6. import threading
  7. import requests
  8. import io
  9. import time
  10. import json
  11. from channel.chat_channel import ChatChannel
  12. from channel.wechat.wechat_message import *
  13. from common.singleton import singleton
  14. from common.log import logger
  15. from lib import itchat
  16. from lib.itchat.content import *
  17. from bridge.reply import *
  18. from bridge.context import *
  19. from config import conf
  20. from common.time_check import time_checker
  21. from common.expired_dict import ExpiredDict
  22. from plugins import *
  23. @itchat.msg_register([TEXT,VOICE])
  24. def handler_single_msg(msg):
  25. WechatChannel().handle_single(WeChatMessage(msg))
  26. return None
  27. @itchat.msg_register([TEXT,VOICE], isGroupChat=True)
  28. def handler_group_msg(msg):
  29. WechatChannel().handle_group(WeChatMessage(msg,True))
  30. return None
  31. def _check(func):
  32. def wrapper(self, cmsg: ChatMessage):
  33. msgId = cmsg.msg_id
  34. if msgId in self.receivedMsgs:
  35. logger.info("Wechat message {} already received, ignore".format(msgId))
  36. return
  37. self.receivedMsgs[msgId] = cmsg
  38. create_time = cmsg.create_time # 消息时间戳
  39. if conf().get('hot_reload') == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息
  40. logger.debug("[WX]history message {} skipped".format(msgId))
  41. return
  42. return func(self, cmsg)
  43. return wrapper
  44. #可用的二维码生成接口
  45. #https://api.qrserver.com/v1/create-qr-code/?size=400×400&data=https://www.abc.com
  46. #https://api.isoyu.com/qr/?m=1&e=L&p=20&url=https://www.abc.com
  47. def qrCallback(uuid,status,qrcode):
  48. # logger.debug("qrCallback: {} {}".format(uuid,status))
  49. if status == '0':
  50. try:
  51. from PIL import Image
  52. img = Image.open(io.BytesIO(qrcode))
  53. _thread = threading.Thread(target=img.show, args=("QRCode",))
  54. _thread.setDaemon(True)
  55. _thread.start()
  56. except Exception as e:
  57. pass
  58. import qrcode
  59. url = f"https://login.weixin.qq.com/l/{uuid}"
  60. qr_api1="https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url)
  61. qr_api2="https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(url)
  62. qr_api3="https://api.pwmqr.com/qrcode/create/?url={}".format(url)
  63. qr_api4="https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}".format(url)
  64. print("You can also scan QRCode in any website below:")
  65. print(qr_api3)
  66. print(qr_api4)
  67. print(qr_api2)
  68. print(qr_api1)
  69. qr = qrcode.QRCode(border=1)
  70. qr.add_data(url)
  71. qr.make(fit=True)
  72. qr.print_ascii(invert=True)
  73. @singleton
  74. class WechatChannel(ChatChannel):
  75. NOT_SUPPORT_REPLYTYPE = []
  76. def __init__(self):
  77. super().__init__()
  78. self.receivedMsgs = ExpiredDict(60*60*24)
  79. def startup(self):
  80. itchat.instance.receivingRetryCount = 600 # 修改断线超时时间
  81. # login by scan QRCode
  82. hotReload = conf().get('hot_reload', False)
  83. try:
  84. itchat.auto_login(enableCmdQR=2, hotReload=hotReload, qrCallback=qrCallback)
  85. except Exception as e:
  86. if hotReload:
  87. logger.error("Hot reload failed, try to login without hot reload")
  88. itchat.logout()
  89. os.remove("itchat.pkl")
  90. itchat.auto_login(enableCmdQR=2, hotReload=hotReload, qrCallback=qrCallback)
  91. else:
  92. raise e
  93. self.user_id = itchat.instance.storageClass.userName
  94. self.name = itchat.instance.storageClass.nickName
  95. logger.info("Wechat login success, user_id: {}, nickname: {}".format(self.user_id, self.name))
  96. # start message listener
  97. itchat.run()
  98. # handle_* 系列函数处理收到的消息后构造Context,然后传入produce函数中处理Context和发送回复
  99. # Context包含了消息的所有信息,包括以下属性
  100. # type 消息类型, 包括TEXT、VOICE、IMAGE_CREATE
  101. # content 消息内容,如果是TEXT类型,content就是文本内容,如果是VOICE类型,content就是语音文件名,如果是IMAGE_CREATE类型,content就是图片生成命令
  102. # kwargs 附加参数字典,包含以下的key:
  103. # session_id: 会话id
  104. # isgroup: 是否是群聊
  105. # receiver: 需要回复的对象
  106. # msg: ChatMessage消息对象
  107. # origin_ctype: 原始消息类型,语音转文字后,私聊时如果匹配前缀失败,会根据初始消息是否是语音来放宽触发规则
  108. # desire_rtype: 希望回复类型,默认是文本回复,设置为ReplyType.VOICE是语音回复
  109. @time_checker
  110. @_check
  111. def handle_single(self, cmsg : ChatMessage):
  112. if cmsg.ctype == ContextType.VOICE:
  113. if conf().get('speech_recognition') != True:
  114. return
  115. logger.debug("[WX]receive voice msg: {}".format(cmsg.content))
  116. else:
  117. logger.debug("[WX]receive text msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
  118. context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=False, msg=cmsg)
  119. if context:
  120. self.produce(context)
  121. @time_checker
  122. @_check
  123. def handle_group(self, cmsg : ChatMessage):
  124. if cmsg.ctype == ContextType.VOICE:
  125. if conf().get('speech_recognition') != True:
  126. return
  127. logger.debug("[WX]receive voice for group msg: {}".format(cmsg.content))
  128. else:
  129. # logger.debug("[WX]receive group msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
  130. pass
  131. context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=True, msg=cmsg)
  132. if context:
  133. self.produce(context)
  134. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  135. def send(self, reply: Reply, context: Context):
  136. receiver = context["receiver"]
  137. if reply.type == ReplyType.TEXT:
  138. itchat.send(reply.content, toUserName=receiver)
  139. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  140. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  141. itchat.send(reply.content, toUserName=receiver)
  142. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  143. elif reply.type == ReplyType.VOICE:
  144. itchat.send_file(reply.content, toUserName=receiver)
  145. logger.info('[WX] sendFile={}, receiver={}'.format(reply.content, receiver))
  146. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  147. img_url = reply.content
  148. pic_res = requests.get(img_url, stream=True)
  149. image_storage = io.BytesIO()
  150. for block in pic_res.iter_content(1024):
  151. image_storage.write(block)
  152. image_storage.seek(0)
  153. itchat.send_image(image_storage, toUserName=receiver)
  154. logger.info('[WX] sendImage url={}, receiver={}'.format(img_url,receiver))
  155. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  156. image_storage = reply.content
  157. image_storage.seek(0)
  158. itchat.send_image(image_storage, toUserName=receiver)
  159. logger.info('[WX] sendImage, receiver={}'.format(receiver))