Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

wechat_channel.py 8.2KB

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