-
-
Save user12986714/e5251abbdb0bb21072dfa11f34d3126e to your computer and use it in GitHub Desktop.
WS listener prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
import websocket | |
import threading | |
class Listener: | |
def __init__(self, error_room, report_rooms, notifications=None, tags=None): | |
self.error_room = error_room | |
self.report_rooms = report_rooms | |
self.notifications = notifications | |
self.tags = tags | |
self.ws_link = "whatever" | |
self.key = "secret" | |
self.ws = None | |
self.event_stop = threading.Event() | |
def on_message_handler(self, message): | |
if self.tags is not None: | |
message = self.tags.filter_post(message) | |
for each_room in self.report_rooms: | |
if self.notifications is not None: | |
this_message = self.notifications.filter_post(each_room.id, message) | |
else: | |
this_message = message | |
each_room.send_message(this_message) | |
def conn_ws(self): | |
self.ws = websocket.create_connection(self.ws_link) | |
self.ws.send(self.key) | |
def listener(self): | |
self.conn_ws() | |
while True: | |
try: | |
if self.event_stop.isSet(): | |
break | |
message = self.ws.recv() | |
if message in {"welcome", "confirmed"}: | |
continue | |
if message == "rejected": | |
raise RuntimeError("Subscription rejected.") | |
self.on_message_handler(message) | |
except RuntimeError: | |
raise | |
except Exception: | |
try: | |
self.ws.close() | |
except Exception: | |
pass | |
self.conn_ws() | |
def start(self): | |
threading.Thread(name="listener", target=self.listener, daemon=True).start() | |
def stop(self): | |
self.event_stop.set() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment