Genera un token monouso per l’utente che ha fatto login, mandalo su https://t.me/<bot_username>?start=<token> e collega la chat quando /start <token> arriva al tuo webhook. Da quel momento, ogni evento d’ordine cerca quel chat_id e invia un messaggio con pulsanti inline. Un tocco arriva come callback_query, e lo scrivi sull’ordine solo dopo aver controllato che chi ha toccato ne sia il proprietario. Il collegamento dell’account Telegram è il passaggio che lega un chat ID di Telegram al record utente della tua app, così il tuo backend sa quale chat riceve gli aggiornamenti di quale utente.
Telegram descrive proprio questo uso dei deep link: «un token di autenticazione per collegare l’account Telegram dell’utente al suo account su un’altra piattaforma» (funzioni dei bot, consultato il 2026-11-27). Le regole di parsing del parametro start sono in deep link dei bot di Telegram. Questo articolo costruisce l’intero ciclo attorno a esso.
Il ciclo dal login all’ordine aggiornato
- La pagina del tuo account chiede un link al servizio, e il servizio salva un token casuale con una scadenza di 10 minuti.
- L’utente apre il link e tocca Start (Avvia), e il bot riceve
/start <token>. - Il servizio elimina il token, salva
chat_ide l’ID utente Telegram sul tuo utente e conferma in chat. - Il tuo sistema degli ordini invia ogni evento, e il servizio manda un messaggio con un pulsante Cancel order (Annulla ordine) finché l’ordine è ancora in attesa.
- Un tocco arriva come
callback_query; il servizio controlla il proprietario, aggiorna l’ordine e modifica il messaggio.
Il passaggio del collegamento non si può saltare. «I bot non possono avviare conversazioni con gli utenti. Un utente deve prima aggiungerli a un gruppo o inviare loro un messaggio» (bot di Telegram, consultato il 2026-11-27). Il /start è insieme il collegamento e il primo messaggio.
Rendi il token start monouso e di breve durata
Chiunque abbia il link può riscattarlo per primo. Un link incollato in una chat di assistenza o finito in uno screenshot collega chi lo apre. Quindi il token è monouso, scade in pochi minuti e viene eliminato al primo /start da una chat privata che lo contiene, valido o no.
Il parametro «può essere lungo fino a 64 caratteri», e sono ammessi solo «A-Z, a-z, 0-9, _ e -». secrets.token_urlsafe(16) produce 22 caratteri da quell’insieme. Tieni il significato del token nel tuo database, mai nel token stesso.
Un utente che torna può toccare un vecchio link e inviare di nuovo /start <token>. Il servizio allora non trova nessun token. Se quella chat è già collegata, lo dice invece di segnalare un errore.
Salva chat_id come intero a 64 bit
Telegram avverte che un chat ID «può avere più di 32 bit significativi», «ma ha al massimo 52 bit significativi, quindi un intero con segno a 64 bit o un tipo float a doppia precisione è sicuro» (tipo Chat, consultato il 2026-11-27). Usa bigint in Postgres. L’integer di SQLite è già a 64 bit. Accetta il collegamento solo da una chat il cui type è private, perché i valori includono anche “group”, “supergroup” e “channel”.
Se vuoi un secondo controllo al momento del collegamento, chiama getChat, che restituisce «informazioni aggiornate sulla chat». Ti consigliamo di chiamarlo una volta al collegamento, non a ogni invio.
Imposta il webhook con gli update che ti servono
Chiedi tre tipi di update. message porta /start, callback_query porta i tocchi, e my_chat_member ti dice quando l’utente blocca il bot. Il valore predefinito vuoto di allowed_updates include già my_chat_member; esclude «chat_member, message_reaction e message_reaction_count» (tipo Update, consultato il 2026-11-27). Elencare esplicitamente i tre rende l’iscrizione indipendente dal valore predefinito.
curl -s "https://api.telegram.org/bot$BOT_TOKEN/setWebhook" \
-H "Content-Type: application/json" \
-d '{
"url": "https://'"$PUBLIC_HOST"'/telegram",
"secret_token": "'"$WEBHOOK_SECRET"'",
"allowed_updates": ["message", "callback_query", "my_chat_member"]
}'
Il secret token va da 1 a 256 caratteri presi da A-Z a-z 0-9 _ -, e Telegram lo rimanda in X-Telegram-Bot-Api-Secret-Token a ogni richiesta. Se il tuo server fallisce, Telegram dice che «ripeteremo la richiesta e rinunceremo dopo un numero ragionevole di tentativi» (setWebhook, consultato il 2026-11-27). Configurare il webhook di Telegram con un secret token tratta il resto della configurazione.
Il servizio
Questo file gira su Python 3.9 o successivo con la sola libreria standard. SQLite contiene le tabelle, così puoi provarlo così com’è, e ognuna corrisponde a una tabella del tuo database. Ha tre route: /link-token e /events/order per il tuo backend, e /telegram per il webhook del bot.
# tg_orders.py: link a Telegram chat to an app user, send order updates with
# inline buttons, and write each verified tap back to the order.
# Python 3.9+, standard library only.
# Run: BOT_TOKEN=... BOT_USERNAME=... WEBHOOK_SECRET=... INTERNAL_TOKEN=... python3 tg_orders.py
import hmac
import json
import os
import secrets
import sqlite3
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
for name in ("BOT_TOKEN", "BOT_USERNAME", "WEBHOOK_SECRET", "INTERNAL_TOKEN"):
if not os.environ.get(name):
raise SystemExit(f"Missing environment variable {name}")
BOT_TOKEN = os.environ["BOT_TOKEN"]
BOT_USERNAME = os.environ["BOT_USERNAME"].lstrip("@")
WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"]
INTERNAL_TOKEN = os.environ["INTERNAL_TOKEN"]
PORT = int(os.environ.get("PORT", "8080"))
API = f"https://api.telegram.org/bot{BOT_TOKEN}/"
TOKEN_TTL = 10 * 60 # seconds a link stays valid
db = sqlite3.connect(os.environ.get("DB_PATH", "tg_orders.db"), isolation_level=None)
db.row_factory = sqlite3.Row
db.executescript("""
create table if not exists link_tokens (
token text primary key,
user_id text not null,
expires_at integer not null
);
create table if not exists telegram_links (
user_id text primary key,
chat_id integer not null unique, -- bigint in Postgres
telegram_user_id integer not null,
active integer not null default 1, -- 0 after the user blocks the bot
linked_at integer not null
);
create table if not exists orders (
id text primary key,
user_id text not null,
status text not null default 'pending',
tg_chat_id integer,
tg_message_id integer
);
create table if not exists order_events (
order_id text not null,
event text not null,
primary key (order_id, event)
);
create table if not exists seen_updates (update_id integer primary key);
""")
last_send = {} # chat_id -> time of the last message, for one message per second per chat
def tg(method, payload, attempt=1):
req = urllib.request.Request(
API + method, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req, timeout=15) as res:
return json.load(res)
except urllib.error.HTTPError as err:
try:
body = json.loads(err.read() or b"{}")
except ValueError:
body = {"ok": False, "description": f"HTTP {err.code}"}
retry_after = (body.get("parameters") or {}).get("retry_after")
if err.code == 429 and retry_after and attempt < 4:
time.sleep(retry_after) # wait exactly as long as Telegram asks
return tg(method, payload, attempt + 1)
return body
except (urllib.error.URLError, TimeoutError) as err:
if attempt < 4:
time.sleep(2 ** attempt)
return tg(method, payload, attempt + 1)
return {"ok": False, "description": str(err)}
def send_message(chat_id, text, keyboard=None):
wait = last_send.get(chat_id, 0) + 1.0 - time.monotonic()
if wait > 0:
time.sleep(wait)
payload = {"chat_id": chat_id, "text": text}
if keyboard:
payload["reply_markup"] = {"inline_keyboard": keyboard}
result = tg("sendMessage", payload)
last_send[chat_id] = time.monotonic()
if not result.get("ok"):
print("sendMessage failed", chat_id, result.get("description"))
return result
def create_link(user_id):
now = int(time.time())
token = secrets.token_urlsafe(16)
db.execute("delete from link_tokens where expires_at < ?", (now,))
db.execute("insert into link_tokens values (?, ?, ?)", (token, user_id, now + TOKEN_TTL))
return f"https://t.me/{BOT_USERNAME}?start={token}"
def on_start(msg, param):
chat = msg.get("chat") or {}
sender = msg.get("from") or {}
if chat.get("type") != "private" or "id" not in sender:
return
if not param:
return send_message(chat["id"], "Open the link on your account page to connect order updates.")
db.execute("begin immediate")
try:
row = db.execute("select user_id, expires_at from link_tokens where token = ?", (param,)).fetchone()
db.execute("delete from link_tokens where token = ?", (param,)) # one use, valid or not
valid = bool(row) and row["expires_at"] >= time.time()
if valid:
db.execute("delete from telegram_links where chat_id = ? and user_id <> ?", (chat["id"], row["user_id"]))
db.execute(
"""insert into telegram_links (user_id, chat_id, telegram_user_id, active, linked_at)
values (?, ?, ?, 1, ?)
on conflict(user_id) do update set chat_id = excluded.chat_id,
telegram_user_id = excluded.telegram_user_id, active = 1, linked_at = excluded.linked_at""",
(row["user_id"], chat["id"], sender["id"], int(time.time())),
)
db.execute("commit")
except Exception:
db.execute("rollback")
raise
if valid:
return send_message(chat["id"], "Connected. Updates on your orders will arrive in this chat.")
linked = db.execute("select 1 from telegram_links where chat_id = ? and active = 1", (chat["id"],)).fetchone()
text = "This chat is already connected." if linked else "This link has expired. Create a new one on your account page."
send_message(chat["id"], text)
def notify_order(order_id, user_id, event):
try:
db.execute("insert into order_events values (?, ?)", (order_id, event))
except sqlite3.IntegrityError:
return {"duplicate": True} # your order system retried this event
db.execute("insert into orders (id, user_id) values (?, ?) on conflict(id) do nothing", (order_id, user_id))
if event == "shipped":
db.execute("update orders set status = 'shipped' where id = ? and status = 'pending'", (order_id,))
link = db.execute("select chat_id from telegram_links where user_id = ? and active = 1", (user_id,)).fetchone()
if not link:
return {"sent": False, "reason": "no active Telegram link"}
if event == "placed":
text = f"Order {order_id} is confirmed and waiting to ship."
keyboard = [[{"text": "Cancel order", "callback_data": f"order:{order_id}:cancel"}]]
elif event == "shipped":
text, keyboard = f"Order {order_id} has shipped.", None
else:
return {"sent": False, "reason": f"unknown event {event}"}
result = send_message(link["chat_id"], text, keyboard)
if not result.get("ok"):
db.execute("delete from order_events where order_id = ? and event = ?", (order_id, event)) # let a retry send it
if result.get("ok"):
sent = result["result"]
db.execute(
"update orders set tg_chat_id = ?, tg_message_id = ? where id = ?",
(sent["chat"]["id"], sent["message_id"], order_id),
)
return {"sent": bool(result.get("ok"))}
def on_callback(q):
parts = (q.get("data") or "").split(":")
if len(parts) != 3 or parts[0] != "order" or parts[2] != "cancel":
return tg("answerCallbackQuery", {"callback_query_id": q["id"]})
order_id = parts[1]
owner = db.execute(
"""select l.telegram_user_id from orders o
join telegram_links l on l.user_id = o.user_id where o.id = ?""",
(order_id,),
).fetchone()
if not owner or owner["telegram_user_id"] != (q.get("from") or {}).get("id"):
return tg("answerCallbackQuery", {"callback_query_id": q["id"], "text": "This button is not for your account."})
cur = db.execute("update orders set status = 'cancelled' where id = ? and status = 'pending'", (order_id,))
done = cur.rowcount == 1
tg("answerCallbackQuery", {"callback_query_id": q["id"], "text": "Cancelled" if done else "No change"})
text = f"Order {order_id} is cancelled." if done else f"Order {order_id} can no longer be cancelled here."
if q.get("inline_message_id"):
target = {"inline_message_id": q["inline_message_id"]}
elif (q.get("message") or {}).get("chat"):
target = {"chat_id": q["message"]["chat"]["id"], "message_id": q["message"]["message_id"]}
else:
return
tg("editMessageText", {**target, "text": text, "reply_markup": {"inline_keyboard": []}})
def on_my_chat_member(update):
chat = update.get("chat") or {}
if chat.get("type") != "private":
return
status = (update.get("new_chat_member") or {}).get("status")
db.execute("update telegram_links set active = ? where chat_id = ?", (0 if status == "kicked" else 1, chat["id"]))
def handle_update(update):
try:
db.execute("insert into seen_updates values (?)", (update["update_id"],))
except (sqlite3.IntegrityError, KeyError):
return # a repeated delivery, or not an update
if "callback_query" in update:
return on_callback(update["callback_query"])
if "my_chat_member" in update:
return on_my_chat_member(update["my_chat_member"])
msg = update.get("message") or {}
parts = (msg.get("text") or "").split(maxsplit=1)
if parts and parts[0].split("@")[0] == "/start":
on_start(msg, parts[1].strip() if len(parts) == 2 else None)
class Handler(BaseHTTPRequestHandler):
def reply(self, code, body):
data = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
try:
body = json.loads(raw or b"{}")
except ValueError:
return self.reply(400, {"error": "bad json"})
if self.path == "/telegram":
got = self.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
if not hmac.compare_digest(got.encode(), WEBHOOK_SECRET.encode()):
return self.reply(401, {})
self.reply(200, {}) # answer first, then work
try:
handle_update(body)
except Exception as err: # keep serving after a bad update
print("update failed", body.get("update_id"), err)
return
auth = self.headers.get("Authorization", "")
if not hmac.compare_digest(auth.encode(), f"Bearer {INTERNAL_TOKEN}".encode()):
return self.reply(401, {})
if self.path == "/link-token" and body.get("user_id"):
return self.reply(201, {"url": create_link(str(body["user_id"]))})
if self.path == "/events/order" and body.get("order_id") and body.get("user_id") and body.get("event"):
return self.reply(200, notify_order(str(body["order_id"]), str(body["user_id"]), str(body["event"])))
return self.reply(404, {"error": "unknown route or missing fields"})
if __name__ == "__main__":
print(f"listening on {PORT}")
HTTPServer(("", PORT), Handler).serve_forever() # one thread, so token use and order updates do not race
Chiedi un link, aprilo sul telefono, poi invia due eventi.
curl -s -X POST http://localhost:8080/link-token \
-H "Authorization: Bearer $INTERNAL_TOKEN" -H "Content-Type: application/json" \
-d '{"user_id": "u-77"}'
curl -s -X POST http://localhost:8080/events/order \
-H "Authorization: Bearer $INTERNAL_TOKEN" -H "Content-Type: application/json" \
-d '{"order_id": "8812", "user_id": "u-77", "event": "placed"}'
curl -s -X POST http://localhost:8080/events/order \
-H "Authorization: Bearer $INTERNAL_TOKEN" -H "Content-Type: application/json" \
-d '{"order_id": "8812", "user_id": "u-77", "event": "shipped"}'
Il server gira su un solo thread, il che tiene l’esempio libero da race condition. La pausa di un secondo per chat però blocca le altre richieste mentre aspetta. In produzione, metti gli invii in una coda con un worker per chat, come in una coda di invio WhatsApp con limitatore di frequenza, e tieni le tabelle nel tuo database.
Il messaggio che invii
sendMessage accetta un text di «1-4096 caratteri dopo il parsing delle entità» e la tastiera in reply_markup. «In caso di successo, viene restituito il Message inviato» (sendMessage, consultato il 2026-11-27). Il servizio salva sull’ordine il chat.id e il message_id di quel messaggio.
Telegram non ha categorie di modelli né una finestra di servizio, quindi le regole qui sono tue. Invia fatti sull’ordine, non offerte, e solo alle chat che si sono collegate di proposito. Il pulsante Cancel order compare solo mentre l’ordine è in attesa. L’aggiornamento di spedizione non ha pulsanti, perché non c’è niente da cambiare.
Le FAQ di Telegram fissano il ritmo: «In una singola chat, evita di inviare più di un messaggio al secondo», e «i bot non possono trasmettere più di circa 30 messaggi al secondo» (FAQ dei bot, consultato il 2026-11-27). Il servizio aspetta un secondo tra un messaggio e l’altro verso la stessa chat, e rispetta retry_after su un 429 come descritto in limiti della Telegram Bot API e retry_after.
Il tocco che ricevi e la scrittura sull’ordine
Una pressione arriva come callback_query con il tuo callback_data in data. Il funzionamento di answerCallbackQuery e della modifica sul posto è in inline keyboard e callback query di Telegram.
Controlla chi ha toccato
callback_data è una stringa che hai scritto tu, e una stringa da sola non prova nulla su chi l’ha premuta. Prima della scrittura, il servizio controlla che callback_query.from.id sia uguale all’ID utente Telegram salvato per il proprietario dell’ordine. Se non corrisponde, riceve una breve risposta e nessuna scrittura. Telegram non fa questo controllo al posto tuo.
La scrittura è un aggiornamento condizionale: status = 'cancelled' where id = ? and status = 'pending'. Un secondo tocco, o un tocco dopo la spedizione, non cambia nessuna riga. Il servizio allora dice all’utente che l’ordine non può più essere annullato da qui.
Gestisci message e inline_message_id
La Bot API 10.5 del 22 novembre 2026 ha aggiunto l’impostazione callback_query_mode, con "default", "auto" o "inline". Con inline, «viene sempre usato il campo inline_message_id al posto del campo message». Quindi un tocco su un messaggio inviato dal tuo bot può arrivare senza message. Il servizio modifica tramite inline_message_id quando è presente, altrimenti tramite chat_id più message_id. Bot API 10.5 e setMySettings tratta l’impostazione.
La Bot API 10.4 del 9 novembre 2026 permette anche risposte effimere alle callback query, tramite ephemeral_message_parameters. Il changelog non dice quanto durano, quindi il servizio modifica invece il messaggio.
Quando il ciclo si rompe
L’utente blocca il bot
Per le chat private, my_chat_member «viene ricevuto solo quando il bot viene bloccato o sbloccato dall’utente». Il servizio imposta active = 0 quando il nuovo stato è kicked e lo riporta a 1 negli altri casi. Non abbiamo verificato il valore kicked nel riferimento ChatMember, quindi blocca e sblocca il bot una volta in un test e registra new_chat_member.status prima di farci affidamento. Gli eventi d’ordine per un collegamento inattivo saltano l’invio. Il riferimento della Bot API non elenca le stringhe di errore restituite da un invio bloccato, quindi non analizzarle.
Telegram ripete un update
I valori di update_id «aumentano in modo sequenziale», cosa che secondo Telegram aiuta a «ignorare gli update ripetuti». Il servizio li salva uno per uno con una chiave primaria e scarta le ripetizioni. Dopo una settimana senza update, l’ID successivo è casuale, quindi deduplica sull’insieme salvato e non su «maggiore dell’ultimo».
Il tuo sistema degli ordini ritenta un evento
order_events ha una chiave primaria su ordine ed evento. Un placed ripetuto restituisce {"duplicate": true} e non invia nulla. Un timeout in tg dopo che Telegram ha accettato un messaggio può comunque produrre una seconda copia al nuovo tentativo.
Non arriva nessun tocco
Nessun tocco significa nessuna scrittura. L’ordine parte nei tempi previsti, e il messaggio di spedizione rende inutile una risposta.
LoginUrl come alternativa
Se l’utente parte da Telegram invece che dal tuo sito, un pulsante login_url apre il tuo sito con la sua identità Telegram allegata. Telegram lo definisce un modo «per autorizzare automaticamente un utente», e «un ottimo sostituto del Telegram Login Widget quando l’utente arriva da Telegram» (LoginUrl, consultato il 2026-11-27). Imposta request_write_access su true per chiedere il permesso che il bot scriva all’utente. Il riferimento aggiunge: «Devi sempre controllare l’hash dei dati ricevuti». Usa il token start quando l’utente ha fatto login sul tuo sito, e LoginUrl quando inizia dalla chat.
Lo stesso ciclo degli ordini su WhatsApp richiede modelli e consenso, come mostra Database Webhook di Supabase verso notifiche WhatsApp.
Dove si colloca Z-API Omni
Z-API Omni include Telegram nello stesso abbonamento di WhatsApp, Messenger e Instagram. Un bot si collega come canale BOT_TELEGRAM con il suo token di BotFather. Non ci sono finestre né modelli: puoi inviare in qualsiasi momento, «purché l’utente abbia avviato il bot almeno una volta». I pulsanti partono come INTERACTIVE_BUTTON, con al massimo tre attachments di id e title.
Prova prima l’identificatore. La documentazione indica come identificatore del contatto lo username del bot (@my_bot), che non può indirizzare un utente, quindi verifica quale recipient.identifier raggiunge una chat collegata. La documentazione non dice nemmeno se collegare il bot imposta il suo webhook. Se lo fa, un tuo setWebhook sottrarrebbe gli update a quella connessione, quindi scegli un solo ricevitore.
curl -X POST "https://api.omni.z-api.io/v1/channels/$CHANNEL_ID/messages" \
-H "Authorization: Bearer $OMNI_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"recipient": { "identifier": "5511999999999" },
"content": {
"type": "INTERACTIVE_BUTTON",
"body": { "message": "How would you rate our service?" },
"attachments": [
{ "id": "1", "title": "Excellent" },
{ "id": "2", "title": "Good" },
{ "id": "3", "title": "Average" }
]
}
}'
Il team di Z-API Omni