diff --git a/src/kassandra/__main__.py b/src/kassandra/__main__.py index f7be0ae..0d1294e 100644 --- a/src/kassandra/__main__.py +++ b/src/kassandra/__main__.py @@ -1,31 +1,10 @@ import argparse import asyncio -from typing import ( - Any, - NoReturn -) - -from matrix_bot.client import Client -from matrix_bot.invite_policy import WhiteList from .config import load_config +from .bot import send_messages from .webhook import run_webhook -async def send_messages( - message_queue: asyncio.Queue[dict[str, Any]], - bot: Client, - rooms: list[str] -)->NoReturn: - """ - Read messages from a queue and send them via the bot. - """ - while True: - message = await message_queue.get() - message = str(message) - for room in rooms: - await bot.send_message(room, message) - message_queue.task_done() - async def main(): parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", default="config.yaml") @@ -34,22 +13,23 @@ async def main(): config = load_config(args.config) alert_queue = asyncio.Queue() - client = await Client( + bot_corout = send_messages( + alert_queue, # Will change in the futur config.username, config.homeserver, - config.password + config.password, + config.alert_rooms + ) + webhook_corout = run_webhook( + alert_queue, + config.host, + config.port ) - invite_policy = await WhiteList(client, config.alert_rooms) - client.set_invite_policy(invite_policy) - # Test: - for room in config.alert_rooms: - await client.send_message(room, f"Hello from {config.username}") await asyncio.gather( - client.run(), - run_webhook(alert_queue, config.host, config.port), - send_messages(alert_queue, client, config.alert_rooms) + bot_corout, + webhook_corout ) if __name__ == "__main__": diff --git a/src/kassandra/bot.py b/src/kassandra/bot.py new file mode 100644 index 0000000..49841d9 --- /dev/null +++ b/src/kassandra/bot.py @@ -0,0 +1,53 @@ +""" +The bot that send messages. +""" + +import asyncio +from typing import ( + Any, + NoReturn +) +from matrix_bot.client import Client +from matrix_bot.invite_policy import WhiteList + +async def __send_messsages( + message_queue: asyncio.Queue[dict[str, Any]], # For now, type will change in the futur + bot: Client, + rooms: list[str] +)->NoReturn: + """ + Actually send the messages from the queue. + """ + while True: + message = await message_queue.get() + message = str(message) + for room in rooms: + await bot.send_message(room, message) + message_queue.task_done() + +async def send_messages( + message_queue: asyncio.Queue[dict[str, Any]], # For now, type will change in the futur + username: str, + homeserver: str, + password: str, + alert_rooms: list[str] +): + """ + Initialize the bot and send messages added to the queue to the alert_rooms. + """ + + bot = await Client( + username, + homeserver, + password + ) + invite_policy = await WhiteList(bot, alert_rooms) + bot.set_invite_policy(invite_policy) + await asyncio.gather( + bot.run(), + __send_messsages( + message_queue, + bot, + alert_rooms + ) + )