From 496108dc6eae8f48079e5f5be7f228662dd897b0 Mon Sep 17 00:00:00 2001 From: Guilhem Saurel Date: Mon, 11 Feb 2019 00:38:08 +0100 Subject: [PATCH] add a matrix client to the server --- main.py | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 1c1965a..112ef5a 100755 --- a/main.py +++ b/main.py @@ -2,14 +2,39 @@ """ wifi-with-matrix script. Bridge between https://code.ffdn.org/FFDN/wifi-with-me & a matrix room + +Needs the following environment variables: + - MMW_BOT_MATRIX_URL: the url of the matrix homeserver + - MMW_BOT_MATRIX_ID: the user id of the bot on this server + - MMW_BOT_MATRIX_PW: the password for this user + - MMW_BOT_ROOM_ID: the room on which send the notifications """ +import os from http.server import BaseHTTPRequestHandler, HTTPServer -SERVER_ADDRESS = ('', 4785) +from matrix_client.client import MatrixClient + +SERVER_ADDRESS = ('', int(os.environ.get('MMW_BOT_PORT', 4785))) +MATRIX_URL = os.environ.get('MMW_BOT_MATRIX_URL', 'https://matrix.org') +MATRIX_ID = os.environ.get('MMW_BOT_MATRIX_ID', 'wwm') +MATRIX_PW = os.environ['MMW_BOT_MATRIX_PW'] +ROOM_ID = os.environ['MMW_BOT_ROOM_ID'] -class Forwarder(BaseHTTPRequestHandler): +class WWMBotServer(HTTPServer): + """ + an HTTPServer that also contain a matrix client + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.matrix_client = MatrixClient(MATRIX_URL) + self.matrix_token = self.matrix_client.login(username=MATRIX_ID, password=MATRIX_PW) + self.matrix_room = self.matrix_client.get_rooms()[ROOM_ID] + + +class WWMBotForwarder(BaseHTTPRequestHandler): """ 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. @@ -32,4 +57,4 @@ class Forwarder(BaseHTTPRequestHandler): if __name__ == '__main__': - HTTPServer(SERVER_ADDRESS, Forwarder).serve_forever() + WWMBotServer(SERVER_ADDRESS, WWMBotForwarder).serve_forever()