mmcli/mmcli/mmws.py

40 lines
825 B
Python
Raw Normal View History

2021-03-15 00:11:50 +00:00
import sys
import json
import websocket
class MMws:
"""
2021-03-23 21:43:26 +00:00
Mattermost websocket client
2021-03-15 00:11:50 +00:00
"""
2021-03-23 21:43:26 +00:00
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
2021-03-15 00:11:50 +00:00
self.ws_url = ws_url
self.ws_handler = ws_handler
self.ws_app = None
2021-03-23 21:43:26 +00:00
def run_websocket(self):
2021-03-15 00:11:50 +00:00
def on_open(ws):
ws.send(json.dumps({
2021-03-23 21:43:26 +00:00
"seq": 1, "action": "authentication_challenge", "data": {"token": self.token}
2021-03-15 00:11:50 +00:00
}))
def on_message(ws, msg):
2021-03-23 21:43:26 +00:00
self.ws_handler(self, json.loads(msg))
2021-03-15 00:11:50 +00:00
def on_error(ws, error):
2021-03-23 21:43:26 +00:00
raise error
2021-03-15 00:11:50 +00:00
2021-03-23 21:43:26 +00:00
self.ws_app = websocket.WebSocketApp(
self.ws_url, on_open=on_open, on_message=on_message, on_error=on_error
)
2021-03-15 00:11:50 +00:00
self.ws_app.run_forever()