Telegram Bot API

Telegram Bot Commands: setMyCommands, Command Scopes and /start Deep Links

· 8 min read

Telegram bot commands are /keywords like /start or /help that Telegram apps highlight in messages, suggest when the user types / and list in the bot's menu. You set the list with /setcommands in @BotFather or with the setMyCommands method, which also supports scopes (different commands for groups, admins or one chat) and per-language lists. Your bot receives a command as an ordinary text message, and /start can carry a deep link parameter. This guide covers all of it with curl, Python and JavaScript examples.

How Telegram bot commands work

A command is just a message whose text begins with /. Registering commands doesn't change what your bot receives; it only tells Telegram apps what to suggest. The rules for the list you register with setMyCommands (the BotCommand object):

Telegram asks every bot to support the global commands /start (begin the interaction, also receives deep link parameters) and /help (what the bot can do and a list of commands), plus /settings if the bot has settings. Prefer specific commands such as /newlocation over a generic /new that needs extra arguments.

Set commands with @BotFather

The no-code way, good for a fixed list:

  1. Open @BotFather and send /setcommands.
  2. Choose your bot.
  3. Send the list, one command per line in the format command - description:
start - Start the bot
help - How to use the bot
settings - Your settings

If you don't have a bot yet, start with how to create a Telegram bot.

Set commands with setMyCommands

setMyCommands does the same from code, so the command list can live in your repository and be updated on deploy. Parameters: commands (required, array of BotCommand), scope (optional, defaults to the default scope) and language_code (optional two-letter ISO 639-1 code). It returns true:

curl "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/setMyCommands" \
  -H "Content-Type: application/json" \
  -d '{"commands":[{"command":"start","description":"Start the bot"},{"command":"help","description":"How to use the bot"}]}'

To try it without code, open setMyCommands in the Bot API Tester, paste your token, fill in the commands and press Execute. Then call getMyCommands to see the stored list.

Command scopes and languages

A scope decides who sees a list. There are 7 BotCommandScope types:

Scope typeWho sees the listExtra fields
defaultEveryone, if no narrower list applies—
all_private_chatsAll private chats with the bot—
all_group_chatsAll groups and supergroups—
all_chat_administratorsAdministrators of all groups and supergroups—
chatOne specific chatchat_id
chat_administratorsAdministrators of one group or supergroupchat_id
chat_memberOne member of one group or supergroupchat_id, user_id

chat_id is a numeric id or a supergroup @username; channels and channel direct messages chats aren't supported. Each scope can also have per-language lists: with language_code the list goes to users with that app language, without it to everyone in the scope who has no dedicated language list.

Telegram shows the first list that is set, checking from the narrowest scope down. In a private chat the order is chat → all_private_chats → default; in groups it is chat_member → chat_administrators → chat → all_chat_administrators → all_group_chats → default (the admin scopes apply only to administrators). At every step the list with the user's language_code wins over the one without.

This script sets a default list, a Russian translation and extra commands for group admins, then reads one back:

import os
import requests

TOKEN = os.environ["BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}"


def call(method, **params):
    data = requests.post(f"{API}/{method}", json=params, timeout=10).json()
    if not data["ok"]:
        raise RuntimeError(f"{method}: {data['error_code']} {data['description']}")
    return data["result"]


# Default list for everyone
call("setMyCommands", commands=[
    {"command": "start", "description": "Start the bot"},
    {"command": "help", "description": "How to use the bot"},
    {"command": "settings", "description": "Your settings"},
])

# Same commands for users whose Telegram app is in Russian
call("setMyCommands", language_code="ru", commands=[
    {"command": "start", "description": "Запустить бота"},
    {"command": "help", "description": "Как пользоваться ботом"},
    {"command": "settings", "description": "Ваши настройки"},
])

# Extra commands for administrators of all groups
call("setMyCommands", scope={"type": "all_chat_administrators"}, commands=[
    {"command": "help", "description": "How to use the bot"},
    {"command": "stats", "description": "Group statistics"},
])

print(call("getMyCommands", scope={"type": "all_chat_administrators"}))
const TOKEN = process.env.BOT_TOKEN;
const API = `https://api.telegram.org/bot${TOKEN}`;

async function call(method, params = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
  });
  const data = await res.json();
  if (!data.ok) throw new Error(`${method}: ${data.error_code} ${data.description}`);
  return data.result;
}

// Default list for everyone
await call("setMyCommands", {
  commands: [
    { command: "start", description: "Start the bot" },
    { command: "help", description: "How to use the bot" },
    { command: "settings", description: "Your settings" },
  ],
});

// Same commands for users whose Telegram app is in Russian
await call("setMyCommands", {
  language_code: "ru",
  commands: [
    { command: "start", description: "Запустить бота" },
    { command: "help", description: "Как пользоваться ботом" },
    { command: "settings", description: "Ваши настройки" },
  ],
});

// Extra commands for administrators of all groups
await call("setMyCommands", {
  scope: { type: "all_chat_administrators" },
  commands: [
    { command: "help", description: "How to use the bot" },
    { command: "stats", description: "Group statistics" },
  ],
});

console.log(await call("getMyCommands", { scope: { type: "all_chat_administrators" } }));

Scopes only control what users see. Updates don't say which scope a command came from, and users can type any command, including ones you never registered. Always check on the server that the command exists and that the user may run it (for example, check admin rights with getChatMember).

getMyCommands and deleteMyCommands

getMyCommands returns the array of BotCommand for a given scope and language_code, or an empty array if none are set. deleteMyCommands removes the list for that scope and language; affected users then see the next list in the lookup order:

curl "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/deleteMyCommands" \
  -H "Content-Type: application/json" \
  -d '{"scope":{"type":"all_chat_administrators"}}'

Handle commands and the /start parameter

Commands arrive as normal message updates with the text as typed. In groups a command may be addressed to a specific bot as /command@your_bot, so strip the @username part and ignore commands meant for other bots. Deep linking works like this:

A long polling bot that parses commands, handles /start with and without a parameter and builds a base64url deep link:

import base64
import os
import re
import requests

TOKEN = os.environ["BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}"
BOT_USERNAME = requests.get(f"{API}/getMe", timeout=10).json()["result"]["username"]
COMMAND_RE = re.compile(r"^/([A-Za-z0-9_]+)(?:@([A-Za-z0-9_]+))?(?:\s+(.*))?$", re.S)


def make_start_link(payload: str) -> str:
    # base64url without "=" padding: only A-Z a-z 0-9 _ - remain (max 64 chars)
    code = base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=")
    return f"https://t.me/{BOT_USERNAME}?start={code}"


def read_start_param(code: str) -> str:
    return base64.urlsafe_b64decode(code + "=" * (-len(code) % 4)).decode()


def parse_command(text):
    m = COMMAND_RE.match(text)
    if not m or (m[2] and m[2].lower() != BOT_USERNAME.lower()):
        return None  # not a command, or a command for another bot
    return m[1].lower(), (m[3] or "").strip()


def send(chat_id, text):
    requests.post(f"{API}/sendMessage", json={"chat_id": chat_id, "text": text}, timeout=10)


print("Share this link:", make_start_link("ref:42"))
offset = 0
while True:
    resp = requests.get(f"{API}/getUpdates", params={"offset": offset, "timeout": 30}, timeout=40).json()
    for update in resp["result"]:
        offset = update["update_id"] + 1
        msg = update.get("message")
        parsed = parse_command(msg.get("text", "")) if msg else None
        if not parsed:
            continue
        name, args = parsed
        chat_id = msg["chat"]["id"]
        if name == "start" and args:
            try:
                send(chat_id, "Welcome! You came from: " + read_start_param(args))
            except ValueError:
                send(chat_id, "Welcome! Unknown start parameter.")
        elif name == "start":
            send(chat_id, "Welcome! Send /help to see what I can do.")
        elif name == "help":
            send(chat_id, "/start - start the bot\n/help - this message\n/settings - your settings")
        elif name == "settings":
            send(chat_id, "No settings yet.")
const TOKEN = process.env.BOT_TOKEN;
const API = `https://api.telegram.org/bot${TOKEN}`;
const BOT_USERNAME = (await (await fetch(`${API}/getMe`)).json()).result.username;
const COMMAND_RE = /^\/([A-Za-z0-9_]+)(?:@([A-Za-z0-9_]+))?(?:\s+([\s\S]*))?$/;

function makeStartLink(payload) {
  // Node's base64url has no "=" padding: only A-Z a-z 0-9 _ - remain (max 64 chars)
  const code = Buffer.from(payload).toString("base64url");
  return `https://t.me/${BOT_USERNAME}?start=${code}`;
}

function readStartParam(code) {
  return Buffer.from(code, "base64url").toString("utf8");
}

function parseCommand(text) {
  const m = COMMAND_RE.exec(text);
  if (!m || (m[2] && m[2].toLowerCase() !== BOT_USERNAME.toLowerCase())) {
    return null; // not a command, or a command for another bot
  }
  return { name: m[1].toLowerCase(), args: (m[3] ?? "").trim() };
}

async function send(chatId, text) {
  await fetch(`${API}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ chat_id: chatId, text }),
  });
}

console.log("Share this link:", makeStartLink("ref:42"));
let offset = 0;
while (true) {
  const resp = await (await fetch(`${API}/getUpdates?offset=${offset}&timeout=30`)).json();
  for (const update of resp.result) {
    offset = update.update_id + 1;
    const msg = update.message;
    const parsed = msg ? parseCommand(msg.text ?? "") : null;
    if (!parsed) continue;
    const { name, args } = parsed;
    const chatId = msg.chat.id;
    if (name === "start" && args) {
      await send(chatId, "Welcome! You came from: " + readStartParam(args));
    } else if (name === "start") {
      await send(chatId, "Welcome! Send /help to see what I can do.");
    } else if (name === "help") {
      await send(chatId, "/start - start the bot\n/help - this message\n/settings - your settings");
    } else if (name === "settings") {
      await send(chatId, "No settings yet.");
    }
  }
}

Run the JavaScript version as bot.mjs with Node.js 18+ (it uses top-level await). Treat the start parameter as untrusted input: anyone can craft a link, so never put a secret in it that grants access by itself. getUpdates doesn't work while a webhook is set; for production see setting up a Telegram bot webhook.

Commands in groups and privacy mode

Bots in groups run in privacy mode by default. They then receive commands explicitly meant for them (/command@your_bot), general commands like /start only if the bot was the last bot to send a message to the group, replies to their messages and service messages. When several bots share a group, ask users to tap commands from the list, which adds the @your_bot part. To receive all messages, make the bot an admin or disable privacy mode with /setprivacy in @BotFather.

In private chats, a menu button next to the input field opens the list of commands by default. You can point it to a Mini App instead, or back to commands, with setChatMenuButton; without chat_id it changes the default for all chats:

curl "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/setChatMenuButton" \
  -H "Content-Type: application/json" \
  -d '{"menu_button":{"type":"commands"}}'

Other types are web_app (with text and web_app) and default. Since Bot API 10.2 a BotCommand can also have is_ephemeral: true: such a command sent in a group stays invisible to other members and bots, and only the bot receives it.

Best practices for bot commands

Troubleshooting

SymptomLikely causeFix
400 with BOT_COMMAND_INVALIDUppercase letters, hyphens, a leading / or more than 32 characters in commandUse 1–32 lowercase letters, digits and underscores, without the slash
Commands set, but a user sees another listA narrower scope or a list for the user's language takes priorityCheck each scope and language with getMyCommands
Bot ignores /start in a groupPrivacy mode and another bot spoke lastSend /start@your_bot, or change privacy mode
The start parameter doesn't arriveCharacters outside A-Z a-z 0-9 _ - (e.g. = padding) or more than 64 charactersEncode with base64url, strip padding, shorten the payload
401 UnauthorizedWrong or revoked tokenSee the bot token guide

Frequently asked questions

How do I add commands to my Telegram bot?

Either send /setcommands to @BotFather and pick your bot, or call the Bot API method setMyCommands with a list of BotCommand objects. Telegram apps then suggest the commands when a user types / and show them in the menu.

What characters can a Telegram bot command contain?

In setMyCommands the command text is 1–32 characters and can contain only lowercase English letters, digits and underscores. The description is 1–256 characters. At most 100 commands can be set per scope and language.

How do I pass a parameter to /start?

Use a deep link like https://t.me/your_bot?start=airplane. The bot receives the message /start airplane. The parameter can be up to 64 characters from A-Z, a-z, 0-9, _ and -; use base64url for other data.

Why does my bot not see commands in a group?

With privacy mode on (the default), a bot in a group receives commands explicitly meant for it, like /command@your_bot, and general commands like /start only if it was the last bot to send a message there. Use the @your_bot form, make the bot an admin or turn privacy mode off with /setprivacy.

How do I show different commands to group admins?

Call setMyCommands with scope set to {"type": "all_chat_administrators"} for all groups, or {"type": "chat_administrators", "chat_id": ...} for one group. Still check permissions on the server: updates don't say which scope a command came from.

How do I remove all commands from a bot?

Call deleteMyCommands for each scope and language_code you set. After deletion, users see the next list in the lookup order, for example the default commands.

How to Create a Telegram Bot: Step by Step with BotFather and Python

How to create a Telegram bot step by step: register it with @BotFather, get the token, test it with getMe and send a first message with curl or Python.

How to Deploy a Telegram Bot: VPS, Docker and Serverless Hosting

How to deploy a Telegram bot: polling vs webhook, a systemd service on a VPS, Docker, Cloudflare Workers with secret_token, plus a launch checklist.

Telegram Bot API 10.0–10.5: Bot Settings, Widgets, Rich Messages, Ephemeral Messages, Guest Mode and More

What's new in Telegram Bot API 10.0–10.5: setMySettings and BotFullInfo, HTML widgets, rich and ephemeral messages, guest mode, with JSON examples.

Telegram Bot API Errors: What Each Error Means and How to Fix It

Telegram Bot API errors explained: 400 chat not found, 403 bot was blocked by the user, 409 Conflict, 429 retry_after. Causes, fixes and handling code.

Telegram Bot API Limits: Rate Limits, 429 Errors, File Sizes and Message Length

Telegram Bot API rate limits explained: 30 msg/s, 1 msg/s per chat, 20/min in groups, handling 429 retry_after, plus file size and message length limits.

Telegram Bot Keyboards: Inline Keyboard, Callback Buttons and Reply Keyboard

Add Telegram bot buttons: inline keyboard with callback_data, answerCallbackQuery, editing the message after a press, reply keyboard and ForceReply.

n8n Telegram Integration: Connect a Telegram Bot, Trigger Workflows and Send Messages

Connect n8n to Telegram: bot token as Access Token, Telegram Trigger webhook over public HTTPS, sending messages by chat id, and fixes for common errors.

How to Send a Message with the Telegram Bot API (sendMessage)

Telegram Bot API send message guide: sendMessage with curl, Python and JavaScript, HTML and MarkdownV2 formatting, inline buttons and error fixes.

Telegram Bot Token: How to Get It, Find It Again, Check It and Keep It Safe

Telegram bot token guide: get one from @BotFather, find the token of an existing bot, check it with getMe, revoke a leaked token and store it safely.

How to Set Up a Telegram Bot Webhook: setWebhook, Secret Token and Troubleshooting

Set up a Telegram bot webhook: setWebhook URL requirements, secret_token header check, getWebhookInfo debugging, deleteWebhook and fixes for n8n.

How to Get a Telegram Chat ID for a User, Group, Channel or Topic

How to get a Telegram chat ID for a user, group, supergroup, channel or forum topic with getUpdates, plus fixes for an empty result and 409 Conflict.

Telegram Inline Bot: How to Enable Inline Mode and Answer Inline Queries

Build a Telegram inline bot: enable inline mode with @BotFather or setMySettings, handle inline_query updates and reply with answerInlineQuery.

Telegram Stars Payments for Bots: Invoices, Pre-Checkout, Refunds and Subscriptions

Accept Telegram Stars payments in your bot: sendInvoice with XTR, pre_checkout_query, successful_payment, refunds, subscriptions, Python/JS code.

Telegram Test Server: How to Test a Bot in the Telegram Test Environment

Use the Telegram test server for bots: log in to the test environment, create a test bot, call the Bot API via /test/ and switch our tester to TEST.

Telegram Widgets for Your Website: Login Widget, Post Embed, Discussion and Share Button

Add Telegram to your website: the new Telegram Login (OIDC), the legacy Login Widget with hash check code, post embeds, comments and a share button.

TelegramWidget JavaScript API: Reference, Events, Error Codes and Limits

TelegramWidget JavaScript API reference: properties, request(), events, error codes, CSS variables, widget_query and answerWidgetQuery, plus every limit.

Telegram Widget Examples: Complete HTML and Python Bot Code

Working Telegram widget examples with full code: a static order card, a counter with widget_query requests, a shared live poll and a local preview stub.

Telegram Widgets: Interactive HTML Inside Bot Messages

Telegram widgets (Bot API 10.4): what they are, how sendWidget, chat_data and public_data work, where they run today and how they differ from Mini Apps.

How to Test a Telegram Mini App: From Browser Mock to Real Telegram

Test a Telegram Mini App step by step: browser mock mode, localhost via HTTPS tunnel, test environment, DevTools per platform, initData validation.