Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

293 lines
12KB

  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 import chat_channel
  15. from channel.wechat.wechat_message import *
  16. from common.expired_dict import ExpiredDict
  17. from common.log import logger
  18. from common.singleton import singleton
  19. from common.time_check import time_checker
  20. from common.utils import convert_webp_to_png
  21. from config import conf, get_appdata_dir
  22. from lib import itchat
  23. from lib.itchat.content import *
  24. @itchat.msg_register([TEXT, VOICE, PICTURE, NOTE, ATTACHMENT, SHARING])
  25. def handler_single_msg(msg):
  26. try:
  27. cmsg = WechatMessage(msg, False)
  28. except NotImplementedError as e:
  29. logger.debug("[WX]single message {} skipped: {}".format(msg["MsgId"], e))
  30. return None
  31. WechatChannel().handle_single(cmsg)
  32. return None
  33. @itchat.msg_register([TEXT, VOICE, PICTURE, NOTE, ATTACHMENT, SHARING], isGroupChat=True)
  34. def handler_group_msg(msg):
  35. try:
  36. cmsg = WechatMessage(msg, True)
  37. except NotImplementedError as e:
  38. logger.debug("[WX]group message {} skipped: {}".format(msg["MsgId"], e))
  39. return None
  40. WechatChannel().handle_group(cmsg)
  41. return None
  42. def _check(func):
  43. def wrapper(self, cmsg: ChatMessage):
  44. msgId = cmsg.msg_id
  45. if msgId in self.receivedMsgs:
  46. logger.info("Wechat message {} already received, ignore".format(msgId))
  47. return
  48. self.receivedMsgs[msgId] = True
  49. create_time = cmsg.create_time # 消息时间戳
  50. if conf().get("hot_reload") == True and int(create_time) < int(time.time()) - 60: # 跳过1分钟前的历史消息
  51. logger.debug("[WX]history message {} skipped".format(msgId))
  52. return
  53. if cmsg.my_msg and not cmsg.is_group:
  54. logger.debug("[WX]my message {} skipped".format(msgId))
  55. return
  56. return func(self, cmsg)
  57. return wrapper
  58. # 可用的二维码生成接口
  59. # https://api.qrserver.com/v1/create-qr-code/?size=400×400&data=https://www.abc.com
  60. # https://api.isoyu.com/qr/?m=1&e=L&p=20&url=https://www.abc.com
  61. def qrCallback(uuid, status, qrcode):
  62. # logger.debug("qrCallback: {} {}".format(uuid,status))
  63. if status == "0":
  64. try:
  65. from PIL import Image
  66. img = Image.open(io.BytesIO(qrcode))
  67. _thread = threading.Thread(target=img.show, args=("QRCode",))
  68. _thread.setDaemon(True)
  69. _thread.start()
  70. except Exception as e:
  71. pass
  72. import qrcode
  73. url = f"https://login.weixin.qq.com/l/{uuid}"
  74. qr_api1 = "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url)
  75. qr_api2 = "https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(url)
  76. qr_api3 = "https://api.pwmqr.com/qrcode/create/?url={}".format(url)
  77. qr_api4 = "https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?text={}".format(url)
  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. _send_qr_code([qr_api3, qr_api4, qr_api2, qr_api1])
  84. qr = qrcode.QRCode(border=1)
  85. qr.add_data(url)
  86. qr.make(fit=True)
  87. qr.print_ascii(invert=True)
  88. @singleton
  89. class WechatChannel(ChatChannel):
  90. NOT_SUPPORT_REPLYTYPE = []
  91. def __init__(self):
  92. super().__init__()
  93. self.receivedMsgs = ExpiredDict(conf().get("expires_in_seconds", 3600))
  94. self.auto_login_times = 0
  95. def startup(self):
  96. try:
  97. itchat.instance.receivingRetryCount = 600 # 修改断线超时时间
  98. # login by scan QRCode
  99. hotReload = conf().get("hot_reload", False)
  100. status_path = os.path.join(get_appdata_dir(), "itchat.pkl")
  101. itchat.auto_login(
  102. enableCmdQR=2,
  103. hotReload=hotReload,
  104. statusStorageDir=status_path,
  105. qrCallback=qrCallback,
  106. exitCallback=self.exitCallback,
  107. loginCallback=self.loginCallback
  108. )
  109. self.user_id = itchat.instance.storageClass.userName
  110. self.name = itchat.instance.storageClass.nickName
  111. logger.info("Wechat login success, user_id: {}, nickname: {}".format(self.user_id, self.name))
  112. # start message listener
  113. itchat.run()
  114. except Exception as e:
  115. logger.exception(e)
  116. def exitCallback(self):
  117. try:
  118. from common.linkai_client import chat_client
  119. if chat_client.client_id and conf().get("use_linkai"):
  120. _send_logout()
  121. time.sleep(2)
  122. self.auto_login_times += 1
  123. if self.auto_login_times < 100:
  124. chat_channel.handler_pool._shutdown = False
  125. self.startup()
  126. except Exception as e:
  127. pass
  128. def loginCallback(self):
  129. logger.debug("Login success")
  130. _send_login_success()
  131. # handle_* 系列函数处理收到的消息后构造Context,然后传入produce函数中处理Context和发送回复
  132. # Context包含了消息的所有信息,包括以下属性
  133. # type 消息类型, 包括TEXT、VOICE、IMAGE_CREATE
  134. # content 消息内容,如果是TEXT类型,content就是文本内容,如果是VOICE类型,content就是语音文件名,如果是IMAGE_CREATE类型,content就是图片生成命令
  135. # kwargs 附加参数字典,包含以下的key:
  136. # session_id: 会话id
  137. # isgroup: 是否是群聊
  138. # receiver: 需要回复的对象
  139. # msg: ChatMessage消息对象
  140. # origin_ctype: 原始消息类型,语音转文字后,私聊时如果匹配前缀失败,会根据初始消息是否是语音来放宽触发规则
  141. # desire_rtype: 希望回复类型,默认是文本回复,设置为ReplyType.VOICE是语音回复
  142. @time_checker
  143. @_check
  144. def handle_single(self, cmsg: ChatMessage):
  145. # filter system message
  146. if cmsg.other_user_id in ["weixin"]:
  147. return
  148. if cmsg.ctype == ContextType.VOICE:
  149. if conf().get("speech_recognition") != True:
  150. return
  151. logger.debug("[WX]receive voice msg: {}".format(cmsg.content))
  152. elif cmsg.ctype == ContextType.IMAGE:
  153. logger.debug("[WX]receive image msg: {}".format(cmsg.content))
  154. elif cmsg.ctype == ContextType.PATPAT:
  155. logger.debug("[WX]receive patpat msg: {}".format(cmsg.content))
  156. elif cmsg.ctype == ContextType.TEXT:
  157. logger.debug("[WX]receive text msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
  158. else:
  159. logger.debug("[WX]receive msg: {}, cmsg={}".format(cmsg.content, cmsg))
  160. context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=False, msg=cmsg)
  161. if context:
  162. self.produce(context)
  163. @time_checker
  164. @_check
  165. def handle_group(self, cmsg: ChatMessage):
  166. if cmsg.ctype == ContextType.VOICE:
  167. if conf().get("group_speech_recognition") != True:
  168. return
  169. logger.debug("[WX]receive voice for group msg: {}".format(cmsg.content))
  170. elif cmsg.ctype == ContextType.IMAGE:
  171. logger.debug("[WX]receive image for group msg: {}".format(cmsg.content))
  172. elif cmsg.ctype in [ContextType.JOIN_GROUP, ContextType.PATPAT, ContextType.ACCEPT_FRIEND, ContextType.EXIT_GROUP]:
  173. logger.debug("[WX]receive note msg: {}".format(cmsg.content))
  174. elif cmsg.ctype == ContextType.TEXT:
  175. # logger.debug("[WX]receive group msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
  176. pass
  177. elif cmsg.ctype == ContextType.FILE:
  178. logger.debug(f"[WX]receive attachment msg, file_name={cmsg.content}")
  179. else:
  180. logger.debug("[WX]receive group msg: {}".format(cmsg.content))
  181. context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=True, msg=cmsg, no_need_at=conf().get("no_need_at", False))
  182. if context:
  183. self.produce(context)
  184. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  185. def send(self, reply: Reply, context: Context):
  186. receiver = context["receiver"]
  187. if reply.type == ReplyType.TEXT:
  188. itchat.send(reply.content, toUserName=receiver)
  189. logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
  190. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  191. itchat.send(reply.content, toUserName=receiver)
  192. logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
  193. elif reply.type == ReplyType.VOICE:
  194. itchat.send_file(reply.content, toUserName=receiver)
  195. logger.info("[WX] sendFile={}, receiver={}".format(reply.content, receiver))
  196. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  197. img_url = reply.content
  198. logger.debug(f"[WX] start download image, img_url={img_url}")
  199. pic_res = requests.get(img_url, stream=True)
  200. image_storage = io.BytesIO()
  201. size = 0
  202. for block in pic_res.iter_content(1024):
  203. size += len(block)
  204. image_storage.write(block)
  205. logger.info(f"[WX] download image success, size={size}, img_url={img_url}")
  206. image_storage.seek(0)
  207. if ".webp" in img_url:
  208. try:
  209. image_storage = convert_webp_to_png(image_storage)
  210. except Exception as e:
  211. logger.error(f"Failed to convert image: {e}")
  212. return
  213. itchat.send_image(image_storage, toUserName=receiver)
  214. logger.info("[WX] sendImage url={}, receiver={}".format(img_url, receiver))
  215. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  216. image_storage = reply.content
  217. image_storage.seek(0)
  218. itchat.send_image(image_storage, toUserName=receiver)
  219. logger.info("[WX] sendImage, receiver={}".format(receiver))
  220. elif reply.type == ReplyType.FILE: # 新增文件回复类型
  221. file_storage = reply.content
  222. itchat.send_file(file_storage, toUserName=receiver)
  223. logger.info("[WX] sendFile, receiver={}".format(receiver))
  224. elif reply.type == ReplyType.VIDEO: # 新增视频回复类型
  225. video_storage = reply.content
  226. itchat.send_video(video_storage, toUserName=receiver)
  227. logger.info("[WX] sendFile, receiver={}".format(receiver))
  228. elif reply.type == ReplyType.VIDEO_URL: # 新增视频URL回复类型
  229. video_url = reply.content
  230. logger.debug(f"[WX] start download video, video_url={video_url}")
  231. video_res = requests.get(video_url, stream=True)
  232. video_storage = io.BytesIO()
  233. size = 0
  234. for block in video_res.iter_content(1024):
  235. size += len(block)
  236. video_storage.write(block)
  237. logger.info(f"[WX] download video success, size={size}, video_url={video_url}")
  238. video_storage.seek(0)
  239. itchat.send_video(video_storage, toUserName=receiver)
  240. logger.info("[WX] sendVideo url={}, receiver={}".format(video_url, receiver))
  241. def _send_login_success():
  242. try:
  243. from common.linkai_client import chat_client
  244. if chat_client.client_id:
  245. chat_client.send_login_success()
  246. except Exception as e:
  247. pass
  248. def _send_logout():
  249. try:
  250. from common.linkai_client import chat_client
  251. if chat_client.client_id:
  252. chat_client.send_logout()
  253. except Exception as e:
  254. pass
  255. def _send_qr_code(qrcode_list: list):
  256. try:
  257. from common.linkai_client import chat_client
  258. if chat_client.client_id:
  259. chat_client.send_qrcode(qrcode_list)
  260. except Exception as e:
  261. pass