matrix-webhook/main.py

61 lines
1.9 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
"""
wifi-with-matrix script.
Bridge between https://code.ffdn.org/FFDN/wifi-with-me & a matrix room
"""
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']
ROOM_ID = os.environ['ROOM_ID']
API_KEY = os.environ['API_KEY']
2019-02-10 18:38:08 -05:00
class WWMBotServer(HTTPServer):
"""
an HTTPServer that also contain a matrix client
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
2019-02-10 19:51:35 -05:00
client = MatrixClient(MATRIX_URL)
client.login(username=MATRIX_ID, password=MATRIX_PW)
self.room = client.get_rooms()[ROOM_ID]
2019-02-10 16:22:09 -05:00
2019-02-10 18:38:08 -05:00
class WWMBotForwarder(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:
status = 'OK'
2019-02-12 18:55:24 -05:00
self.server.room.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-10 19:51:35 -05:00
self.wfile.write(b"{'status': %a}" % status)
2019-02-10 16:22:09 -05:00
if __name__ == '__main__':
2019-02-10 19:29:55 -05:00
print('Wifi-With-Matrix bridge starting…')
2019-02-10 18:38:08 -05:00
WWMBotServer(SERVER_ADDRESS, WWMBotForwarder).serve_forever()