"""Leitura do chat ao vivo, em tempo real, para medir a reação do público. - Twitch: IRC anônimo (irc.chat.twitch.tv:6697, apelido `justinfanNNNN`): só leitura, sem conta nem token. - Kick: websocket público do Pusher usado pelo site (`chatrooms..v2`). Não é API oficial: pode mudar sem aviso e o Cloudflare às vezes bloqueia a consulta do id da sala. - YouTube: ler o chat exige a API do YouTube (cota) — ainda não suportado; a sessão segue pelo áudio. Cada leitor roda numa thread, reconecta sozinho e entrega lotes de (instante, usuário, texto) com o relógio de parede; quem chama converte para o tempo da gravação. """ from __future__ import annotations import json import logging import random import re import socket import ssl import threading import time from typing import Callable import httpx from .emotes import parse_twitch_tag log = logging.getLogger("cenaforge_clipper.chat") # (hora real, usuário, texto, emotes nativos recortados do texto) OnMessages = Callable[[list[tuple[float, str, str, list[str]]]], None] _PRIVMSG = re.compile(r"^(?:@(\S+) )?:([^!\s]+)!\S+ PRIVMSG #\S+ :(.*)$") _ROOM_ID = re.compile(r"(?:^@|;)room-id=(\d+)") KICK_PUSHER = "wss://ws-us2.pusher.com/app/32cbd69e4b950bf97679?protocol=7&client=js&version=8.4.0&flash=false" class ChatReader: def __init__(self, platform: str, channel: str, on_messages: OnMessages): self.platform, self.channel, self.on_messages = platform, channel, on_messages self.status = "off" self.received = 0 self.room_id: str | None = None # id numérico do canal na Twitch (para emotes 7TV/BTTV/FFZ) self._stop = threading.Event() self._thread: threading.Thread | None = None def start(self) -> None: if self.platform == "youtube" or not self.channel: self.status = "unsupported" return target = {"twitch": self._run_twitch, "kick": self._run_kick}[self.platform] self._thread = threading.Thread(target=self._loop, args=(target,), name=f"chat-{self.channel}", daemon=True) self._thread.start() def stop(self) -> None: self._stop.set() def _loop(self, target: Callable[[], None]) -> None: delay = 2.0 while not self._stop.is_set(): try: self.status = "connecting" target() delay = 2.0 except Exception as exc: # noqa: BLE001 - rede caiu: reconecta com espera crescente self.status = f"error: {type(exc).__name__}: {str(exc)[:120]}" log.warning("chat %s/%s: %s", self.platform, self.channel, self.status) self._stop.wait(delay) delay = min(60.0, delay * 2) self.status = "off" def _deliver(self, batch: list[tuple[float, str, str]]) -> None: if batch: self.received += len(batch) self.on_messages(batch) # ---------- Twitch (IRC) ---------- def _run_twitch(self) -> None: context = ssl.create_default_context() with socket.create_connection(("irc.chat.twitch.tv", 6697), timeout=30) as raw: with context.wrap_socket(raw, server_hostname="irc.chat.twitch.tv") as sock: sock.settimeout(1.0) nick = f"justinfan{random.randint(10000, 99999)}" # Tags trazem os emotes nativos (com posição no texto) e o room-id do canal. sock.sendall(f"CAP REQ :twitch.tv/tags\r\nNICK {nick}\r\nJOIN #{self.channel}\r\n".encode()) buffer, batch, last_flush, last_data = b"", [], time.monotonic(), time.monotonic() while not self._stop.is_set(): try: chunk = sock.recv(65536) if not chunk: raise ConnectionError("conexão fechada pela Twitch") buffer += chunk last_data = time.monotonic() except TimeoutError: pass except socket.timeout: pass *lines, buffer = buffer.split(b"\r\n") for line in lines: text = line.decode("utf-8", errors="replace") if text.startswith("PING"): sock.sendall(("PONG" + text[4:] + "\r\n").encode()) elif " 366 " in text or " JOIN #" in text: self.status = "connected" elif match := _PRIVMSG.match(text): tags, body = _parse_tags(match.group(1) or ""), match.group(3) self.room_id = self.room_id or tags.get("room-id") batch.append((time.time(), match.group(2), body[:300], parse_twitch_tag(tags.get("emotes", ""), body))) elif room := _ROOM_ID.search(text): self.room_id = self.room_id or room.group(1) if time.monotonic() - last_flush >= 1.0: self._deliver(batch) batch, last_flush = [], time.monotonic() if time.monotonic() - last_data > 360: # a Twitch manda PING a cada ~5 min raise ConnectionError("sem dados há 6 min") # ---------- Kick (Pusher, não oficial) ---------- def _run_kick(self) -> None: from websockets.sync.client import connect # import tardio: só quem usa Kick precisa response = httpx.get( f"https://kick.com/api/v2/channels/{self.channel}", headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"}, timeout=20, follow_redirects=True, ) if response.status_code != 200: raise ConnectionError(f"kick.com respondeu {response.status_code} ao buscar a sala do chat") room = response.json()["chatroom"]["id"] with connect(KICK_PUSHER, open_timeout=20) as ws: ws.send(json.dumps({"event": "pusher:subscribe", "data": {"auth": "", "channel": f"chatrooms.{room}.v2"}})) batch, last_flush = [], time.monotonic() while not self._stop.is_set(): try: raw = ws.recv(timeout=1.0) except TimeoutError: raw = None if raw: event = json.loads(raw) name = event.get("event", "") if name == "pusher_internal:subscription_succeeded": self.status = "connected" elif name == "pusher:ping": ws.send(json.dumps({"event": "pusher:pong", "data": {}})) elif name.endswith("ChatMessageEvent"): data = json.loads(event.get("data") or "{}") user = (data.get("sender") or {}).get("username", "") # Emotes da Kick chegam como [emote:123:NOME]: fica só o nome, que é o que carrega a reação. content = data.get("content", "") kick_emotes = re.findall(r"\[emote:\d+:([^\]]+)\]", content) text = re.sub(r"\[emote:\d+:([^\]]+)\]", r"\1", content) batch.append((time.time(), user, text[:300], kick_emotes)) if time.monotonic() - last_flush >= 1.0: self._deliver(batch) batch, last_flush = [], time.monotonic() def _parse_tags(raw: str) -> dict[str, str]: """`color=#F00;emotes=25:0-4;room-id=123` → dict. Só usamos ids e posições (sem desescapar valores).""" tags: dict[str, str] = {} for item in raw.split(";"): if "=" in item: key, value = item.split("=", 1) tags[key] = value return tags