How to build a Lightning Baccarat Telegram bot
Step by step to post every Lightning Baccarat round to a Telegram group: create the bot, hook it to the API stream, format the cards and avoid repeats.
Published on October 30, 2026 · 7 min read
A Lightning Baccarat Telegram bot is the most common project on top of a results API, and also the quickest to finish: a new bot, an API key and about seventy lines of Python. This guide goes from zero to the bot posting every hand to the group, with the whole code — no framework and no dependency beyond an HTTP library.
By the end, each round becomes a message like this:
♦ Lightning Baccarat · 15:42:31 Player K♥ 9♦ → 9 Banker 5♣ 2♠ 7♥ → 4 Winner: PLAYER (natural) Last 20: P B B P T P B P P B
What you need before you start
- A Telegram bot. Talk to @BotFather, send
/newbot, pick a name and a username. It gives you a token, which is the bot's password: keep it out of your code. - The group id. Add the bot to the group, send any message there and open
https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates. The group'schat.idis in there, and in groups it is negative (something like-1001234567890). - A Lightning Baccarat API key. Create your LynxMetrics account, confirm your email and open the 2-hour trial in the dashboard. It uses Pro plan limits and asks for no card, so you can finish the whole bot before subscribing. Each round's fields are in the API overview.
If the bot is going to post to a group, make it an administrator only if you need to: to just send messages, an ordinary member is enough.
Where the bot receives rounds
The API offers two paths, and for a bot the choice is clear: /stream. It keeps a connection open and delivers the hand the moment it is stored, without you asking — which, besides being faster, spends one request from your per-minute limit instead of twenty. The full comparison is in live results.
The whole bot
Install the HTTP library and keep the secrets in the environment:
pip install httpx export LYNX_KEY="sk-lynx..." export TG_TOKEN="123456:ABC..." export TG_CHAT="-1001234567890"
bot.py
import json
import os
import time
from collections import deque
import httpx
LYNX_KEY = os.environ["LYNX_KEY"]
TG_TOKEN = os.environ["TG_TOKEN"]
TG_CHAT = os.environ["TG_CHAT"]
STREAM = "https://api.lynxmetrics.com/v1/lightning-baccarat/stream"
RESULTS = "https://api.lynxmetrics.com/v1/lightning-baccarat/results"
TELEGRAM = "https://api.telegram.org/bot" + TG_TOKEN + "/sendMessage"
RANKS = {"A": "A", "T": "10", "J": "J", "Q": "Q", "K": "K"}
SUITS = {"C": "♣", "D": "♦", "H": "♥", "S": "♠"}
LETTER = {"player": "P", "banker": "B", "tie": "T"}
last_hands = deque(maxlen=20) # short history for the message footer
seen = set() # ids already posted, so nothing repeats
last_id = None # id of the most recent hand we posted
def hand(cards):
return " ".join(RANKS.get(c[0], c[0]) + SUITS[c[1]] for c in cards)
def message(round_):
data = round_["data"]
clock = round_["settledAt"][11:19]
winner = {"player": "PLAYER", "banker": "BANKER", "tie": "TIE"}[round_["outcome"]]
marks = []
if data["natural"]:
marks.append("natural")
if data["player"]["pair"]:
marks.append("Player pair")
if data["banker"]["pair"]:
marks.append("Banker pair")
extra = " (" + ", ".join(marks) + ")" if marks else ""
return "\n".join([
"♦ <b>Lightning Baccarat</b> · " + clock + " UTC",
"Player " + hand(data["player"]["cards"]) + " → <b>" + str(data["player"]["score"]) + "</b>",
"Banker " + hand(data["banker"]["cards"]) + " → <b>" + str(data["banker"]["score"]) + "</b>",
"Winner: <b>" + winner + "</b>" + extra,
"Last " + str(len(last_hands)) + ": " + " ".join(last_hands),
])
def post(round_):
global last_id
if round_["id"] in seen: # the stream's ready repeats the last hand
return
seen.add(round_["id"])
last_id = round_["id"]
last_hands.append(LETTER[round_["outcome"]])
httpx.post(
TELEGRAM,
json={"chat_id": TG_CHAT, "text": message(round_), "parse_mode": "HTML"},
timeout=15,
)
def page_from_results(since):
"""Last resort: too long an absence for the stream to recover on its own."""
while True:
response = httpx.get(
RESULTS,
headers={"x-api-key": LYNX_KEY},
params={"after": since, "limit": 250},
timeout=30,
)
body = response.json()
for round_ in body["data"]:
post(round_)
since = round_["id"]
if not body["nextCursor"]:
return
def follow():
headers = {"x-api-key": LYNX_KEY, "accept": "text/event-stream"}
if last_id: # reconnect: the API returns what closed while we were away
headers["last-event-id"] = last_id
with httpx.stream("GET", STREAM, headers=headers, timeout=None) as response:
response.raise_for_status()
event = None
for line in response.iter_lines():
if line.startswith("event:"):
event = line.split(":", 1)[1].strip()
elif line.startswith("data:"):
body = json.loads(line.split(":", 1)[1])
if event == "ready":
if body.get("resyncError") == "too_many_missed":
page_from_results(last_id)
for round_ in body.get("missed") or []:
post(round_)
if body["data"]:
post(body["data"])
elif event == "round":
post(body["data"])
elif event == "closed":
return "closed"
while True:
try:
if follow() == "closed":
print("another connection took this key's slot: exiting", flush=True)
break
except Exception as error:
print("dropped:", type(error).__name__, error, flush=True)
time.sleep(3)That is it: python bot.py and the group starts receiving hands.
The four things that separate a bot that lasts from one that dies overnight
Never repeating a message
Each round's id is fixed and never changes, which is why it is the right latch. The seen set solves two cases at once: the event: ready, which repeats the last hand on purpose when the connection opens, and the reconnect after a drop. Without that latch, every restart of the bot re-posts the previous hand.
Covering the gap from a drop
When reopening the connection, the bot sends the id of the last hand it posted in the last-event-id header. The API then returns, inside ready, a missed list with the hands that closed while it was away — up to 50, oldest first. That is what makes a two-minute outage pass without anyone in the group noticing.
Only when the absence goes beyond 50 hands, about half an hour of table time, does the stream give up and send resyncError: "too_many_missed". That is when page_from_results steps in and finishes the job through /results?after= — the same parameter as in the history article. Note the order in the code: page_from_results runs before handling the ready's data, so the messages come out in the order the hands happened.
Treating reconnection as normal
Every stream connection is closed after 6 hours, even a healthy one. Anyone running all day reconnects about four times a day, so the while True loop is not a defence against bugs: it is the expected behaviour. With last-event-id, none of those reconnects costs a hand. The same loop covers network drops and server restarts.
If an event: closed arrives, the case is different: it means another connection opened with the same key and took the slot. Reconnecting there would drop the other one, and the two copies would keep evicting each other forever — which is why the bot leaves the loop. Usually it is a second copy of the bot you forgot was running.
Not fighting Telegram's limit
Telegram accepts about 20 messages per minute in the same group. One round every 35 seconds is fewer than 2 a minute, so you have plenty of room — until you want statistics, streak alerts and hourly summaries in the same group. If it all adds up beyond the limit, Telegram answers 429 with retry_after, and it is worth respecting.
Ideas for the message
With the fields the API delivers, you can enrich it without inventing anything:
- Announce that the table is resolving the hand. The
event: phase, which you ask for with?phases=1, arrives before the cards, with theroundIdthe hand will have: you can post a "hand in progress" and then edit the same message with the result, using Telegram'seditMessageText. Store themessage_idperroundId— and know how to expire a phase that never became a hand. - Flag streaks. When
currentStreak.lengthfrom/statsgoes past 4, add a line. One request per round at most. - Call out pairs. The
pairfield on each side already says so, and it is the most followed side bet. - Hourly summary. A
/stats?sample=100every hour, with the percentages and the sample total next to them — and never the percentage alone, for the reason explained in statistics. - A text Bead Road. The
last_handsdeque already forms theP B B P Tstrip; in coloured squares it looks just like the table's chart.
Where to run it, and what not to do
The bot is light: any small VPS, a container or an always-on machine handles it, because the only work is keeping a connection open. What it cannot do is run in a serverless function with a short timeout, since the stream needs a live process — in that case, poll /latest on a cron and keep the last id somewhere.
Two security rules, worth more than the bot itself: the API key and the Telegram token never go into the repository or to the browser side, and each bot deserves its own project at LynxMetrics, with its own key — that way you can revoke one without taking the others down. Details in API security.
Frequently asked questions
- Do I need to know how to code to build a Lightning Baccarat bot?
You need the basics of Python or another language with an HTTP client. The complete code in this article is about seventy lines and uses a single library, httpx, plus the Telegram bot token and the API key.
- How does the bot avoid posting the same round twice?
By storing the id of every round it has posted. The id is fixed and never changes, and the stream's ready event repeats the last round on purpose when the connection opens, so without that latch every restart would re-post the previous hand.
- What happens to the bot when the connection drops?
It reopens the stream sending the id of the last hand posted in the last-event-id header, and the API returns in ready the hands that closed while it was away, up to 50. If the absence went beyond that, resyncError too_many_missed arrives and the bot finishes through /results?after=. Every connection is also closed every 6 hours by design, so reconnecting is normal behaviour.
- Can I run the bot for free during the trial?
Yes. The Lightning Baccarat trial lasts 2 hours with Pro plan limits, no card required, and can be repeated every 24 hours. That is enough time to finish and test the bot before subscribing.
- Can I run the bot in a serverless function?
Not with the stream, which needs a live process holding the connection open. In serverless, poll /latest on a cron, keep the id of the last round handled in some storage and post only when it changes.
For adults 18 and over only. LynxMetrics is not affiliated with Evolution or with the casinos that offer Lightning Baccarat, and it only sells data and stats, never predictions or betting tips, because every round is random and past results do not predict the next one.
Read also
- Lightning Baccarat API: endpoints, examples and limits
How LynxMetrics' Lightning Baccarat API works: every round's cards in JSON, the four endpoints, Python and Node examples, history, pricing and a free trial.
- Lightning Baccarat accuracy: a 143-round audit
The audit we ran before opening the Lightning Baccarat API: 143 rounds checked against an external source and frame by frame, and what we still watch daily.
- How Lightning Baccarat works: rules and multipliers
Evolution's Lightning Baccarat rules from the start: card values, when the third card comes out, natural, pair, and what the Lightning layer changes.