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.

134 lines
5.3KB

  1. # encoding:utf-8
  2. """
  3. wechaty channel
  4. Python Wechaty - https://github.com/wechaty/python-wechaty
  5. """
  6. import base64
  7. from concurrent.futures import ThreadPoolExecutor
  8. import os
  9. import time
  10. import asyncio
  11. from bridge.context import Context
  12. from wechaty_puppet import FileBox
  13. from wechaty import Wechaty, Contact
  14. from wechaty.user import Message
  15. from bridge.reply import *
  16. from bridge.context import *
  17. from channel.chat_channel import ChatChannel
  18. from channel.wechat.wechaty_message import WechatyMessage
  19. from common.log import logger
  20. from config import conf
  21. try:
  22. from voice.audio_convert import mp3_to_sil
  23. except Exception as e:
  24. pass
  25. thread_pool = ThreadPoolExecutor(max_workers=8)
  26. def thread_pool_callback(worker):
  27. worker_exception = worker.exception()
  28. if worker_exception:
  29. logger.exception("Worker return exception: {}".format(worker_exception))
  30. class WechatyChannel(ChatChannel):
  31. def __init__(self):
  32. pass
  33. def startup(self):
  34. asyncio.run(self.main())
  35. async def main(self):
  36. config = conf()
  37. token = config.get('wechaty_puppet_service_token')
  38. os.environ['WECHATY_PUPPET_SERVICE_TOKEN'] = token
  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(self.bot.Room.find(receiver_id),loop).result()
  53. else:
  54. receiver = asyncio.run_coroutine_threadsafe(self.bot.Contact.find(receiver_id),loop).result()
  55. msg = None
  56. if reply.type == ReplyType.TEXT:
  57. msg = reply.content
  58. asyncio.run_coroutine_threadsafe(receiver.say(msg),loop).result()
  59. logger.info('[WX] sendMsg={}, receiver={}'.format(reply, receiver))
  60. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  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.VOICE:
  65. voiceLength = None
  66. if reply.content.endswith('.mp3'):
  67. mp3_file = reply.content
  68. sil_file = os.path.splitext(mp3_file)[0] + '.sil'
  69. voiceLength = mp3_to_sil(mp3_file, sil_file)
  70. try:
  71. os.remove(mp3_file)
  72. except Exception as e:
  73. pass
  74. elif reply.content.endswith('.sil'):
  75. sil_file = reply.content
  76. else:
  77. raise Exception('voice file must be mp3 or sil format')
  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(sil_file)
  86. except Exception as e:
  87. pass
  88. logger.info('[WX] sendVoice={}, receiver={}'.format(reply.content, receiver))
  89. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  90. img_url = reply.content
  91. t = int(time.time())
  92. msg = FileBox.from_url(url=img_url, name=str(t) + '.png')
  93. asyncio.run_coroutine_threadsafe(receiver.say(msg),loop).result()
  94. logger.info('[WX] sendImage url={}, receiver={}'.format(img_url,receiver))
  95. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  96. image_storage = reply.content
  97. image_storage.seek(0)
  98. t = int(time.time())
  99. msg = FileBox.from_base64(base64.b64encode(image_storage.read()), str(t) + '.png')
  100. asyncio.run_coroutine_threadsafe(receiver.say(msg),loop).result()
  101. logger.info('[WX] sendImage, receiver={}'.format(receiver))
  102. async def on_message(self, msg: Message):
  103. """
  104. listen for message event
  105. """
  106. try:
  107. cmsg = await WechatyMessage(msg)
  108. except NotImplementedError as e:
  109. logger.debug('[WX] {}'.format(e))
  110. return
  111. except Exception as e:
  112. logger.exception('[WX] {}'.format(e))
  113. return
  114. logger.debug('[WX] message:{}'.format(cmsg))
  115. room = msg.room() # 获取消息来自的群聊. 如果消息不是来自群聊, 则返回None
  116. isgroup = room is not None
  117. ctype = cmsg.ctype
  118. context = self._compose_context(ctype, cmsg.content, isgroup=isgroup, msg=cmsg)
  119. if context:
  120. logger.info('[WX] receiveMsg={}, context={}'.format(cmsg, context))
  121. thread_pool.submit(self._handle_loop, context, asyncio.get_event_loop()).add_done_callback(thread_pool_callback)
  122. def _handle_loop(self,context,loop):
  123. asyncio.set_event_loop(loop)
  124. self._handle(context)