2022-11-13 10:07:08 +00:00
|
|
|
import logging
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
import socketio
|
|
|
|
from observable import Observable
|
|
|
|
|
|
|
|
try:
|
|
|
|
import tomllib
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
import tomli as tomllib
|
|
|
|
|
|
|
|
from .models import as_dataclass
|
|
|
|
|
|
|
|
|
|
|
|
class Client:
|
2022-11-14 19:29:08 +00:00
|
|
|
logger = logging.getLogger("socketio.client")
|
2022-11-13 10:07:08 +00:00
|
|
|
|
|
|
|
def __init__(self, token=None):
|
|
|
|
self.token = token or self._token_from_toml()
|
|
|
|
self.sio = socketio.Client()
|
|
|
|
self.sio.on("connect", self.connect_handler)
|
|
|
|
self.sio.on("event", self.event_handler)
|
|
|
|
self.sio.on("disconnect", self.disconnect_handler)
|
|
|
|
self.obs = Observable()
|
2022-11-14 19:29:08 +00:00
|
|
|
self.streamlabs = ("donation",)
|
|
|
|
self.twitch = ("follow", "subscription", "host", "bits", "raids")
|
|
|
|
self.youtube = ("follow", "subscription", "superchat")
|
2022-11-13 10:07:08 +00:00
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
self.sio.connect(f"https://sockets.streamlabs.com?token={self.token}")
|
|
|
|
return self
|
|
|
|
|
|
|
|
def _token_from_toml(self) -> str:
|
|
|
|
filepath = Path.cwd() / "config.toml"
|
|
|
|
with open(filepath, "rb") as f:
|
|
|
|
conn = tomllib.load(f)
|
|
|
|
assert "token" in conn.get("streamlabs")
|
|
|
|
return conn["streamlabs"].get("token")
|
|
|
|
|
|
|
|
def connect_handler(self):
|
2022-11-14 19:29:08 +00:00
|
|
|
self.logger.info("Connected to Streamlabs Socket API")
|
2022-11-13 10:07:08 +00:00
|
|
|
|
|
|
|
def event_handler(self, data):
|
2022-11-14 19:29:08 +00:00
|
|
|
if "for" in data and data["type"] in set(
|
|
|
|
self.streamlabs + self.twitch + self.youtube
|
|
|
|
):
|
|
|
|
self.obs.trigger(
|
|
|
|
data["for"],
|
|
|
|
data["type"],
|
|
|
|
as_dataclass(data["type"], *data["message"]),
|
|
|
|
)
|
2022-11-13 10:07:08 +00:00
|
|
|
|
|
|
|
def disconnect_handler(self):
|
2022-11-14 19:29:08 +00:00
|
|
|
self.logger.info("Disconnected from Streamlabs Socket API")
|
2022-11-13 10:07:08 +00:00
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self.sio.disconnect()
|
|
|
|
|
|
|
|
|
|
|
|
def connect(**kwargs):
|
|
|
|
SIO_cls = Client
|
|
|
|
return SIO_cls(**kwargs)
|