matrix-client → matrix-nio

This commit is contained in:
Guilhem Saurel 2020-02-16 13:47:00 +01:00
parent a6fad80ca7
commit 2c97fa3d3f

View file

@ -2,6 +2,8 @@
""" """
Matrix Webhook Matrix Webhook
Post a message to a matrix room with a simple HTTP POST Post a message to a matrix room with a simple HTTP POST
v1: matrix-client & http.server
v2: matrix-nio & aiohttp
""" """
import asyncio import asyncio
@ -9,17 +11,15 @@ import json
import os import os
from aiohttp import web from aiohttp import web
from matrix_client.client import MatrixClient from nio import AsyncClient
from nio.rooms import MatrixRoom
SERVER_ADDRESS = ('', int(os.environ.get('PORT', 4785))) SERVER_ADDRESS = ('', int(os.environ.get('PORT', 4785)))
MATRIX_URL = os.environ.get('MATRIX_URL', 'https://matrix.org') MATRIX_URL = os.environ.get('MATRIX_URL', 'https://matrix.org')
MATRIX_ID = os.environ.get('MATRIX_ID', 'wwm') MATRIX_ID = os.environ.get('MATRIX_ID', '@wwm:matrix.org')
MATRIX_PW = os.environ['MATRIX_PW'] MATRIX_PW = os.environ['MATRIX_PW']
API_KEY = os.environ['API_KEY'] API_KEY = os.environ['API_KEY']
CLIENT = AsyncClient(MATRIX_URL, MATRIX_ID)
client = MatrixClient(MATRIX_URL)
client.login(username=MATRIX_ID, password=MATRIX_PW)
rooms = client.get_rooms()
async def handler(request): async def handler(request):
@ -27,32 +27,40 @@ async def handler(request):
Coroutine given to the server, st. it knows what to do with an HTTP request. 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. This one handles a POST, checks its content, and forwards it to the matrix room.
""" """
data = json.loads(request.read().decode()) data = await request.read()
data = json.loads(data.decode())
status, ret = 400, 'I need a json dict with text & key' status, ret = 400, 'I need a json dict with text & key'
if all(key in data for key in ['text', 'key']): if all(key in data for key in ['text', 'key']):
status, ret = 401, 'I need the good "key"' status, ret = 401, 'I need the good "key"'
if data['key'] == API_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' status, ret = 200, 'OK'
if request.rel_url[1:] not in rooms: await CLIENT.room_send(room_id=str(request.rel_url)[1:],
# try to see if this room has been joined recently message_type="m.room.message",
rooms = client.get_rooms() content={
if request.rel_url[1:] in rooms: "msgtype": "m.text",
status, ret = 200, json.dumps(rooms[request.rel_url[1:]].send_text(data['text'])) "body": data['text'],
})
return web.Response(text='{"status": %i, "ret": "%a"}' % (status, ret), return web.Response(text='{"status": %i, "ret": "%s"}' % (status, ret),
content_type='application/json', content_type='application/json',
status=status) status=status)
async def main(): async def main():
"""
Main coroutine
matrix client login & start web server
"""
await CLIENT.login(MATRIX_PW)
server = web.Server(handler) server = web.Server(handler)
runner = web.ServerRunner(server) runner = web.ServerRunner(server)
await runner.setup() await runner.setup()
site = web.TCPSite(runner, *SERVER_ADDRESS) site = web.TCPSite(runner, *SERVER_ADDRESS)
await site.start() await site.start()
print("======= Serving ======")
# pause here for very long time by serving HTTP requests and # pause here for very long time by serving HTTP requests and
# waiting for keyboard interruption # waiting for keyboard interruption
await asyncio.sleep(100 * 3600) await asyncio.sleep(100 * 3600)