matrix-webhook/matrix_webhook.py

69 lines
2.1 KiB
Python
Raw Normal View History

2019-02-10 19:29:55 -05:00
#!/usr/bin/env python3
2019-02-10 16:22:09 -05:00
"""
2019-02-17 05:46:00 -05:00
Matrix Webhook
Post a message to a matrix room with a simple HTTP POST
2019-02-10 16:22:09 -05:00
"""
2020-02-14 13:18:51 -05:00
import asyncio
import json
2019-02-10 18:38:08 -05:00
import os
2019-02-10 16:22:09 -05:00
2020-02-14 13:18:51 -05:00
from aiohttp import web
2019-02-10 18:38:08 -05:00
from matrix_client.client import MatrixClient
2019-02-10 19:51:35 -05:00
SERVER_ADDRESS = ('', int(os.environ.get('PORT', 4785)))
MATRIX_URL = os.environ.get('MATRIX_URL', 'https://matrix.org')
MATRIX_ID = os.environ.get('MATRIX_ID', 'wwm')
MATRIX_PW = os.environ['MATRIX_PW']
API_KEY = os.environ['API_KEY']
2019-02-10 18:38:08 -05:00
2020-02-14 13:18:51 -05:00
client = MatrixClient(MATRIX_URL)
client.login(username=MATRIX_ID, password=MATRIX_PW)
rooms = client.get_rooms()
2019-02-10 18:38:08 -05:00
2020-02-14 13:18:51 -05:00
async def handler(request):
2019-02-10 18:38:08 -05:00
"""
2020-02-14 13:18:51 -05:00
Coroutine given to the server, st. it knows what to do with an HTTP request.
This one handles a POST, checks its content, and forwards it to the matrix room.
2019-02-10 18:38:08 -05:00
"""
2020-02-14 13:18:51 -05:00
data = json.loads(request.read().decode())
status, ret = 400, 'I need a json dict with text & key'
if all(key in data for key in ['text', 'key']):
status, ret = 401, 'I need the good "key"'
if data['key'] == API_KEY:
status, ret = 404, 'I need the id of the room as a path, and to be in this room'
if request.rel_url[1:] not in rooms:
# try to see if this room has been joined recently
rooms = client.get_rooms()
if request.rel_url[1:] in rooms:
status, ret = 200, json.dumps(rooms[request.rel_url[1:]].send_text(data['text']))
2019-02-10 18:38:08 -05:00
2020-02-14 13:18:51 -05:00
return web.Response(text='{"status": %i, "ret": "%a"}' % (status, ret),
content_type='application/json',
status=status)
2019-02-10 16:22:09 -05:00
2020-02-14 13:18:51 -05:00
async def main():
server = web.Server(handler)
runner = web.ServerRunner(server)
await runner.setup()
site = web.TCPSite(runner, *SERVER_ADDRESS)
await site.start()
print("======= Serving ======")
2019-02-10 16:22:09 -05:00
2020-02-14 13:18:51 -05:00
# pause here for very long time by serving HTTP requests and
# waiting for keyboard interruption
await asyncio.sleep(100 * 3600)
2019-02-10 16:22:09 -05:00
if __name__ == '__main__':
2020-02-14 13:18:51 -05:00
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
except KeyboardInterrupt:
pass
loop.close()