main.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. from urllib.parse import urlparse
  3. import os
  4. import simplematrixbotlib as botlib
  5. import nio
  6. from speech_recognition import ASR
  7. creds = botlib.Creds(
  8. homeserver=os.environ['HOMESERVER'],
  9. username=os.environ['USERNAME'],
  10. password=os.getenv('PASSWORD', None),
  11. login_token=os.getenv('LOGIN_TOKEN', None),
  12. access_token=os.getenv('ACCESS_TOKEN', None),
  13. session_stored_file="/data/session.txt"
  14. )
  15. config = botlib.Config()
  16. config.encryption_enabled = True
  17. config.emoji_verify = False
  18. config.ignore_unverified_devices = True
  19. config.store_path = '/data/crypto_store/'
  20. bot = botlib.Bot(creds, config)
  21. asr = ASR(os.getenv('ASR_MODEL', 'tiny'), os.getenv('ASR_LANGUAGE', 'en'))
  22. @bot.listener.on_custom_event(nio.RoomMessageAudio)
  23. async def on_message_audio(room, event):
  24. await on_audio(room, event, False)
  25. @bot.listener.on_custom_event(nio.RoomEncryptedAudio)
  26. async def on_encrypted_audio(room, event):
  27. await on_audio(room, event, True)
  28. async def on_audio(room, event, encrypted):
  29. print(room.machine_name, event.sender, event.body, event.url)
  30. match = botlib.MessageMatch(room, event, bot)
  31. if match.is_not_from_this_bot():
  32. await bot.async_client.room_typing(room.machine_name, True, timeout=120000)
  33. url = urlparse(event.url)
  34. response = await bot.async_client.download(server_name=url.netloc, media_id=url.path[1:])
  35. if encrypted:
  36. print("decrypting...")
  37. data = nio.crypto.attachments.decrypt_attachment(
  38. response.body,
  39. event.source["content"]["file"]["key"]["k"],
  40. event.source["content"]["file"]["hashes"]["sha256"],
  41. event.source["content"]["file"]["iv"],
  42. )
  43. else:
  44. data = response.body
  45. print(response)
  46. result = await asr.transcribe(data)
  47. await bot.async_client.room_typing(room.machine_name, False)
  48. filename = response.filename or event.body
  49. if filename:
  50. reply = f"Transcription of {filename}: {result}"
  51. else:
  52. reply = f"Transcription: {result}"
  53. await bot.api._send_room(
  54. room_id=room.room_id,
  55. content={
  56. "msgtype": "m.notice",
  57. "body": reply,
  58. "m.relates_to": {
  59. "m.in_reply_to": {
  60. "event_id": event.event_id
  61. }
  62. }
  63. })
  64. if __name__ == "__main__":
  65. asr.load_model()
  66. bot.run()