join room before sending message
This commit is contained in:
parent
624a1b2c08
commit
7ffa47c267
2 changed files with 29 additions and 1 deletions
|
@ -76,6 +76,11 @@ async def matrix_webhook(request):
|
||||||
else:
|
else:
|
||||||
formatted_body = markdown(str(data["body"]), extensions=["extra"])
|
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 = {
|
content = {
|
||||||
"msgtype": "m.text",
|
"msgtype": "m.text",
|
||||||
"body": data["body"],
|
"body": data["body"],
|
||||||
|
|
|
@ -6,7 +6,7 @@ from http import HTTPStatus
|
||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from nio import AsyncClient
|
from nio import AsyncClient
|
||||||
from nio.exceptions import LocalProtocolError
|
from nio.exceptions import LocalProtocolError
|
||||||
from nio.responses import RoomSendError
|
from nio.responses import RoomSendError, JoinError
|
||||||
|
|
||||||
from . import conf
|
from . import conf
|
||||||
|
|
||||||
|
@ -22,6 +22,29 @@ def create_json_response(status, ret):
|
||||||
return web.json_response(response_data, status=status)
|
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):
|
async def send_room_message(room_id, content):
|
||||||
"""Send a message to a room."""
|
"""Send a message to a room."""
|
||||||
LOGGER.debug(f"Sending room message in {room_id=}: {content=}")
|
LOGGER.debug(f"Sending room message in {room_id=}: {content=}")
|
||||||
|
|
Loading…
Reference in a new issue