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.

192 lines
8.0KB

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