Merge pull request #1 from homeworkprod-forks/main

Simplify code
This commit is contained in:
Guilhem Saurel 2021-01-03 16:40:25 +01:00 committed by GitHub
commit aad02887f1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -33,35 +33,46 @@ async def handler(request):
This one handles a POST, checks its content, and forwards it to the matrix room. This one handles a POST, checks its content, and forwards it to the matrix room.
""" """
data = await request.read() data = await request.read()
try: try:
data = json.loads(data.decode()) data = json.loads(data.decode())
status, ret = HTTPStatus.BAD_REQUEST, 'I need a json dict with text & key'
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
data = {} return create_json_response(HTTPStatus.BAD_REQUEST, 'Invalid JSON')
status, ret = HTTPStatus.BAD_REQUEST, 'This was not valid JSON'
if all(key in data for key in ['text', 'key']): if not all(key in data for key in ['text', 'key']):
status, ret = HTTPStatus.UNAUTHORIZED, 'I need the good "key"' return create_json_response(HTTPStatus.BAD_REQUEST,
if data['key'] == API_KEY: 'Missing text and/or API key property')
status, ret = HTTPStatus.OK, 'OK'
if data['key'] != API_KEY:
return create_json_response(HTTPStatus.UNAUTHORIZED, 'Invalid API key')
room_id = str(request.rel_url)[1:]
content = { content = {
"msgtype": "m.text", 'msgtype': 'm.text',
"body": data['text'], 'body': data['text'],
"format": "org.matrix.custom.html", 'format': 'org.matrix.custom.html',
"formatted_body": markdown(data['text'], extensions=['extra']), 'formatted_body': markdown(data['text'], extensions=['extra']),
} }
try: try:
await CLIENT.room_send(room_id=str(request.rel_url)[1:], await send_room_message(room_id, content)
message_type="m.room.message",
content=content)
except LocalProtocolError: # Connection lost, try another login except LocalProtocolError: # Connection lost, try another login
await CLIENT.login(MATRIX_PW) await CLIENT.login(MATRIX_PW)
await CLIENT.room_send(room_id=str(request.rel_url)[1:], await send_room_message(room_id, content)
message_type="m.room.message",
content=content)
return web.Response(text='{"status": %i, "ret": "%s"}' % (status, ret), return create_json_response(HTTPStatus.OK, 'OK')
content_type='application/json',
status=status)
def create_json_response(status, ret):
"""Create a JSON response."""
response_data = {'status': status, 'ret': ret}
return web.json_response(response_data, status=status)
async def send_room_message(room_id, content):
"""Send a message to a room."""
return await CLIENT.room_send(room_id=room_id,
message_type='m.room.message',
content=content)
async def main(event): async def main(event):