matrix_webhook.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 an HTTP request.
  27. This one handles a POST, checks its content, and forwards it to the matrix room.
  28. """
  29. def do_POST(self):
  30. """
  31. get a json dict from the request, 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, ret = 400, 'I need a json dict with text & key'
  36. if all(key in data for key in ['text', 'key']):
  37. status, ret = 401, 'I need the good "key"'
  38. if data['key'] == API_KEY:
  39. status, ret = 404, '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, ret = 200, json.dumps(self.server.rooms[self.path[1:]].send_text(data['text']))
  45. self.send_response(status)
  46. self.send_header('Content-Type', 'application/json')
  47. self.end_headers()
  48. self.wfile.write(b'{"status": %i, "ret": "%a"}' % (status, ret))
  49. if __name__ == '__main__':
  50. MatrixWebhookServer(SERVER_ADDRESS, MatrixWebhookHandler).serve_forever()