main.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python3
  2. """
  3. wifi-with-matrix script.
  4. Bridge between https://code.ffdn.org/FFDN/wifi-with-me & a matrix room
  5. """
  6. import json
  7. import os
  8. from http.server import BaseHTTPRequestHandler, HTTPServer
  9. from matrix_client.client import MatrixClient
  10. SERVER_ADDRESS = ('', int(os.environ.get('PORT', 4785)))
  11. MATRIX_URL = os.environ.get('MATRIX_URL', 'https://matrix.org')
  12. MATRIX_ID = os.environ.get('MATRIX_ID', 'wwm')
  13. MATRIX_PW = os.environ['MATRIX_PW']
  14. ROOM_ID = os.environ['ROOM_ID']
  15. API_KEY = os.environ['API_KEY']
  16. class WWMBotServer(HTTPServer):
  17. """
  18. an HTTPServer that also contain a matrix client
  19. """
  20. def __init__(self, *args, **kwargs):
  21. super().__init__(*args, **kwargs)
  22. client = MatrixClient(MATRIX_URL)
  23. client.login(username=MATRIX_ID, password=MATRIX_PW)
  24. self.room = client.get_rooms()[ROOM_ID]
  25. class WWMBotForwarder(BaseHTTPRequestHandler):
  26. """
  27. Class given to the server, st. it knows what to do with a request.
  28. This one handles the HTTP request, and forwards it to the matrix room.
  29. """
  30. def do_POST(self):
  31. """
  32. main method, get a json dict from wifi-with-me, send a message to a matrix room
  33. """
  34. length = int(self.headers.get('Content-Length'))
  35. data = json.loads(self.rfile.read(length).decode())
  36. status = 'I need a json dict with text & key'
  37. if all(key in data for key in ['text', 'key']):
  38. status = 'wrong key'
  39. if data['key'] == API_KEY:
  40. status = 'OK'
  41. self.server.room.send_text(data['text'])
  42. self.send_response(200 if status == 'OK' else 401)
  43. self.send_header('Content-Type', 'application/json')
  44. self.end_headers()
  45. self.wfile.write(b"{'status': %a}" % status)
  46. if __name__ == '__main__':
  47. print('Wifi-With-Matrix bridge starting…')
  48. WWMBotServer(SERVER_ADDRESS, WWMBotForwarder).serve_forever()