Clipador: chat da Kick pelo Centrifugo (a chave fixa do Pusher parou de valer)
A Kick passou a escolher o provedor de tempo real por canal (POST web.kick.com/api/v1/realtime/channels/<id>/chat/
connection) e hoje responde Centrifugo; o Pusher com a chave antiga recusava com "App key not in this cluster" e o
chat de toda fonte da Kick ficava em erro. Agora: token de convidado (/v1/realtime/auth/connection, sem login) →
connect → subscribe chatrooms.<sala>.v2; ping {} respondido; token expira e o laço reconecta. Se a Kick indicar
Pusher, usa a chave e o cluster que ela informar. Testado ao vivo no chat de kick.com/peusantista.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
dbb5e8ef92
commit
d9bf411e7a
+104
-22
@@ -1,8 +1,11 @@
|
||||
"""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.<id>.v2`). Não é API oficial: pode mudar
|
||||
sem aviso e o Cloudflare às vezes bloqueia a consulta do id da sala.
|
||||
- Kick: o mesmo tempo real que o site usa (não é API oficial: pode mudar sem aviso). Desde 11/2026 a Kick
|
||||
escolhe o provedor por canal (`POST web.kick.com/api/v1/realtime/channels/<id>/chat/connection`): hoje responde
|
||||
**Centrifugo** (token de convidado em `/v1/realtime/auth/connection`, sem login) e o Pusher com a chave fixa antiga
|
||||
passou a recusar ("App key not in this cluster"). O canal continua `chatrooms.<sala>.v2` e a mensagem tem o mesmo
|
||||
formato. 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
|
||||
@@ -19,6 +22,7 @@ import socket
|
||||
import ssl
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from typing import Callable
|
||||
|
||||
import httpx
|
||||
@@ -31,7 +35,25 @@ 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"
|
||||
KICK_API = "https://web.kick.com/api/v1/realtime"
|
||||
KICK_HEADERS = {"User-Agent": "Mozilla/5.0", "Accept": "application/json", "Origin": "https://kick.com"}
|
||||
# Pedido do site ao escolher o provedor (os dois que ele aceita). Medido 18/11/2026: a resposta é Centrifugo.
|
||||
KICK_CAPABILITIES = {"accepted_providers": [{"provider": "pusher"}, {"provider": "centrifugo"}]}
|
||||
KICK_CENTRIFUGO_DEFAULT = "wss://realtime.us-west-2.platform.kick.com/connection/websocket"
|
||||
_KICK_EMOTE = re.compile(r"\[emote:\d+:([^\]]+)\]")
|
||||
|
||||
|
||||
def kick_message(event: str, payload: object) -> tuple[str, str, list[str]] | None:
|
||||
"""Mensagem de chat da Kick → (usuário, texto, emotes), ou None se o evento não é mensagem. O `data` vem como
|
||||
texto JSON (Pusher e Centrifugo). Emotes chegam como [emote:123:NOME]: fica só o nome, que carrega a reação."""
|
||||
if not str(event).endswith("ChatMessageEvent"):
|
||||
return None
|
||||
data = json.loads(payload) if isinstance(payload, str) else (payload or {})
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
content = str(data.get("content") or "")
|
||||
user = str((data.get("sender") or {}).get("username") or "")
|
||||
return user, _KICK_EMOTE.sub(r"\1", content)[:300], _KICK_EMOTE.findall(content)
|
||||
|
||||
|
||||
class ChatReader:
|
||||
@@ -114,20 +136,84 @@ class ChatReader:
|
||||
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) ----------
|
||||
# ---------- Kick (tempo real do site, 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,
|
||||
)
|
||||
response = httpx.get(f"https://kick.com/api/v2/channels/{self.channel}", headers=KICK_HEADERS, 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:
|
||||
channel = response.json()
|
||||
room, channel_id = channel["chatroom"]["id"], channel["id"]
|
||||
client_id = str(uuid.uuid4())
|
||||
provider = self._kick_provider(channel_id, client_id)
|
||||
if provider.get("provider") == "pusher":
|
||||
self._run_kick_pusher(room, provider)
|
||||
else:
|
||||
self._run_kick_centrifugo(room, client_id, (provider.get("credentials") or {}).get("url") or KICK_CENTRIFUGO_DEFAULT)
|
||||
|
||||
def _kick_provider(self, channel_id: int, client_id: str) -> dict:
|
||||
"""Provedor de tempo real que a Kick indica para o chat deste canal ({provider, credentials}). Falha na consulta
|
||||
→ Centrifugo no endereço padrão (o que a Kick respondeu em todos os canais testados)."""
|
||||
try:
|
||||
r = httpx.post(f"{KICK_API}/channels/{channel_id}/chat/connection", headers=KICK_HEADERS, timeout=20,
|
||||
json={"client": {"id": client_id, "type": "web"}, "capabilities": KICK_CAPABILITIES})
|
||||
r.raise_for_status()
|
||||
connections = (r.json().get("data") or {}).get("connections") or []
|
||||
return connections[0] if connections else {"provider": "centrifugo"}
|
||||
except (httpx.HTTPError, ValueError, KeyError, IndexError) as exc:
|
||||
log.info("chat kick/%s: provedor não informado (%s); usando Centrifugo", self.channel, exc)
|
||||
return {"provider": "centrifugo"}
|
||||
|
||||
def _run_kick_centrifugo(self, room: int, client_id: str, url: str) -> None:
|
||||
"""Centrifugo (protocolo JSON): token de convidado → connect → subscribe `chatrooms.<sala>.v2`. O servidor manda
|
||||
`{}` como ping (responde `{}`); o token expira (~45 min) e o servidor fecha: o laço reconecta com token novo."""
|
||||
from websockets.sync.client import connect # import tardio: só quem usa Kick precisa
|
||||
|
||||
r = httpx.post(f"{KICK_API}/auth/connection", headers=KICK_HEADERS, json={"client_id": client_id}, timeout=20)
|
||||
r.raise_for_status()
|
||||
token = (r.json().get("data") or {}).get("token")
|
||||
if not token:
|
||||
raise ConnectionError("Kick não devolveu o token do chat")
|
||||
with connect(url, open_timeout=20, additional_headers={"Origin": "https://kick.com", "User-Agent": "Mozilla/5.0"}) as ws:
|
||||
ws.send(json.dumps({"connect": {"token": token, "name": "js"}, "id": 1}))
|
||||
ws.send(json.dumps({"subscribe": {"channel": f"chatrooms.{room}.v2"}, "id": 2}))
|
||||
batch, last_flush = [], time.monotonic()
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
raw = ws.recv(timeout=1.0)
|
||||
except TimeoutError:
|
||||
raw = None
|
||||
for part in (raw or "").split("\n"):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
if part == "{}":
|
||||
ws.send("{}") # ping do Centrifugo
|
||||
continue
|
||||
msg = json.loads(part)
|
||||
if msg.get("error"):
|
||||
raise ConnectionError(f"Kick (Centrifugo): {msg['error']}")
|
||||
if msg.get("id") == 2 and "subscribe" in msg:
|
||||
self.status = "connected"
|
||||
pub = (msg.get("push") or {}).get("pub") or {}
|
||||
data = pub.get("data") or {}
|
||||
item = kick_message(data.get("event", ""), data.get("data")) if isinstance(data, dict) else None
|
||||
if item:
|
||||
batch.append((time.time(), *item))
|
||||
if time.monotonic() - last_flush >= 1.0:
|
||||
self._deliver(batch)
|
||||
batch, last_flush = [], time.monotonic()
|
||||
|
||||
def _run_kick_pusher(self, room: int, provider: dict) -> None:
|
||||
"""Pusher com a chave e o cluster que a Kick informar (a chave fixa antiga parou de valer em 11/2026)."""
|
||||
from websockets.sync.client import connect
|
||||
|
||||
creds = provider.get("credentials") or {}
|
||||
key, cluster = creds.get("appKey") or creds.get("key"), creds.get("cluster") or "us2"
|
||||
if not key:
|
||||
raise ConnectionError("Kick indicou Pusher sem a chave")
|
||||
url = f"wss://ws-{cluster}.pusher.com/app/{key}?protocol=7&client=js&version=8.4.0&flash=false"
|
||||
with connect(url, 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():
|
||||
@@ -142,14 +228,10 @@ class ChatReader:
|
||||
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))
|
||||
else:
|
||||
item = kick_message(name, event.get("data") or "{}")
|
||||
if item:
|
||||
batch.append((time.time(), *item))
|
||||
if time.monotonic() - last_flush >= 1.0:
|
||||
self._deliver(batch)
|
||||
batch, last_flush = [], time.monotonic()
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Chat da Kick (18/11/2026): a Kick trocou o Pusher de chave fixa pelo Centrifugo com token de convidado.
|
||||
O formato da mensagem é o mesmo; estes testes fixam a leitura dos dois envelopes e dos emotes."""
|
||||
import json
|
||||
|
||||
from app.chat import kick_message
|
||||
|
||||
CHAT_EVENT = r"App\Events\ChatMessageEvent"
|
||||
MSG = {"id": "x", "chatroom_id": 58665335, "content": "kkkk [emote:37226:KEKW] ganhou [emote:1:GG]",
|
||||
"type": "message", "sender": {"username": "BielLopez"}}
|
||||
|
||||
|
||||
def test_kick_message_reads_user_text_and_emotes():
|
||||
user, text, emotes = kick_message(CHAT_EVENT, json.dumps(MSG))
|
||||
assert user == "BielLopez" and text == "kkkk KEKW ganhou GG" and emotes == ["KEKW", "GG"]
|
||||
|
||||
|
||||
def test_kick_message_ignores_other_events_and_accepts_dict():
|
||||
assert kick_message(r"App\Events\UserBannedEvent", json.dumps(MSG)) is None
|
||||
assert kick_message(CHAT_EVENT, MSG)[0] == "BielLopez"
|
||||
|
||||
|
||||
def test_centrifugo_push_envelope_has_the_pusher_event_inside():
|
||||
# Linha real do Centrifugo (18/11/2026, chat do peusantista), com o conteúdo trocado.
|
||||
line = json.dumps({"push": {"channel": "chatrooms.58665335.v2", "pub": {"data": {
|
||||
"event": CHAT_EVENT, "data": json.dumps(MSG)}}}})
|
||||
data = json.loads(line)["push"]["pub"]["data"]
|
||||
assert kick_message(data["event"], data["data"])[1].startswith("kkkk KEKW")
|
||||
Reference in New Issue
Block a user