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.

237 lines
8.9KB

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