# Link a Telegram account to your app for order notifications

> Bind a Telegram chat to your user with a one-time start token, send order updates with inline buttons, and write each verified tap back to the order.

Published 2026-11-27. Z-API Omni team.

Generate a one-time token for the logged-in user, send them to `https://t.me/<bot_username>?start=<token>`, and bind the chat when `/start <token>` reaches your webhook. From then on, every order event looks up that `chat_id` and sends a message with inline buttons. A tap arrives as a `callback_query`, and you write it back to the order only after checking that the person who tapped owns it. Telegram account linking is the step that ties a Telegram chat ID to your app's user record, so your backend knows which chat receives which user's updates.

Telegram describes this exact use for deep links: "an authentication token to connect the user's Telegram account to their account on another platform" ([bot features](https://core.telegram.org/bots/features#deep-linking), accessed 2026-11-27). The parsing rules for the start parameter are in [Telegram bot deep links](/academy/articles/telegram-bot-deep-linking-start-parameter/). This post builds the whole loop around it.

## The loop from login to updated order

1. Your account page asks the service for a link, and the service stores a random token with a 10-minute expiry.
2. The user opens the link and taps Start, and the bot receives `/start <token>`.
3. The service deletes the token, stores `chat_id` and the Telegram user ID against your user, and confirms in the chat.
4. Your order system posts each event, and the service sends a message with a Cancel order button while the order is still pending.
5. A tap arrives as a `callback_query`; the service checks the owner, updates the order and edits the message.

The link step can't be skipped. "Bots can't start conversations with users. A user must either add them to a group or send them a message first" ([Telegram bots](https://core.telegram.org/bots), accessed 2026-11-27). The `/start` is both the link and the first message.

## Make the start token one-time and short-lived

Anyone who holds the link can claim it first. A link pasted into a support chat or caught in a screenshot binds whoever opens it. So the token is single-use, expires in minutes, and is deleted on the first `/start` from a private chat that carries it, valid or not.

The parameter "can be up to 64 characters long," and only "A-Z, a-z, 0-9, _ and - are allowed." `secrets.token_urlsafe(16)` gives 22 characters from that set. Keep the meaning of the token in your database, never in the token itself.

A returning user can tap an old link and send `/start <token>` again. The service then finds no token. If that chat is already linked, it says so instead of reporting an error.

### Store chat_id as a 64-bit integer

Telegram warns that a chat ID "may have more than 32 significant bits", "But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type is safe" ([Chat type](https://core.telegram.org/bots/api/types/chat), accessed 2026-11-27). Use `bigint` in Postgres. SQLite's `integer` is already 64-bit. Accept the link only from a chat whose `type` is `private`, since the values also include "group", "supergroup" and "channel".

If you want a second check at bind time, call [`getChat`](https://core.telegram.org/bots/api/methods/getchat), which returns "up-to-date information about the chat." We suggest calling it once at linking, not on every send.

## Set the webhook with the updates you need

Ask for three update types. `message` carries `/start`, `callback_query` carries the taps, and `my_chat_member` tells you when the user blocks the bot. The default empty `allowed_updates` already includes `my_chat_member`; it leaves out "chat_member, message_reaction, and message_reaction_count" ([Update type](https://core.telegram.org/bots/api/types/update), accessed 2026-11-27). Listing the three explicitly keeps the subscription independent of the default.

```bash
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"]
  }'
```

The secret token is 1 to 256 characters from `A-Z a-z 0-9 _ -`, and Telegram sends it back in `X-Telegram-Bot-Api-Secret-Token` on every request. If your server fails, Telegram says "we will repeat the request and give up after a reasonable number of attempts" ([setWebhook](https://core.telegram.org/bots/api/methods/setwebhook), accessed 2026-11-27). [Telegram webhook setup with a secret token](/academy/articles/telegram-bot-api-webhook-setup-secret-token/) covers the rest of the setup.

## The service

This file runs on Python 3.9 or later with the standard library only. SQLite holds the tables so you can try it as pasted, and each maps to a table in your own database. It has three routes: `/link-token` and `/events/order` for your backend, and `/telegram` for the bot's webhook.

```python
# 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
```

Ask for a link, open it on your phone, then post two events.

```bash
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"}'
```

The server runs on one thread, which keeps the example free of races. The one-second pause per chat then blocks other requests while it waits. In production, put sends on a queue with a worker per chat, as in [WhatsApp outbound send queue and rate limiter](/academy/articles/whatsapp-outbound-send-queue-rate-limiter/), and keep the tables in your database.

## The message you send

`sendMessage` takes `text` of "1-4096 characters after entities parsing" and the keyboard in `reply_markup`. "On success, the sent Message is returned" ([sendMessage](https://core.telegram.org/bots/api/methods/sendmessage), accessed 2026-11-27). The service stores that message's `chat.id` and `message_id` on the order.

Telegram has no template categories or service window, so the rules here are your own. Send order facts, not offers, and only to chats that linked on purpose. The Cancel order button appears only while the order is pending. The shipped update carries no button, because nothing on it can change.

Telegram's FAQ sets the pace: "In a single chat, avoid sending more than one message per second," and "bots are not able to broadcast more than about 30 messages per second" ([bots FAQ](https://core.telegram.org/bots/faq), accessed 2026-11-27). The service waits a second between messages to one chat, and honors `retry_after` on a 429 as described in [Telegram Bot API limits and retry_after](/academy/articles/telegram-bot-api-rate-limits-flood-429/).

## The tap you receive and the write-back

A press arrives as a `callback_query` with your `callback_data` in `data`. The mechanics of `answerCallbackQuery` and editing in place are in [Telegram inline keyboards and callback queries](/academy/articles/telegram-bot-inline-keyboards-callback-queries/).

### Check who tapped

`callback_data` is a string you wrote, and a string alone proves nothing about who pressed it. Before the write, the service checks that `callback_query.from.id` equals the Telegram user ID stored for the order's owner. A mismatch gets a short answer and no write. Telegram doesn't make this check for you.

The write is a conditional update: `status = 'cancelled' where id = ? and status = 'pending'`. A second tap, or a tap after the order shipped, changes no row. The service then tells the user that the order can no longer be cancelled here.

### Handle message and inline_message_id

[Bot API 10.5](https://core.telegram.org/bots/api-changelog) of November 22, 2026 added the `callback_query_mode` setting, with `"default"`, `"auto"` or `"inline"`. With `inline`, "the field inline_message_id is always used instead of the field message." So a tap on a message your bot sent can arrive without `message`. The service edits through `inline_message_id` when present and through `chat_id` plus `message_id` otherwise. [Bot API 10.5 and setMySettings](/academy/articles/telegram-bot-api-10-5-getme-botfullinfo-setmysettings/) covers the setting.

Bot API 10.4 of November 9, 2026 also allows ephemeral replies to callback queries, through `ephemeral_message_parameters`. The changelog says nothing about how long they persist, so the service edits the message instead.

## When the loop breaks

### The user blocks the bot

For private chats, `my_chat_member` "is received only when the bot is blocked or unblocked by the user." The service sets `active = 0` when the new status is `kicked` and back to 1 otherwise. We didn't verify the `kicked` value against the ChatMember reference, so block and unblock the bot once in a test and log `new_chat_member.status` before you rely on it. Order events for an inactive link skip the send. The Bot API reference doesn't list the error strings a blocked send returns, so don't parse them.

### Telegram repeats an update

`update_id` values "increase sequentially", which Telegram says helps "ignore repeated updates." The service stores each one with a primary key and drops repeats. After a week with no updates, the next ID is random, so dedupe on the stored set rather than on "greater than the last one."

### Your order system retries an event

`order_events` has a primary key on order and event. A repeated `placed` returns `{"duplicate": true}` and sends nothing. A timeout in `tg` after Telegram accepted a message can still produce a second copy on retry.

### No tap comes back

No tap means no write. The order ships on schedule, and the shipped message replaces the need for an answer.

## LoginUrl as the alternative

If the user starts on Telegram rather than on your site, a `login_url` button opens your site with their Telegram identity attached. Telegram calls it a way "to automatically authorize a user", and "a great replacement for the Telegram Login Widget when the user is coming from Telegram" ([LoginUrl](https://core.telegram.org/bots/api/types/loginurl), accessed 2026-11-27). Set `request_write_access` to true to ask permission for the bot to message the user. The reference adds: "You must always check the hash of the received data". Use the start token when the user is logged in on your site, and LoginUrl when they begin in the chat.

The same order loop on WhatsApp needs templates and consent, as shown in [Supabase database webhooks to WhatsApp notifications](/academy/articles/supabase-database-webhook-whatsapp-notification/).

## Where Z-API Omni fits

Z-API Omni includes Telegram in the same subscription as WhatsApp, Messenger and Instagram. A bot connects as a `BOT_TELEGRAM` channel with its BotFather token. There is no window and there are no templates: you can send at any time, "as long as the user has started the bot at least once." Buttons go out as `INTERACTIVE_BUTTON`, with at most three `attachments` of `id` and `title`.

Test the identifier first. The docs list the contact identifier as the bot username (`@my_bot`), which can't address a user, so check which `recipient.identifier` reaches a linked chat. The docs also don't say whether connecting the bot sets its webhook. If it does, a `setWebhook` of your own would take updates away from that connection, so pick one receiver.

<!-- TODO:test Omni snippet: which recipient.identifier addresses a Telegram user, whether /start and the chat id arrive in MESSAGE_RECEIVED, the button-tap payload, and whether connecting the bot sets its webhook -->

```bash
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" }
      ]
    }
  }'
```

[View documentation](https://developer.omni.z-api.io/en)

*Z-API Omni team*
