Split code into separate classes
This commit is contained in:
parent
e1177d388d
commit
8f78ee8c2d
|
@ -12,35 +12,51 @@ TELEGRAM_BOT_TOKEN = os.environ['TELEGRAM_BOT_TOKEN']
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
try:
|
try:
|
||||||
matrix_client = \
|
matrix_loop = None
|
||||||
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)
|
|
||||||
|
|
||||||
telegram_bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
|
matrix_loop = MatrixLoop(MATRIX_HOMESERVER_URL, MATRIX_FULL_USER_ID,
|
||||||
telegram_dispatcher = telegram.Dispatcher(bot=telegram_bot)
|
MATRIX_PASSWORD)
|
||||||
telegram_dispatcher.register_message_handler(telegram_on_message)
|
await matrix_loop.prepare()
|
||||||
|
|
||||||
|
telegram_loop = TelegramLoop(TELEGRAM_BOT_TOKEN)
|
||||||
|
|
||||||
await asyncio.gather(
|
await asyncio.gather(
|
||||||
matrix_loop(matrix_client),
|
matrix_loop.run(),
|
||||||
telegram_loop(),
|
telegram_loop.run(),
|
||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
if matrix_client:
|
if matrix_loop:
|
||||||
await matrix_client.close()
|
await matrix_loop.finish()
|
||||||
|
|
||||||
async def matrix_loop(client):
|
class MatrixLoop:
|
||||||
await client.sync_forever(timeout=30000)
|
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():
|
async def prepare(self):
|
||||||
print(456, file=sys.stderr)
|
await self.client.login(self.password)
|
||||||
|
|
||||||
async def matrix_on_message(room, event):
|
async def finish(self):
|
||||||
print(room, event, file=sys.stderr)
|
await self.client.close()
|
||||||
|
|
||||||
async def telegram_on_message(msg):
|
async def run(self):
|
||||||
print(msg, file=sys.stderr)
|
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__':
|
if __name__ == '__main__':
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
Reference in a new issue