Split code into separate classes

This commit is contained in:
Alex Kotov 2023-01-08 22:43:37 +04:00
parent e1177d388d
commit 8f78ee8c2d
No known key found for this signature in database
GPG key ID: 553C0EBBEB5D5F08

View file

@ -12,35 +12,51 @@ TELEGRAM_BOT_TOKEN = os.environ['TELEGRAM_BOT_TOKEN']
async def main():
try:
matrix_client = \
matrix.AsyncClient(MATRIX_HOMESERVER_URL, MATRIX_FULL_USER_ID)
matrix_client.add_event_callback(matrix_on_message,
matrix.RoomMessage)
await matrix_client.login(MATRIX_PASSWORD)
matrix_loop = None
telegram_bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
telegram_dispatcher = telegram.Dispatcher(bot=telegram_bot)
telegram_dispatcher.register_message_handler(telegram_on_message)
matrix_loop = MatrixLoop(MATRIX_HOMESERVER_URL, MATRIX_FULL_USER_ID,
MATRIX_PASSWORD)
await matrix_loop.prepare()
telegram_loop = TelegramLoop(TELEGRAM_BOT_TOKEN)
await asyncio.gather(
matrix_loop(matrix_client),
telegram_loop(),
matrix_loop.run(),
telegram_loop.run(),
)
finally:
if matrix_client:
await matrix_client.close()
if matrix_loop:
await matrix_loop.finish()
async def matrix_loop(client):
await client.sync_forever(timeout=30000)
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 telegram_loop():
print(456, file=sys.stderr)
async def prepare(self):
await self.client.login(self.password)
async def matrix_on_message(room, event):
print(room, event, file=sys.stderr)
async def finish(self):
await self.client.close()
async def telegram_on_message(msg):
print(msg, file=sys.stderr)
async def run(self):
await self.client.sync_forever(timeout=30000)
async def on_message(self, room, event):
print(room, event, file=sys.stderr)
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)
async def run(self):
print(456, file=sys.stderr)
async def on_message(self, msg):
print(msg, file=sys.stderr)
if __name__ == '__main__':
asyncio.run(main())