Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

125 rindas
5.0KB

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