# Telegram bot commands: setMyCommands, scopes and menu button

> Set Telegram bot commands with setMyCommands: naming rules, the seven scopes, language_code, the menu button and parsing /command@botname in groups.

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

`setMyCommands` sets the command list Telegram clients show for your bot, which the menu button opens by default. Each command is 1 to 32 lowercase English letters, digits or underscores, with a description of 1 to 256 characters. A list holds at most 100 commands, and you can set a separate list per scope and per language. Telegram shows each user the most specific list that exists. The rules are in [setMyCommands](https://core.telegram.org/bots/api#setmycommands) and [BotCommand](https://core.telegram.org/bots/api#botcommand), at Bot API 10.3 of August 24, 2026 (accessed 2026-11-04).

## Command naming rules

Each entry in `commands` is a BotCommand object with these fields.

| Field | Rule in the reference |
| --- | --- |
| `command` | 1 to 32 characters; "only lowercase English letters, digits and underscores" |
| `description` | 1 to 256 characters |
| `is_ephemeral` | Optional, added in Bot API 10.2; true if the command sends an ephemeral message, "which can be seen only by the sender of the message and the bot" |

The [features page](https://core.telegram.org/bots/features#commands) is looser and allows "Latin letters, numbers and underscores." Follow the API reference, since `setMyCommands` is where the rule applies. The reference doesn't describe how ephemeral commands show up in updates. Name commands "as specific as possible." Telegram's examples are `/newlocation` or `/newrule` rather than `/new`.

Telegram requires developers to support a set of global commands and names three. `/start` "begins the interaction with the user." `/help` returns a help message with a list of commands. `/settings`, "if applicable," shows the bot's settings for this user.

## Set the default list with curl

Requests go to `https://api.telegram.org/bot<token>/setMyCommands` and take a JSON body. Telegram publishes no sample for this method. Every request and script here was written for this post from the parameter tables.

```bash
curl -X POST "https://api.telegram.org/botBOT_TOKEN/setMyCommands" \
  -H "Content-Type: application/json" \
  -d '{"commands": [{"command": "start", "description": "Start the bot"}, {"command": "help", "description": "What this bot can do"}, {"command": "settings", "description": "Your settings"}]}'
```

The method "Returns True on success," so the response is `{"ok":true,"result":true}`. Without `scope` or `language_code`, this becomes the fallback list for every user.

## Scopes and language_code

The optional `scope` object decides who sees a list. It defaults to BotCommandScopeDefault, and the reference defines seven types.

| Scope object | `type` | Extra fields |
| --- | --- | --- |
| BotCommandScopeDefault | `default` | none |
| BotCommandScopeAllPrivateChats | `all_private_chats` | none |
| BotCommandScopeAllGroupChats | `all_group_chats` | none |
| BotCommandScopeAllChatAdministrators | `all_chat_administrators` | none |
| BotCommandScopeChat | `chat` | `chat_id` |
| BotCommandScopeChatAdministrators | `chat_administrators` | `chat_id` |
| BotCommandScopeChatMember | `chat_member` | `chat_id`, `user_id` |

`chat_id` takes a chat ID or the @username of a supergroup. The chat-based scopes don't accept channel chats.

`language_code` is "A two-letter ISO 639-1 language code." A list without one applies to every user in the scope whose language has no dedicated list. Set your main list without a code, then add `es` or `pt` lists on top. The user's language arrives in `message.from.language_code`, not on the Message itself.

### How Telegram picks a list

Telegram uses the first list that is set. At each step it checks the list for the user's language before the list without one. In private chats the order is `chat`, `all_private_chats`, then `default`.

In groups and supergroups the order is `chat_member`, `chat_administrators`, `chat`, `all_chat_administrators`, `all_group_chats`, then `default`. The two administrator scopes count only for administrators. Lists don't merge. An admin who matches `all_chat_administrators` sees that list instead of `all_group_chats` or `default`, so repeat `/start` and `/help` in it. A Spanish-speaking admin also gets the admin list without a language before the Spanish default list, because scope is checked first.

### Check permissions on the server

Bot API updates "will not contain any information about the scope of a command sent by the user." A member can still type an admin command by hand. Your backend should "always verify that received commands are valid and that the user was authorized to use them regardless of scope." With a webhook, command messages arrive like any other message update. The setup is in [Telegram webhooks with secret_token](/academy/articles/telegram-bot-api-webhook-setup-secret-token/).

## Set and read lists in Python, delete with curl

The script below validates each list against the BotCommand rules, sets three lists and reads one back with `getMyCommands`. That method returns an empty array when no list is set for the scope and language. It uses only the standard library and reads the token from `TELEGRAM_BOT_TOKEN`.

```python
# set_commands.py  usage: TELEGRAM_BOT_TOKEN=BOT_TOKEN python set_commands.py
import json
import os
import re
import sys
import urllib.error
import urllib.request

BASE = os.environ.get("TELEGRAM_API_BASE", "https://api.telegram.org")
TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") or sys.exit("set TELEGRAM_BOT_TOKEN")
API = BASE + "/bot" + TOKEN
COMMAND_RE = re.compile(r"^[a-z0-9_]{1,32}$")

SHARED = [
    {"command": "start", "description": "Start the bot"},
    {"command": "help", "description": "What this bot can do"},
]
LISTS = [
    ({"type": "default"}, "", SHARED + [{"command": "settings", "description": "Your settings"}]),
    ({"type": "default"}, "es", [
        {"command": "start", "description": "Iniciar el bot"},
        {"command": "help", "description": "Qué puede hacer este bot"},
        {"command": "settings", "description": "Tu configuración"},
    ]),
    ({"type": "all_chat_administrators"}, "", SHARED + [{"command": "stats", "description": "Group statistics"}]),
]

def call(method, params):
    req = urllib.request.Request(
        f"{API}/{method}",
        data=json.dumps(params).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        try:
            return json.load(e)  # Telegram puts the error in a JSON body
        except ValueError:
            return {"ok": False, "error_code": e.code, "description": str(e.reason)}

def check(commands):
    if len(commands) > 100:
        raise ValueError("at most 100 commands per list")
    for c in commands:
        if not COMMAND_RE.match(c["command"]):
            raise ValueError(f"bad command name: {c['command']!r}")
        if not 1 <= len(c["description"]) <= 256:
            raise ValueError(f"description must be 1-256 characters: {c['command']}")

def main():
    for scope, lang, commands in LISTS:
        check(commands)
        params = {"commands": commands, "scope": scope}
        if lang:
            params["language_code"] = lang
        result = call("setMyCommands", params)
        label = f"{scope['type']} {lang or '(no language)'}"
        if not result.get("ok"):
            sys.exit(f"setMyCommands {label}: {result.get('error_code')} {result.get('description')}")
        print("set", label)

    current = call("getMyCommands", {"scope": {"type": "default"}, "language_code": "es"})
    if not current.get("ok"):
        sys.exit(f"getMyCommands: {current.get('error_code')} {current.get('description')}")
    for c in current["result"]:
        print(f"/{c['command']}  {c['description']}")

if __name__ == "__main__":
    main()
```

`check()` runs before each request, so a name such as `NewRule` or `new-rule` stops the script before Telegram sees it. When Telegram rejects a call, the response has `ok: false`, and the script prints its `error_code` and `description` before it exits. `getMyCommands` also accepts an empty string as `language_code`, which reads the list without a language.

To remove a list, call `deleteMyCommands` with the same `scope` and `language_code`. Afterwards "higher level commands will be shown to affected users," so admins here fall back to the default list.

```bash
curl -X POST "https://api.telegram.org/botBOT_TOKEN/deleteMyCommands" \
  -H "Content-Type: application/json" \
  -d '{"scope": {"type": "all_chat_administrators"}}'
```

The reference doesn't say how long clients take to show a changed list.

## Change the menu button

"In all bot chats, a menu button appears near the message field," and by default it opens the command list. [`setChatMenuButton`](https://core.telegram.org/bots/api#setchatmenubutton) changes it in one private chat, or changes the default when you leave out `chat_id`. This request sets the default button back to the command list.

```bash
curl -X POST "https://api.telegram.org/botBOT_TOKEN/setChatMenuButton" \
  -H "Content-Type: application/json" \
  -d '{"menu_button": {"type": "commands"}}'
```

The other values are `web_app`, which launches a Mini App and takes `text` plus a WebAppInfo object in `web_app`, and `default`, meaning no value was set. `getChatMenuButton` returns the current button, or the default one without `chat_id`.

## Parse /command@botname in groups

A group bot in privacy mode receives `/command@this_bot`, and a plain `/start` only when it was the last bot to post. The rules are in [why your Telegram bot doesn't see group messages](/academy/articles/telegram-bot-privacy-mode-group-messages/). Commands arrive as [MessageEntity](https://core.telegram.org/bots/api#messageentity) objects of type `bot_command`, such as `/start@jobs_bot`.

The entity's `offset` and `length` count UTF-16 code units. Python strings index code points, so an emoji before the command shifts a plain slice. The parser below slices through UTF-16 and strips `@username`. It ignores commands addressed to another bot. Pass it the `username` that `getMe` returns. Its sample messages were written for this post.

```python
# parse_command.py  usage: python parse_command.py
def utf16_slice(text, start, end=None):
    raw = text.encode("utf-16-le")
    return raw[start * 2:None if end is None else end * 2].decode("utf-16-le")

def parse_command(message, bot_username):
    """Return (command, args) for a command addressed to this bot, else None."""
    text = message.get("text", "")
    for entity in message.get("entities", []):
        if entity["type"] != "bot_command":
            continue
        end = entity["offset"] + entity["length"]
        name, _, target = utf16_slice(text, entity["offset"], end)[1:].partition("@")
        if target and target.lower() != bot_username.lower():
            return None
        return name.lower(), utf16_slice(text, end).strip()
    return None

if __name__ == "__main__":
    samples = [
        {"text": "/start@my_demo_bot spaceship",
         "entities": [{"type": "bot_command", "offset": 0, "length": 18}]},
        {"text": "\U0001F44B /help@my_demo_bot",
         "entities": [{"type": "bot_command", "offset": 3, "length": 17}]},
        {"text": "/start@other_bot",
         "entities": [{"type": "bot_command", "offset": 0, "length": 16}]},
    ]
    for message in samples:
        print(parse_command(message, "my_demo_bot"))
```

It prints `('start', 'spaceship')`, `('help', '')` and `None`. The second message starts with a wave emoji, two UTF-16 units long, so the entity's offset is 3. The first sample is the deep-link form `/start@your_bot spaceship` from the features page.

If you'd rather put buttons under a message than rely on typed commands, see [Telegram inline keyboards and callback queries](/academy/articles/telegram-bot-inline-keyboards-callback-queries/).

*Z-API Omni team*
