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.

224 lines
8.2KB

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