Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

wechaty_channel.py 5.2KB

1 rok temu
1 rok temu
1 rok temu
1 rok temu
1 rok temu
1 rok temu
1 rok temu
1 rok temu
1 rok temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 any_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. config = conf()
  35. token = config.get('wechaty_puppet_service_token')
  36. os.environ['WECHATY_PUPPET_SERVICE_TOKEN'] = token
  37. asyncio.run(self.main())
  38. async def main(self):
  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. file_path = reply.content
  67. sil_file = os.path.splitext(file_path)[0] + '.sil'
  68. voiceLength = int(any_to_sil(file_path, sil_file))
  69. if voiceLength >= 60000:
  70. voiceLength = 60000
  71. logger.info('[WX] voice too long, length={}, set to 60s'.format(voiceLength))
  72. # 发送语音
  73. t = int(time.time())
  74. msg = FileBox.from_file(sil_file, name=str(t) + '.sil')
  75. if voiceLength is not None:
  76. msg.metadata['voiceLength'] = voiceLength
  77. asyncio.run_coroutine_threadsafe(receiver.say(msg),loop).result()
  78. try:
  79. os.remove(file_path)
  80. if sil_file != file_path:
  81. os.remove(sil_file)
  82. except Exception as e:
  83. pass
  84. logger.info('[WX] sendVoice={}, receiver={}'.format(reply.content, receiver))
  85. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  86. img_url = reply.content
  87. t = int(time.time())
  88. msg = FileBox.from_url(url=img_url, name=str(t) + '.png')
  89. asyncio.run_coroutine_threadsafe(receiver.say(msg),loop).result()
  90. logger.info('[WX] sendImage url={}, receiver={}'.format(img_url,receiver))
  91. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  92. image_storage = reply.content
  93. image_storage.seek(0)
  94. t = int(time.time())
  95. msg = FileBox.from_base64(base64.b64encode(image_storage.read()), str(t) + '.png')
  96. asyncio.run_coroutine_threadsafe(receiver.say(msg),loop).result()
  97. logger.info('[WX] sendImage, receiver={}'.format(receiver))
  98. async def on_message(self, msg: Message):
  99. """
  100. listen for message event
  101. """
  102. try:
  103. cmsg = await WechatyMessage(msg)
  104. except NotImplementedError as e:
  105. logger.debug('[WX] {}'.format(e))
  106. return
  107. except Exception as e:
  108. logger.exception('[WX] {}'.format(e))
  109. return
  110. logger.debug('[WX] message:{}'.format(cmsg))
  111. room = msg.room() # 获取消息来自的群聊. 如果消息不是来自群聊, 则返回None
  112. isgroup = room is not None
  113. ctype = cmsg.ctype
  114. context = self._compose_context(ctype, cmsg.content, isgroup=isgroup, msg=cmsg)
  115. if context:
  116. logger.info('[WX] receiveMsg={}, context={}'.format(cmsg, context))
  117. thread_pool.submit(self._handle_loop, context, asyncio.get_event_loop()).add_done_callback(thread_pool_callback)
  118. def _handle_loop(self,context,loop):
  119. asyncio.set_event_loop(loop)
  120. self._handle(context)