Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

195 lines
7.9KB

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