From 7ffa47c26714cbc7e3e92097ba131ff298523560 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20B=C3=B6hmke?= Date: Sat, 18 Sep 2021 12:12:54 +0200 Subject: [PATCH] join room before sending message --- matrix_webhook/handler.py | 5 +++++ matrix_webhook/utils.py | 25 ++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/matrix_webhook/handler.py b/matrix_webhook/handler.py index 1f1ac5f..3460810 100644 --- a/matrix_webhook/handler.py +++ b/matrix_webhook/handler.py @@ -76,6 +76,11 @@ async def matrix_webhook(request): else: formatted_body = markdown(str(data["body"]), extensions=["extra"]) + # try to join room first -> non none response means error + resp = await utils.join_room(data["room_id"]) + if resp is not None: + return resp + content = { "msgtype": "m.text", "body": data["body"], diff --git a/matrix_webhook/utils.py b/matrix_webhook/utils.py index 2b4d74d..339472b 100644 --- a/matrix_webhook/utils.py +++ b/matrix_webhook/utils.py @@ -6,7 +6,7 @@ from http import HTTPStatus from aiohttp import web from nio import AsyncClient from nio.exceptions import LocalProtocolError -from nio.responses import RoomSendError +from nio.responses import RoomSendError, JoinError from . import conf @@ -22,6 +22,29 @@ def create_json_response(status, ret): return web.json_response(response_data, status=status) +async def join_room(room_id): + """Try to join the room.""" + LOGGER.debug(f"Join room {room_id=}") + + for _ in range(10): + try: + resp = await CLIENT.join(room_id) + if isinstance(resp, JoinError): + if resp.status_code == "M_UNKNOWN_TOKEN": + LOGGER.warning("Reconnecting") + await CLIENT.login(conf.MATRIX_PW) + else: + return create_json_response( + ERROR_MAP[resp.status_code], resp.message + ) + else: + return None + except LocalProtocolError as e: + LOGGER.error(f"Send error: {e}") + LOGGER.warning("Trying again") + return create_json_response(HTTPStatus.GATEWAY_TIMEOUT, "Homeserver not responding") + + async def send_room_message(room_id, content): """Send a message to a room.""" LOGGER.debug(f"Sending room message in {room_id=}: {content=}")