matrix_webhook.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python3
  2. """
  3. Matrix Webhook
  4. Post a message to a matrix room with a simple HTTP POST
  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. API_KEY = os.environ['API_KEY']
  15. class MatrixWebhookServer(HTTPServer):
  16. """
  17. an HTTPServer that embeds a matrix client
  18. """
  19. def __init__(self, *args, **kwargs):
  20. super().__init__(*args, **kwargs)
  21. self.client = MatrixClient(MATRIX_URL)
  22. self.client.login(username=MATRIX_ID, password=MATRIX_PW)
  23. self.rooms = self.client.get_rooms()
  24. class MatrixWebhookHandler(BaseHTTPRequestHandler):
  25. """
  26. Class given to the server, st. it knows what to do with a request.
  27. This one handles the HTTP request, and forwards it to the matrix room.
  28. """
  29. def do_POST(self):
  30. """
  31. main method, get a json dict from wifi-with-me, send a message to a matrix room
  32. """
  33. length = int(self.headers.get('Content-Length'))
  34. data = json.loads(self.rfile.read(length).decode())
  35. status = 'I need a json dict with text & key'
  36. if all(key in data for key in ['text', 'key']):
  37. status = 'wrong key'
  38. if data['key'] == API_KEY:
  39. status = 'I need the id of the room as a path, and to be in this room'
  40. if self.path[1:] not in self.server.rooms:
  41. # try to see if this room has been joined recently
  42. self.server.rooms = self.server.client.get_rooms()
  43. if self.path[1:] in self.server.rooms:
  44. status = 'OK'
  45. self.server.rooms[self.path[1:]].send_text(data['text'])
  46. self.send_response(200 if status == 'OK' else 401)
  47. self.send_header('Content-Type', 'application/json')
  48. self.end_headers()
  49. self.wfile.write(b'{"status": "%a"}' % status)
  50. if __name__ == '__main__':
  51. MatrixWebhookServer(SERVER_ADDRESS, MatrixWebhookHandler).serve_forever()