mmcli/mmws.py
2021-03-23 22:43:26 +01:00

39 lines
825 B
Python

import sys
import json
import websocket
class MMws:
"""
Mattermost websocket client
"""
def __init__(self, ws_handler, token, ws_url):
"""
@param ws_handler: callback when new data is received on websocket
@param token: Mattermost access token
@param ws_url: websocket URL to connect to
"""
self.token = token
self.ws_url = ws_url
self.ws_handler = ws_handler
self.ws_app = None
def run_websocket(self):
def on_open(ws):
ws.send(json.dumps({
"seq": 1, "action": "authentication_challenge", "data": {"token": self.token}
}))
def on_message(ws, msg):
self.ws_handler(self, json.loads(msg))
def on_error(ws, error):
raise error
self.ws_app = websocket.WebSocketApp(
self.ws_url, on_open=on_open, on_message=on_message, on_error=on_error
)
self.ws_app.run_forever()