選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

wechat_channel.py 7.7KB

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