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.

wechaty_channel.py 5.0KB

1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. 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(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. self.produce(context)