From 6c138a65b409cbfae176a32e11df4b2c5f719a87 Mon Sep 17 00:00:00 2001 From: Guilhem Saurel Date: Tue, 28 Jul 2020 21:56:05 +0200 Subject: [PATCH] try another login on connection lost --- matrix_webhook.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/matrix_webhook.py b/matrix_webhook.py index 0374774..5ffb69f 100755 --- a/matrix_webhook.py +++ b/matrix_webhook.py @@ -16,6 +16,7 @@ from signal import SIGINT, SIGTERM from aiohttp import web from markdown import markdown from nio import AsyncClient +from nio.exceptions import LocalProtocolError SERVER_ADDRESS = ('', int(os.environ.get('PORT', 4785))) MATRIX_URL = os.environ.get('MATRIX_URL', 'https://matrix.org') @@ -42,14 +43,21 @@ async def handler(request): status, ret = HTTPStatus.UNAUTHORIZED, 'I need the good "key"' if data['key'] == API_KEY: status, ret = HTTPStatus.OK, 'OK' - await CLIENT.room_send(room_id=str(request.rel_url)[1:], - message_type="m.room.message", - content={ - "msgtype": "m.text", - "body": data['text'], - "format": "org.matrix.custom.html", - "formatted_body": markdown(data['text'], extensions=['extra']), - }) + content = { + "msgtype": "m.text", + "body": data['text'], + "format": "org.matrix.custom.html", + "formatted_body": markdown(data['text'], extensions=['extra']), + } + try: + await CLIENT.room_send(room_id=str(request.rel_url)[1:], + message_type="m.room.message", + content=content) + except LocalProtocolError: # Connection lost, try another login + await CLIENT.login(MATRIX_PW) + await CLIENT.room_send(room_id=str(request.rel_url)[1:], + message_type="m.room.message", + content=content) return web.Response(text='{"status": %i, "ret": "%s"}' % (status, ret), content_type='application/json',