Metadata-Version: 2.4
Name: clypso-chat
Version: 0.1.1
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Rust
Classifier: Topic :: Communications :: Chat
Classifier: Typing :: Typed
Requires-Dist: pytest>=8 ; extra == 'test'
Requires-Dist: numpy>=1.26 ; extra == 'test'
Provides-Extra: test
License-File: LICENSE
Summary: Fast live chat readers for Twitch, Kick and YouTube, with hype-moment detection. Written in Rust, for Python.
Keywords: twitch,kick,youtube,live-chat,spike-detection,rust
Author: Abdullahmahi
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Issues, https://github.com/mr-Imran/clypso_chat/issues
Project-URL: Repository, https://github.com/mr-Imran/clypso_chat

# clypso-chat

[![PyPI](https://img.shields.io/pypi/v/clypso-chat)](https://pypi.org/project/clypso-chat/)
[![Python](https://img.shields.io/pypi/pyversions/clypso-chat)](https://pypi.org/project/clypso-chat/)
[![License: MIT](https://img.shields.io/pypi/l/clypso-chat)](https://pypi.org/project/clypso-chat/)

**Read live chat from Twitch, Kick and YouTube in Python, and find the moments chat goes wild.**

The readers and parsers are written in Rust. They run outside Python's GIL, so watching dozens of channels costs almost no CPU.

```python
import time
import clypso_chat as cc

with cc.Hub() as hub:
    hub.join("jynxzi", "twitch", "jynxzi")
    time.sleep(20)
    for author, text, ts in hub.drain("jynxzi"):
        print(author, ":", text)
```

```
viewer_one : !??????????!!
viewer_two : BOBCAT IS THE SAME THING
viewer_three : bro what was that
... 130 messages in 20 seconds
```

No login, API key or OAuth app is needed. Every reader is anonymous and read-only.

## Features

- **Three platforms, one API:**
  - Twitch: IRC over TLS.
  - Kick: Pusher WebSocket.
  - YouTube: the live chat feed of any live video.
- **Many channels at once:** every channel shares one small Rust runtime with one OS thread. The readers answer pings, reconnect, back off when blocked, and log what went wrong.
- **Hype detection:** a per-channel counter spots sudden chat spikes against the channel's own normal rate, and returns the moment in the stream that chat reacted to.
- **Platform events:**
  - Twitch: subs, gift bombs, bits and raids.
  - Kick: subs, gifted subs and hosts.
  - YouTube: Super Chats, Super Stickers and memberships.
- **Chat signals:**
  - For each second: messages, distinct chatters, reactions ("KEKW", "clip it", "W") and repeated lines.
  - `compact()` folds an emote wall into one line, so a burst fits in an AI prompt.
- **Fast parsing:** up to 7.6× faster than an equivalent pure-Python parser. Pure-Python details are under [Speed](#speed).
- **Typed:** full type hints. Wheels for Linux, macOS and Windows on every CPython ≥ 3.10.

## Install

```bash
pip install clypso-chat
```

Prebuilt wheels:

| Platform | Wheel |
|---|---|
| Linux x86-64 (glibc ≥ 2.17) | `manylinux_2_17_x86_64` |
| Linux ARM64 (glibc ≥ 2.28) | `manylinux_2_28_aarch64` |
| macOS Apple Silicon / Intel | `macosx_11_0_arm64` / `macosx_10_12_x86_64` |
| Windows x86-64 | `win_amd64` |

Each wheel works on every CPython ≥ 3.10. It needs no OpenSSL: TLS is rustls with Mozilla's root certificates.

Anywhere else, for example Alpine/musl or Windows ARM, pip builds from source. That needs Rust (`rustup`, stable) and a C compiler.

## Read live chat

```python
import time
import clypso_chat as cc

with cc.Hub() as hub:
    hub.join("tw", "twitch", "some_streamer")                     # Twitch channel name
    hub.join("kk", "kick", "some_streamer", room=123456)          # Kick: the chatroom id (see below)
    hub.join("yt", "youtube", "dQw4w9WgXcQ")                      # YouTube: the live video's id

    while True:
        time.sleep(1)
        for stream_id, lines in hub.drain_all():
            for author, text, ts in lines:
                print(f"[{stream_id}] {author}: {text}")
        for line in hub.logs():                                   # "kk kick chat dropped: ...", reconnects, errors
            print("log:", line)
```

- **`join(id, platform, channel)`:** starts a reader. The `id` is your own name for the stream.
- **`drain(id)` / `drain_all()`:** return the messages received since the last call, as `(author, text, epoch_seconds)` tuples.
- **`status(id)`:** returns `{connected, received, reconnects, last_error, last_message_at, events, ...}`.
- **`leave(id)`:** stops one reader. Leaving the `with` block stops them all.

## Detect hype moments

`Counter` keeps messages per second and fires when chat jumps well above the channel's recent normal rate. Use it with your own messages, or call `hub.tick(id)`, which counts the hub's messages for you.

```python
import clypso_chat as cc

counter = cc.Counter("twitch")
t = 1_000_000.0
for s in range(300):                       # 290 calm seconds at 2 msg/s, then 40 msg/s
    for _ in range(2 if s < 290 else 40):
        counter.add(t + s)
    moment = counter.tick(t + s + 1)       # call once a second
    if moment:
        print("chat exploded; the moment was at", moment - t, "s")
```

```
chat exploded; the moment was at 284.0 s
```

The moment comes a few seconds before the burst, because chat reacts after what happened on stream. That makes it the place to start a clip.

You can tune the detector with a dict (the defaults are shown):

```python
cfg = {
    "warmup_s": 120,       # seconds of chat before it may fire
    "baseline_s": 600,     # how far back "normal" is measured
    "z_on": 3.0,           # how many standard deviations above normal counts as a spike
    "min_rate": 1.5,       # and at least this many messages per second
    "chat_lag_s": 4.0,     # how far chat trails the stream
    "cooldown_s": 45.0,    # no second spike within this time
}
counter = cc.Counter("twitch", cfg)
hub = cc.Hub(cfg)
```

## Subs, gifts, raids and Super Chats

```python
for e in hub.events("tw"):
    print(e)
```

```
{'kind': 'raid', 'user': 'BigStreamer', 'amount': 1200.0, 'detail': '', 'text': '', 'ts': None}
{'kind': 'gift', 'user': 'Gifter', 'amount': 50.0, 'detail': '', 'text': '', 'ts': None}
```

| kind | Twitch | Kick | YouTube | `amount` |
|---|---|---|---|---|
| `sub` | sub, resub (`detail`: plan) | subscription | — | months |
| `gift` | gift bomb, one gifted sub | gifted subs | gifted memberships | subs |
| `bits` | cheer | — | — | bits |
| `raid` | raid | host | — | viewers |
| `superchat` | — | — | Super Chat, Super Sticker (`detail`: "$5.00") | the amount |
| `member` | — | — | new or returning member | months |

A gift bomb is counted once, not once per gifted sub. The same parsers also work on raw messages: `twitch_event(line)`, `kick_event(name, data)` and `youtube_event(item)`.

## What chat is saying

```python
chat = [(f"viewer{i}", "KEKW", 100 + i / 10) for i in range(40)]
chat += [("mod", "he fell off the bridge", 101.5), ("a", "CLIP IT", 102.0),
         ("b", "clip it!!", 102.2), ("c", "LMAOOO", 102.4)]
chat.sort(key=lambda x: x[2])

cc.signals(chat)       # per second: (second, messages, chatters, reactions, repeats)
```

```
[(100, 10, 10, 10, 9), (101, 11, 11, 10, 10), (102, 13, 13, 13, 11), (103, 10, 10, 10, 10)]
```

```python
cc.compact(chat, max=10)   # one line per reaction: (author, text, ts, times said, people)
```

```
[('viewer0', 'KEKW', 100.0, 40, 40),
 ('mod', 'he fell off the bridge', 101.5, 1, 1),
 ('a', 'CLIP IT', 102.0, 2, 2),
 ('c', 'LMAOOO', 102.4, 1, 1)]
```

- **Matching:** lines are compared by `cc.norm(text)`, which ignores case and punctuation and squashes held letters. "LMAOOO" becomes "lmao" and "KEKW KEKW KEKW" becomes "kekw".
- **Reactions:** the default list is `cc.KEYWORDS`. Pass your own with `signals(chat, keywords=[...])`.
- **Over `max`:** `compact` keeps the most repeated reactions and an even spread of the rest, in order.

## Parse single messages

To use your own connection, call the parsers directly:

```python
cc.twitch_line("@display-name=Ninja :ninja!ninja@ninja.tmi.twitch.tv PRIVMSG #chan :that was insane")
# ('Ninja', 'that was insane')
cc.kick_item({"content": "W stream", "created_at": "2026-12-01T18:00:00Z", "sender": {"username": "kickfan"}})
# ('kickfan', 'W stream', 1796148000.0)
cc.youtube_item(action)   # one item from YouTube's live chat feed → (author, text, ts)
```

## Platform notes

- **Twitch:** pass the channel name. Anonymous read-only login.
- **YouTube:** pass the id of a *live* video (the part after `watch?v=`). Chat is polled at the pace YouTube asks for.
- **Kick:**
  - Pass `room=<chatroom id>` when you know it. kick.com's channel API often blocks non-browser clients with Cloudflare; without a room the hub tries anyway and retries.
  - The chat WebSocket itself works fine. If Kick changes its public Pusher key, the log says so, and you can pass `Hub(kick_pusher_key="...")`.
- **Failures:** a Kick or YouTube reader that keeps failing waits longer each time: 10 s, 20 s, 40 s, up to 5 minutes.

## Speed

Measured against a pure-Python implementation of the same readers (4-CPU laptop, `python bench/bench.py`):

| | Python | clypso-chat | Faster |
|---|---|---|---|
| Twitch parsing, 200k lines | 0.79 s | 0.10 s | 7.6× |
| Kick parsing, 100k events | 0.61 s | 0.15 s | 4.0× |
| Spike detector, per call | 178 µs | 30 µs | 6.0× |
| 1,000,000 messages over 40 streams, read + counted | 14.9 s CPU | 1.03 s CPU | 14.5× |

On 7 real channels at about 8 messages a second, the whole hub uses about 0.1% of one core.

## API at a glance

| | |
|---|---|
| `Hub(cfg=None, *, threads=1, max_lines=20000, kick_pusher_key=None)` | `join`, `leave`, `drain`, `drain_all`, `events`, `tick`, `rates`, `quiet`, `status`, `streams`, `logs`, `close` |
| `Counter(platform="twitch", cfg=None)` | `add(ts)`, `tick(now)`, `rates`, `series`, `quiet()` |
| `spike(rates, cfg)`, `chat_quiet(rates, cfg)`, `loud_spike(db, cfg)` | the detectors on a plain list of numbers |
| `twitch_line`, `kick_item`, `youtube_item` | one message → `(author, text[, ts])` |
| `twitch_event`, `kick_event`, `youtube_event` | one message → an event dict or `None` |
| `signals`, `compact`, `norm`, `KEYWORDS` | chat signals |

Full signatures are in `clypso_chat/_native.pyi`, so your editor shows them.

## Development

```bash
pip install maturin
maturin develop --release && pytest     # 95 tests
cargo test                              # the Rust unit tests
```

The tests run each reader against local fakes of Twitch IRC, Kick's Pusher socket and YouTube's chat feed: handshakes, pings, reconnects, events and errors. `bench/smoke.py` reads a few seconds of real chat.

How it plugs into the Clypso clipping engine it was built for is described in `docs/CLYPSO.md`.

## License

MIT

