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.

271 satır
11KB

  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, ATTACHMENT, SHARING])
  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, ATTACHMENT, SHARING], 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] = True
  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. if cmsg.my_msg and not cmsg.is_group:
  52. logger.debug("[WX]my message {} skipped".format(msgId))
  53. return
  54. return func(self, cmsg)
  55. return wrapper
  56. # 可用的二维码生成接口
  57. # https://api.qrserver.com/v1/create-qr-code/?size=400×400&data=https://www.abc.com
  58. # https://api.isoyu.com/qr/?m=1&e=L&p=20&url=https://www.abc.com
  59. def qrCallback(uuid, status, qrcode):
  60. # logger.debug("qrCallback: {} {}".format(uuid,status))
  61. if status == "0":
  62. try:
  63. from PIL import Image
  64. img = Image.open(io.BytesIO(qrcode))
  65. _thread = threading.Thread(target=img.show, args=("QRCode",))
  66. _thread.setDaemon(True)
  67. _thread.start()
  68. except Exception as e:
  69. pass
  70. import qrcode
  71. url = f"https://login.weixin.qq.com/l/{uuid}"
  72. qr_api1 = "https://api.isoyu.com/qr/?m=1&e=L&p=20&url={}".format(url)
  73. qr_api2 = "https://api.qrserver.com/v1/create-qr-code/?size=400×400&data={}".format(url)
  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(url)
  76. print("You can also scan QRCode in any website below:")
  77. print(qr_api3)
  78. print(qr_api4)
  79. print(qr_api2)
  80. print(qr_api1)
  81. _send_qr_code([qr_api1, qr_api2, qr_api3, qr_api4])
  82. qr = qrcode.QRCode(border=1)
  83. qr.add_data(url)
  84. qr.make(fit=True)
  85. qr.print_ascii(invert=True)
  86. @singleton
  87. class WechatChannel(ChatChannel):
  88. NOT_SUPPORT_REPLYTYPE = []
  89. def __init__(self):
  90. super().__init__()
  91. self.receivedMsgs = ExpiredDict(60 * 60)
  92. self.auto_login_times = 0
  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. itchat.auto_login(
  99. enableCmdQR=2,
  100. hotReload=hotReload,
  101. statusStorageDir=status_path,
  102. qrCallback=qrCallback,
  103. exitCallback=self.exitCallback,
  104. loginCallback=self.loginCallback
  105. )
  106. self.user_id = itchat.instance.storageClass.userName
  107. self.name = itchat.instance.storageClass.nickName
  108. logger.info("Wechat login success, user_id: {}, nickname: {}".format(self.user_id, self.name))
  109. # start message listener
  110. itchat.run()
  111. def exitCallback(self):
  112. _send_logout()
  113. time.sleep(3)
  114. self.auto_login_times += 1
  115. if self.auto_login_times < 100:
  116. self.startup()
  117. def loginCallback(self):
  118. logger.debug("Login success")
  119. _send_login_success()
  120. # handle_* 系列函数处理收到的消息后构造Context,然后传入produce函数中处理Context和发送回复
  121. # Context包含了消息的所有信息,包括以下属性
  122. # type 消息类型, 包括TEXT、VOICE、IMAGE_CREATE
  123. # content 消息内容,如果是TEXT类型,content就是文本内容,如果是VOICE类型,content就是语音文件名,如果是IMAGE_CREATE类型,content就是图片生成命令
  124. # kwargs 附加参数字典,包含以下的key:
  125. # session_id: 会话id
  126. # isgroup: 是否是群聊
  127. # receiver: 需要回复的对象
  128. # msg: ChatMessage消息对象
  129. # origin_ctype: 原始消息类型,语音转文字后,私聊时如果匹配前缀失败,会根据初始消息是否是语音来放宽触发规则
  130. # desire_rtype: 希望回复类型,默认是文本回复,设置为ReplyType.VOICE是语音回复
  131. @time_checker
  132. @_check
  133. def handle_single(self, cmsg: ChatMessage):
  134. # filter system message
  135. if cmsg.other_user_id in ["weixin"]:
  136. return
  137. if cmsg.ctype == ContextType.VOICE:
  138. if conf().get("speech_recognition") != True:
  139. return
  140. logger.debug("[WX]receive voice msg: {}".format(cmsg.content))
  141. elif cmsg.ctype == ContextType.IMAGE:
  142. logger.debug("[WX]receive image msg: {}".format(cmsg.content))
  143. elif cmsg.ctype == ContextType.PATPAT:
  144. logger.debug("[WX]receive patpat msg: {}".format(cmsg.content))
  145. elif cmsg.ctype == ContextType.TEXT:
  146. logger.debug("[WX]receive text msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
  147. else:
  148. logger.debug("[WX]receive msg: {}, cmsg={}".format(cmsg.content, cmsg))
  149. context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=False, msg=cmsg)
  150. if context:
  151. self.produce(context)
  152. @time_checker
  153. @_check
  154. def handle_group(self, cmsg: ChatMessage):
  155. if cmsg.ctype == ContextType.VOICE:
  156. if conf().get("group_speech_recognition") != True:
  157. return
  158. logger.debug("[WX]receive voice for group msg: {}".format(cmsg.content))
  159. elif cmsg.ctype == ContextType.IMAGE:
  160. logger.debug("[WX]receive image for group msg: {}".format(cmsg.content))
  161. elif cmsg.ctype in [ContextType.JOIN_GROUP, ContextType.PATPAT, ContextType.ACCEPT_FRIEND, ContextType.EXIT_GROUP]:
  162. logger.debug("[WX]receive note msg: {}".format(cmsg.content))
  163. elif cmsg.ctype == ContextType.TEXT:
  164. # logger.debug("[WX]receive group msg: {}, cmsg={}".format(json.dumps(cmsg._rawmsg, ensure_ascii=False), cmsg))
  165. pass
  166. elif cmsg.ctype == ContextType.FILE:
  167. logger.debug(f"[WX]receive attachment msg, file_name={cmsg.content}")
  168. else:
  169. logger.debug("[WX]receive group msg: {}".format(cmsg.content))
  170. context = self._compose_context(cmsg.ctype, cmsg.content, isgroup=True, msg=cmsg)
  171. if context:
  172. self.produce(context)
  173. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  174. def send(self, reply: Reply, context: Context):
  175. receiver = context["receiver"]
  176. if reply.type == ReplyType.TEXT:
  177. itchat.send(reply.content, toUserName=receiver)
  178. logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
  179. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  180. itchat.send(reply.content, toUserName=receiver)
  181. logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
  182. elif reply.type == ReplyType.VOICE:
  183. itchat.send_file(reply.content, toUserName=receiver)
  184. logger.info("[WX] sendFile={}, receiver={}".format(reply.content, receiver))
  185. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  186. img_url = reply.content
  187. logger.debug(f"[WX] start download image, img_url={img_url}")
  188. pic_res = requests.get(img_url, stream=True)
  189. image_storage = io.BytesIO()
  190. size = 0
  191. for block in pic_res.iter_content(1024):
  192. size += len(block)
  193. image_storage.write(block)
  194. logger.info(f"[WX] download image success, size={size}, img_url={img_url}")
  195. image_storage.seek(0)
  196. itchat.send_image(image_storage, toUserName=receiver)
  197. logger.info("[WX] sendImage url={}, receiver={}".format(img_url, receiver))
  198. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  199. image_storage = reply.content
  200. image_storage.seek(0)
  201. itchat.send_image(image_storage, toUserName=receiver)
  202. logger.info("[WX] sendImage, receiver={}".format(receiver))
  203. elif reply.type == ReplyType.FILE: # 新增文件回复类型
  204. file_storage = reply.content
  205. itchat.send_file(file_storage, toUserName=receiver)
  206. logger.info("[WX] sendFile, receiver={}".format(receiver))
  207. elif reply.type == ReplyType.VIDEO: # 新增视频回复类型
  208. video_storage = reply.content
  209. itchat.send_video(video_storage, toUserName=receiver)
  210. logger.info("[WX] sendFile, receiver={}".format(receiver))
  211. elif reply.type == ReplyType.VIDEO_URL: # 新增视频URL回复类型
  212. video_url = reply.content
  213. logger.debug(f"[WX] start download video, video_url={video_url}")
  214. video_res = requests.get(video_url, stream=True)
  215. video_storage = io.BytesIO()
  216. size = 0
  217. for block in video_res.iter_content(1024):
  218. size += len(block)
  219. video_storage.write(block)
  220. logger.info(f"[WX] download video success, size={size}, video_url={video_url}")
  221. video_storage.seek(0)
  222. itchat.send_video(video_storage, toUserName=receiver)
  223. logger.info("[WX] sendVideo url={}, receiver={}".format(video_url, receiver))
  224. def _send_login_success():
  225. try:
  226. from common.linkai_client import chat_client
  227. chat_client.send_login_success()
  228. except Exception as e:
  229. pass
  230. def _send_logout():
  231. try:
  232. from common.linkai_client import chat_client
  233. chat_client.send_logout()
  234. except Exception as e:
  235. pass
  236. def _send_qr_code(qrcode_list: list):
  237. try:
  238. from common.linkai_client import chat_client
  239. chat_client.send_qrcode(qrcode_list)
  240. except Exception as e:
  241. pass