# Brazilian Roulette Telegram bot: every spin in your group

> A Telegram bot that posts every Brazilian Roulette spin in your group, in 60 lines of Python on top of the API's /stream, with reconnection and no repeated messages.

Source: https://lynxmetrics.com/en/blog/roleta-brasileira/brazilian-roulette-telegram-bot · Published on 2026-11-21, updated on 2026-11-21

A **Brazilian Roulette Telegram bot** posts every number from **Pragmatic Play's** table in your group the moment the
ball stops. It is about **60 lines of Python** on top of the `/stream` of the
[Roleta Brasileira API](https://lynxmetrics.com/apis/roleta-brasileira), with a single dependency. Each spin becomes a message like this:

```text
🔴 Roleta Brasileira · 22:38:40
Number 5 · red · odd · 1st dozen · column 2
Last 15: 5 26 0 14 31 8 22 17 3 36 11 29 6 19 24
```

## The three ingredients

| What | Where to get it | Cost |
| --- | --- | --- |
| A Telegram bot | [@BotFather](https://t.me/BotFather), with the `/newbot` command | Free |
| The group id | `https://api.telegram.org/bot<TOKEN>/getUpdates` after sending a message in the group | Free |
| A Roleta Brasileira key | LynxMetrics dashboard, on the trial or a subscription | Free trial, or R$ 21.90 a month on Pro |

The **group id is negative**, something like `-1001234567890`. If yours is positive, it is the id of your private chat
with the bot.

## The whole bot

```bash
pip install httpx
export LYNX_KEY="sk-lynx..."
export TG_TOKEN="123456:ABC..."
export TG_CHAT="-1001234567890"
```

```python | bot.py
import json
import os
import time
from collections import deque

import httpx

LYNX_KEY = os.environ["LYNX_KEY"]
TELEGRAM = "https://api.telegram.org/bot" + os.environ["TG_TOKEN"] + "/sendMessage"
TG_CHAT = os.environ["TG_CHAT"]
STREAM = "https://api.lynxmetrics.com/v1/roleta-brasileira/stream"

BALL = {"red": "🔴", "black": "⚫", "green": "🟢"}
ORDINAL = {1: "1st", 2: "2nd", 3: "3rd"}
last = deque(maxlen=15)
posted = set()       # ids already posted: the guard against repeated messages
last_event = None    # to reconnect without losing a spin


def message(spin):
    d = spin["data"]
    parts = [f"Number {d['number']}", spin["outcome"] if d["number"] else "zero"]
    if d["number"] != 0:
        parts += [d["parity"], f"{ORDINAL[d['dozen']]} dozen", f"column {d['column']}"]
    last.appendleft(str(d["number"]))
    return (
        f"{BALL[spin['outcome']]} Roleta Brasileira · {spin['settledAt'][11:19]}\n"
        + " · ".join(parts)
        + "\nLast 15: " + " ".join(last)
    )


def post(spin):
    if spin["id"] in posted:
        return
    posted.add(spin["id"])
    httpx.post(TELEGRAM, json={"chat_id": TG_CHAT, "text": message(spin)}, timeout=10)


def listen():
    global last_event
    headers = {"x-api-key": LYNX_KEY, "accept": "text/event-stream"}
    if last_event:
        headers["last-event-id"] = last_event
    with httpx.stream("GET", STREAM, headers=headers, timeout=httpx.Timeout(10, read=60)) as r:
        r.raise_for_status()
        event, data = None, []
        for line in r.iter_lines():
            if line.startswith("id:"):
                last_event = line[3:].strip()
            elif line.startswith("event:"):
                event = line[6:].strip()
            elif line.startswith("data:"):
                data.append(line[5:])
            elif line == "" and data:
                body = json.loads("".join(data))
                if event == "round":
                    post(body["data"])
                elif event == "ready":  # on the way back, the spins that settled while the bot was away
                    for spin in body.get("missed") or []:
                        post(spin)
                event, data = None, []


wait = 1
while True:
    try:
        listen()
        wait = 1
    except Exception as error:
        print("dropped:", error, "| back in", wait, "s")
        time.sleep(wait)
        wait = min(wait * 2, 60)
```

## What makes a bot last for months

1. **It reconnects on its own, with a growing wait.** If the network drops, the final loop retries in 1, 2, 4 seconds,
   up to a minute, without hammering the API.
2. **It loses no spin on a drop.** The bot keeps the `id` of the last spin and sends it in `last-event-id` when it
   reconnects: the first event of the new connection, `ready`, carries in `missed` what settled while it was away
   (up to 50 spins), and the bot posts those before moving on.
3. **It never repeats a message.** Each spin's `id` is fixed, so the `posted` set stops a resent spin from becoming a
   double message in the group.
4. **It uses almost none of the limit.** The open connection counts as one request; the rest of the plan limit stays
   free. The comparison with `/latest` is in
   [Brazilian Roulette live results](https://lynxmetrics.com/blog/roleta-brasileira/brazilian-roulette-live-results).

To keep the bot up 24 hours a day, see [where to host a bot](https://lynxmetrics.com/blog/where-to-host-a-bot).

## Ideas to go further

- An hourly summary with the dozens and columns, taken from `/stats`
  ([Brazilian Roulette statistics](https://lynxmetrics.com/blog/roleta-brasileira/brazilian-roulette-statistics)).
- An alert when the same color comes up eight times in a row, reading `currentStreak`.
- The same bot for [Roleta ao Vivo](https://lynxmetrics.com/apis/roleta-ao-vivo), changing only the address: the format is the same.

> An honest bot posts what happened. Promising to hit the next number is selling something that does not exist: every
> spin is independent of the previous ones.

## Frequently asked questions

### Do I need a server for the Brazilian Roulette bot?

To stay up 24 hours a day, yes: a computer that stays on or simple hosting is enough, because the bot uses little memory and a single connection.

### Does the bot lose spins if the internet drops?

No, as long as it sends the last-event-id when reconnecting, as the code in this article does: the API resends the spins that settled while it was away, up to 50.

### Can I test the Brazilian Roulette bot for free?

Yes. The API's free trial key works on /stream with the Pro plan limits, with no card.
