echo_bot.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. This bot writes transcribed voice messages from each user to the chat
  3. """
  4. import asyncio
  5. from aiortc.mediastreams import AudioStreamTrack
  6. from hubsbot import Bot
  7. from hubsbot.peer import Peer
  8. from hubsbot.consumer import Message
  9. from hubsbot.consumer import \
  10. ConsumerFactory as BaseConsumerFactory, TextConsumer as BaseTextConsumer # Abstract factories
  11. from hubsbot.consumer.processed.vosk import VoskVoiceConsumer # A consumer with text transcription
  12. class TextConsumer(BaseTextConsumer):
  13. def __init__(self, peer: Peer):
  14. self.peer = peer
  15. async def on_message(self, msg: Message):
  16. print(f'Message from {self.peer.id}: {msg}')
  17. class VoiceConsumer(VoskVoiceConsumer):
  18. def __init__(self, track: AudioStreamTrack, peer: Peer, bot: Bot):
  19. super().__init__(track)
  20. self.peer = peer
  21. self.bot = bot
  22. async def on_message(self, msg: Message):
  23. await self.bot.hubs_client.send_chat(f'Transcribed from {self.peer.display_name}: {msg.body}')
  24. # Override consumer factory
  25. class ConsumerFactory(BaseConsumerFactory):
  26. def __init__(self, bot: Bot):
  27. self.bot = bot
  28. pass
  29. def create_text_consumer(self, peer: Peer):
  30. return TextConsumer(peer)
  31. def create_voice_consumer(self, peer: Peer, track: AudioStreamTrack):
  32. recorder = VoiceConsumer(track, peer, self.bot)
  33. return recorder
  34. def main():
  35. bot = Bot(
  36. host='HOST',
  37. room_id='ROOM_ID',
  38. avatar_id="basebot",
  39. display_name="Python User",
  40. consumer_factory=None,
  41. voice_track=AudioStreamTrack())
  42. bot.consumer_factory = ConsumerFactory(bot)
  43. asyncio.get_event_loop().run_until_complete(bot.join())
  44. if __name__ == '__main__':
  45. main()