matrix-webhook/matrix_webhook.py

64 lines
2.2 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
"""
import json
2019-02-10 18:38:08 -05:00
import os
2019-02-10 16:22:09 -05:00
from http.server import BaseHTTPRequestHandler, HTTPServer
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
2019-02-17 05:46:00 -05:00
class MatrixWebhookServer(HTTPServer):
2019-02-10 18:38:08 -05:00
"""
2019-02-17 05:46:00 -05:00
an HTTPServer that embeds a matrix client
2019-02-10 18:38:08 -05:00
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
2019-02-17 05:01:40 -05:00
self.client = MatrixClient(MATRIX_URL)
self.client.login(username=MATRIX_ID, password=MATRIX_PW)
self.rooms = self.client.get_rooms()
2019-02-10 16:22:09 -05:00
2019-02-17 05:46:00 -05:00
class MatrixWebhookHandler(BaseHTTPRequestHandler):
2019-02-10 16:22:09 -05:00
"""
Class given to the server, st. it knows what to do with a request.
This one handles the HTTP request, and forwards it to the matrix room.
"""
def do_POST(self):
"""
main method, get a json dict from wifi-with-me, send a message to a matrix room
"""
length = int(self.headers.get('Content-Length'))
data = json.loads(self.rfile.read(length).decode())
2019-02-12 18:55:24 -05:00
status = 'I need a json dict with text & key'
if all(key in data for key in ['text', 'key']):
2019-02-10 19:51:35 -05:00
status = 'wrong key'
if data['key'] == API_KEY:
2019-02-17 05:01:40 -05:00
status = 'I need the id of the room as a path, and to be in this room'
if self.path[1:] not in self.server.rooms:
# try to see if this room has been joined recently
self.server.rooms = self.server.client.get_rooms()
2019-02-12 19:04:32 -05:00
if self.path[1:] in self.server.rooms:
status = 'OK'
self.server.rooms[self.path[1:]].send_text(data['text'])
2019-02-10 19:51:35 -05:00
self.send_response(200 if status == 'OK' else 401)
2019-02-10 16:22:09 -05:00
self.send_header('Content-Type', 'application/json')
self.end_headers()
2019-02-12 19:13:28 -05:00
self.wfile.write(b'{"status": "%a"}' % status)
2019-02-10 16:22:09 -05:00
if __name__ == '__main__':
2019-02-17 05:46:00 -05:00
MatrixWebhookServer(SERVER_ADDRESS, MatrixWebhookHandler).serve_forever()