main.py 2.5 KB

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