140 line
5.1KB

  1. # encoding:utf-8
  2. """
  3. wechaty channel
  4. Python Wechaty - https://github.com/wechaty/python-wechaty
  5. """
  6. import asyncio
  7. import base64
  8. import os
  9. import time
  10. from wechaty import Contact, Wechaty
  11. from wechaty.user import Message
  12. from wechaty_puppet import FileBox
  13. from bridge.context import *
  14. from bridge.context import Context
  15. from bridge.reply import *
  16. from channel.chat_channel import ChatChannel
  17. from channel.wechat.wechaty_message import WechatyMessage
  18. from common.log import logger
  19. from common.singleton import singleton
  20. from config import conf
  21. try:
  22. from voice.audio_convert import any_to_sil
  23. except Exception as e:
  24. pass
  25. @singleton
  26. class WechatyChannel(ChatChannel):
  27. NOT_SUPPORT_REPLYTYPE = []
  28. def __init__(self):
  29. super().__init__()
  30. def startup(self):
  31. config = conf()
  32. token = config.get("wechaty_puppet_service_token")
  33. os.environ["WECHATY_PUPPET_SERVICE_TOKEN"] = token
  34. asyncio.run(self.main())
  35. async def main(self):
  36. loop = asyncio.get_event_loop()
  37. # 将asyncio的loop传入处理线程
  38. self.handler_pool._initializer = lambda: asyncio.set_event_loop(loop)
  39. self.bot = Wechaty()
  40. self.bot.on("login", self.on_login)
  41. self.bot.on("message", self.on_message)
  42. await self.bot.start()
  43. async def on_login(self, contact: Contact):
  44. self.user_id = contact.contact_id
  45. self.name = contact.name
  46. logger.info("[WX] login user={}".format(contact))
  47. # 统一的发送函数,每个Channel自行实现,根据reply的type字段发送不同类型的消息
  48. def send(self, reply: Reply, context: Context):
  49. receiver_id = context["receiver"]
  50. loop = asyncio.get_event_loop()
  51. if context["isgroup"]:
  52. receiver = asyncio.run_coroutine_threadsafe(
  53. self.bot.Room.find(receiver_id), loop
  54. ).result()
  55. else:
  56. receiver = asyncio.run_coroutine_threadsafe(
  57. self.bot.Contact.find(receiver_id), loop
  58. ).result()
  59. msg = None
  60. if reply.type == ReplyType.TEXT:
  61. msg = reply.content
  62. asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result()
  63. logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
  64. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  65. msg = reply.content
  66. asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result()
  67. logger.info("[WX] sendMsg={}, receiver={}".format(reply, receiver))
  68. elif reply.type == ReplyType.VOICE:
  69. voiceLength = None
  70. file_path = reply.content
  71. sil_file = os.path.splitext(file_path)[0] + ".sil"
  72. voiceLength = int(any_to_sil(file_path, sil_file))
  73. if voiceLength >= 60000:
  74. voiceLength = 60000
  75. logger.info(
  76. "[WX] voice too long, length={}, set to 60s".format(voiceLength)
  77. )
  78. # 发送语音
  79. t = int(time.time())
  80. msg = FileBox.from_file(sil_file, name=str(t) + ".sil")
  81. if voiceLength is not None:
  82. msg.metadata["voiceLength"] = voiceLength
  83. asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result()
  84. try:
  85. os.remove(file_path)
  86. if sil_file != file_path:
  87. os.remove(sil_file)
  88. except Exception as e:
  89. pass
  90. logger.info(
  91. "[WX] sendVoice={}, receiver={}".format(reply.content, receiver)
  92. )
  93. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  94. img_url = reply.content
  95. t = int(time.time())
  96. msg = FileBox.from_url(url=img_url, name=str(t) + ".png")
  97. asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result()
  98. logger.info("[WX] sendImage url={}, receiver={}".format(img_url, receiver))
  99. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  100. image_storage = reply.content
  101. image_storage.seek(0)
  102. t = int(time.time())
  103. msg = FileBox.from_base64(
  104. base64.b64encode(image_storage.read()), str(t) + ".png"
  105. )
  106. asyncio.run_coroutine_threadsafe(receiver.say(msg), loop).result()
  107. logger.info("[WX] sendImage, receiver={}".format(receiver))
  108. async def on_message(self, msg: Message):
  109. """
  110. listen for message event
  111. """
  112. try:
  113. cmsg = await WechatyMessage(msg)
  114. except NotImplementedError as e:
  115. logger.debug("[WX] {}".format(e))
  116. return
  117. except Exception as e:
  118. logger.exception("[WX] {}".format(e))
  119. return
  120. logger.debug("[WX] message:{}".format(cmsg))
  121. room = msg.room() # 获取消息来自的群聊. 如果消息不是来自群聊, 则返回None
  122. isgroup = room is not None
  123. ctype = cmsg.ctype
  124. context = self._compose_context(ctype, cmsg.content, isgroup=isgroup, msg=cmsg)
  125. if context:
  126. logger.info("[WX] receiveMsg={}, context={}".format(cmsg, context))
  127. self.produce(context)