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

84 lines
2.2 KiB
Python
Raw Normal View History

2023-01-10 16:08:27 +00:00
import sys
2023-01-07 20:11:46 +00:00
2023-01-10 16:08:27 +00:00
import asyncio as telegram
import nio as matrix
2023-01-10 00:48:55 +00:00
from config_dataclass import Config
2023-01-10 00:48:55 +00:00
CONFIG_FILE_NAME = "config.yaml"
2023-01-08 22:13:27 +00:00
2023-01-08 19:28:13 +00:00
def main():
2023-01-10 00:48:55 +00:00
config = Config.from_yaml_config(CONFIG_FILE_NAME)
2023-01-08 19:31:11 +00:00
2023-01-10 16:08:27 +00:00
telegram.run(Application(config).run())
class TelegramLopp:
def __init__(self, app):
self.app = app
self.bot = telegram.Bot(token=app.config.telegram_bot_token)
self.dispatcher = telegram.Dispatcher(bot=self.bot)
self.dispatcher.register_message_handler(self.on_message)
async def run(self) -> None:
await self.dispatcher.start_polling()
async def on_message(self, msg):
print(msg, file=sys.stderr)
class MatrixLoop:
def __init__(self, app):
self.app = app
self.client = matrix.AsyncClient(
app.config.matrix_homeserver_url,
app.config.matrix_full_bot_id,
)
self.client.add_event_callback(self.on_message, matrix.RoomMessage)
async def prepare(self):
await self.client.login(self.app.config.matrix_bot_password)
async def finish(self):
await self.client.close()
async def run(self):
await self.client.sync_forever(timeout=30000)
async def on_message(self, room, event):
print(room, event, file=sys.stderr)
def upgrade_room(self, room, telegram_nickname):
event_dict = matrix.event_builders.event_builder.EventBuilder(
name=telegram_nickname
).as_dict()
client.room_send(
room_id=room,
message_type=event_dict["type"],
content=event_dict["content"],
) # предположу что оно так работает
# https://matrix-nio.readthedocs.io/en/latest/nio.html#module-nio.event_builders.state_events
2023-01-08 19:31:11 +00:00
2023-01-08 19:28:13 +00:00
class Application:
2023-01-08 19:31:11 +00:00
def __init__(self, config):
self.config = config
self.matrix_loop = MatrixLoop(self)
2023-01-10 16:08:27 +00:00
self.telegram = TelegramLopp(self)
2023-01-08 19:28:13 +00:00
async def run(self):
try:
await self.matrix_loop.prepare()
await asyncio.gather(
self.matrix_loop.run(),
2023-01-10 13:16:50 +00:00
self.telegram.run(),
2023-01-08 19:28:13 +00:00
)
finally:
if self.matrix_loop:
await self.matrix_loop.finish()
2023-01-08 18:43:37 +00:00
2023-01-08 13:54:22 +00:00
if __name__ == "__main__":
2023-01-08 19:28:13 +00:00
main()