This repository has been archived on 2023-01-19. You can view files and clone it, but cannot push or open issues or pull requests.
MirrorTea/mirrortea/__main__.py

63 lines
1.7 KiB
Python
Raw Normal View History

2023-01-07 20:11:46 +00:00
import asyncio
2023-01-08 13:01:33 +00:00
import os
2023-01-08 12:55:14 +00:00
import sys
2023-01-07 21:13:27 +00:00
import aiogram as telegram
import nio as matrix
2023-01-07 20:11:46 +00:00
2023-01-08 13:01:33 +00:00
MATRIX_HOMESERVER_URL = os.environ['MATRIX_HOMESERVER_URL']
MATRIX_FULL_USER_ID = os.environ['MATRIX_FULL_USER_ID']
MATRIX_PASSWORD = os.environ['MATRIX_PASSWORD']
TELEGRAM_BOT_TOKEN = os.environ['TELEGRAM_BOT_TOKEN']
2023-01-07 21:42:02 +00:00
2023-01-07 21:29:12 +00:00
async def main():
2023-01-07 21:42:02 +00:00
try:
2023-01-08 18:43:37 +00:00
matrix_loop = None
2023-01-07 21:42:02 +00:00
2023-01-08 18:43:37 +00:00
matrix_loop = MatrixLoop(MATRIX_HOMESERVER_URL, MATRIX_FULL_USER_ID,
MATRIX_PASSWORD)
await matrix_loop.prepare()
telegram_loop = TelegramLoop(TELEGRAM_BOT_TOKEN)
2023-01-07 21:42:02 +00:00
2023-01-08 13:54:22 +00:00
await asyncio.gather(
2023-01-08 18:43:37 +00:00
matrix_loop.run(),
telegram_loop.run(),
2023-01-08 13:54:22 +00:00
)
2023-01-07 21:42:02 +00:00
finally:
2023-01-08 18:43:37 +00:00
if matrix_loop:
await matrix_loop.finish()
class MatrixLoop:
def __init__(self, homeserver_url, full_user_id, password):
self.password = password
self.client = matrix.AsyncClient(homeserver_url, full_user_id)
self.client.add_event_callback(self.on_message, matrix.RoomMessage)
async def prepare(self):
await self.client.login(self.password)
async def finish(self):
await self.client.close()
async def run(self):
await self.client.sync_forever(timeout=30000)
2023-01-07 21:05:21 +00:00
2023-01-08 18:43:37 +00:00
async def on_message(self, room, event):
print(room, event, file=sys.stderr)
2023-01-07 20:11:46 +00:00
2023-01-08 18:43:37 +00:00
class TelegramLoop:
def __init__(self, bot_token):
self.bot = telegram.Bot(token=bot_token)
self.dispatcher = telegram.Dispatcher(bot=self.bot)
self.dispatcher.register_message_handler(self.on_message)
2023-01-07 21:29:12 +00:00
2023-01-08 18:43:37 +00:00
async def run(self):
2023-01-08 18:51:45 +00:00
await self.dispatcher.start_polling()
2023-01-08 12:46:08 +00:00
2023-01-08 18:43:37 +00:00
async def on_message(self, msg):
print(msg, file=sys.stderr)
2023-01-08 13:54:22 +00:00
2023-01-07 20:11:46 +00:00
if __name__ == '__main__':
2023-01-07 21:29:12 +00:00
asyncio.run(main())