main.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python
  2. """
  3. wifi-with-matrix script.
  4. Bridge between https://code.ffdn.org/FFDN/wifi-with-me & a matrix room
  5. Needs the following environment variables:
  6. - MMW_BOT_MATRIX_URL: the url of the matrix homeserver
  7. - MMW_BOT_MATRIX_ID: the user id of the bot on this server
  8. - MMW_BOT_MATRIX_PW: the password for this user
  9. - MMW_BOT_ROOM_ID: the room on which send the notifications
  10. """
  11. import os
  12. from http.server import BaseHTTPRequestHandler, HTTPServer
  13. from matrix_client.client import MatrixClient
  14. SERVER_ADDRESS = ('', int(os.environ.get('MMW_BOT_PORT', 4785)))
  15. MATRIX_URL = os.environ.get('MMW_BOT_MATRIX_URL', 'https://matrix.org')
  16. MATRIX_ID = os.environ.get('MMW_BOT_MATRIX_ID', 'wwm')
  17. MATRIX_PW = os.environ['MMW_BOT_MATRIX_PW']
  18. ROOM_ID = os.environ['MMW_BOT_ROOM_ID']
  19. class WWMBotServer(HTTPServer):
  20. """
  21. an HTTPServer that also contain a matrix client
  22. """
  23. def __init__(self, *args, **kwargs):
  24. super().__init__(*args, **kwargs)
  25. self.matrix_client = MatrixClient(MATRIX_URL)
  26. self.matrix_token = self.matrix_client.login(username=MATRIX_ID, password=MATRIX_PW)
  27. self.matrix_room = self.matrix_client.get_rooms()[ROOM_ID]
  28. class WWMBotForwarder(BaseHTTPRequestHandler):
  29. """
  30. Class given to the server, st. it knows what to do with a request.
  31. This one handles the HTTP request, and forwards it to the matrix room.
  32. """
  33. def do_POST(self):
  34. """
  35. main method, get a json dict from wifi-with-me, send a message to a matrix room
  36. """
  37. self.ret_ok()
  38. def ret_ok(self):
  39. """
  40. return a success status
  41. """
  42. self.send_response(200)
  43. self.send_header('Content-Type', 'application/json')
  44. self.end_headers()
  45. self.wfile.write(b"{'status': 'OK'}")
  46. if __name__ == '__main__':
  47. WWMBotServer(SERVER_ADDRESS, WWMBotForwarder).serve_forever()