# Comandi dei bot Telegram: setMyCommands, scope e pulsante menu

> Imposta i comandi di un bot Telegram con setMyCommands: regole sui nomi, i sette scope, language_code, il pulsante menu e il parsing di /command@botname nei gruppi.

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

`setMyCommands` imposta l'elenco dei comandi che i client Telegram mostrano per il tuo bot, quello che il pulsante menu apre per impostazione predefinita. Ogni comando ha da 1 a 32 caratteri tra lettere inglesi minuscole, cifre e trattini bassi, con una descrizione da 1 a 256 caratteri. Un elenco contiene al massimo 100 comandi, e puoi impostare un elenco separato per ogni scope e per ogni lingua. Telegram mostra a ciascun utente l'elenco più specifico che esiste. Le regole sono in [setMyCommands](https://core.telegram.org/bots/api#setmycommands) e [BotCommand](https://core.telegram.org/bots/api#botcommand), alla Bot API 10.3 del 24 agosto 2026 (consultato il 2026-11-04).

## Regole per i nomi dei comandi

Ogni voce di `commands` è un oggetto BotCommand con questi campi.

| Campo | Regola nel riferimento |
| --- | --- |
| `command` | Da 1 a 32 caratteri; «solo lettere inglesi minuscole, cifre e trattini bassi» |
| `description` | Da 1 a 256 caratteri |
| `is_ephemeral` | Facoltativo, aggiunto nella Bot API 10.2; true se il comando invia un messaggio effimero, «che possono vedere solo il mittente del messaggio e il bot» |

La [pagina sulle funzioni](https://core.telegram.org/bots/features#commands) è più permissiva e ammette «lettere latine, numeri e trattini bassi». Segui il riferimento dell'API, perché la regola si applica in `setMyCommands`. Il riferimento non descrive come compaiono i comandi effimeri negli update. Dai ai comandi nomi «il più specifici possibile». Gli esempi di Telegram sono `/newlocation` o `/newrule` invece di `/new`.

Telegram chiede agli sviluppatori di supportare un insieme di comandi globali e ne nomina tre. `/start` «avvia l'interazione con l'utente». `/help` restituisce un messaggio di aiuto con l'elenco dei comandi. `/settings`, «se applicabile», mostra le impostazioni del bot per quell'utente.

## Impostare l'elenco predefinito con curl

Le richieste vanno a `https://api.telegram.org/bot<token>/setMyCommands` e accettano un corpo JSON. Telegram non pubblica esempi per questo metodo. Ogni richiesta e script di questo articolo è stato scritto a partire dalle tabelle dei parametri.

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

Il metodo «Restituisce True in caso di successo», quindi la risposta è `{"ok":true,"result":true}`. Senza `scope` né `language_code`, questo diventa l'elenco di riserva per tutti gli utenti.

## Scope e language_code

L'oggetto facoltativo `scope` decide chi vede un elenco. Il valore predefinito è BotCommandScopeDefault, e il riferimento definisce sette tipi.

| Oggetto scope | `type` | Campi aggiuntivi |
| --- | --- | --- |
| BotCommandScopeDefault | `default` | nessuno |
| BotCommandScopeAllPrivateChats | `all_private_chats` | nessuno |
| BotCommandScopeAllGroupChats | `all_group_chats` | nessuno |
| BotCommandScopeAllChatAdministrators | `all_chat_administrators` | nessuno |
| BotCommandScopeChat | `chat` | `chat_id` |
| BotCommandScopeChatAdministrators | `chat_administrators` | `chat_id` |
| BotCommandScopeChatMember | `chat_member` | `chat_id`, `user_id` |

`chat_id` accetta un chat ID o lo @username di un supergruppo. Gli scope basati sulla chat non accettano i canali.

`language_code` è «Un codice lingua ISO 639-1 di due lettere». Un elenco senza codice vale per tutti gli utenti dello scope la cui lingua non ha un elenco dedicato. Imposta l'elenco principale senza codice, poi aggiungi sopra gli elenchi `es` o `pt`. La lingua dell'utente arriva in `message.from.language_code`, non nel Message stesso.

### Come Telegram sceglie un elenco

Telegram usa il primo elenco impostato. A ogni passo controlla l'elenco per la lingua dell'utente prima di quello senza lingua. Nelle chat private l'ordine è `chat`, `all_private_chats`, poi `default`.

Nei gruppi e nei supergruppi l'ordine è `chat_member`, `chat_administrators`, `chat`, `all_chat_administrators`, `all_group_chats`, poi `default`. I due scope degli amministratori contano solo per gli amministratori. Gli elenchi non si uniscono. Un amministratore che rientra in `all_chat_administrators` vede quell'elenco al posto di `all_group_chats` o `default`, quindi ripeti lì `/start` e `/help`. Un amministratore che parla spagnolo riceve l'elenco degli amministratori senza lingua prima dell'elenco predefinito in spagnolo, perché lo scope viene controllato per primo.

### Verificare i permessi sul server

Gli update della Bot API «non contengono alcuna informazione sullo scope di un comando inviato dall'utente». Un membro può comunque digitare a mano un comando da amministratore. Il tuo backend deve «verificare sempre che i comandi ricevuti siano validi e che l'utente fosse autorizzato a usarli, indipendentemente dallo scope». Con un webhook, i messaggi di comando arrivano come qualsiasi altro update di messaggio. La configurazione è in [webhook Telegram con secret_token](/academy/it/articles/telegram-bot-api-webhook-setup-secret-token/).

## Impostare e leggere gli elenchi in Python, eliminarli con curl

Lo script qui sotto valida ogni elenco secondo le regole di BotCommand, imposta tre elenchi e ne rilegge uno con `getMyCommands`. Quel metodo restituisce un array vuoto quando non c'è un elenco per lo scope e la lingua. Usa solo la libreria standard e legge il token da `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()` viene eseguita prima di ogni richiesta, quindi un nome come `NewRule` o `new-rule` ferma lo script prima che Telegram lo veda. Quando Telegram rifiuta una chiamata, la risposta contiene `ok: false`, e lo script ne stampa `error_code` e `description` prima di uscire. `getMyCommands` accetta anche una stringa vuota come `language_code`, che legge l'elenco senza lingua.

Per rimuovere un elenco, chiama `deleteMyCommands` con gli stessi `scope` e `language_code`. Dopo, «agli utenti interessati verranno mostrati i comandi di livello superiore», quindi qui gli amministratori tornano all'elenco predefinito.

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

Il riferimento non dice quanto tempo impiegano i client a mostrare un elenco modificato.

## Cambiare il pulsante menu

«In tutte le chat con i bot, accanto al campo del messaggio compare un pulsante menu», e per impostazione predefinita apre l'elenco dei comandi. [`setChatMenuButton`](https://core.telegram.org/bots/api#setchatmenubutton) lo cambia in una singola chat privata, oppure cambia quello predefinito se ometti `chat_id`. Questa richiesta riporta il pulsante predefinito all'elenco dei comandi.

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

Gli altri valori sono `web_app`, che avvia una Mini App e accetta `text` più un oggetto WebAppInfo in `web_app`, e `default`, che indica che non è stato impostato alcun valore. `getChatMenuButton` restituisce il pulsante attuale, oppure quello predefinito senza `chat_id`.

## Analizzare /command@botname nei gruppi

Un bot di gruppo in privacy mode riceve `/command@this_bot`, e un `/start` semplice solo quando è stato l'ultimo bot a scrivere. Le regole sono in [perché il tuo bot Telegram non vede i messaggi del gruppo](/academy/it/articles/telegram-bot-privacy-mode-group-messages/). I comandi arrivano come oggetti [MessageEntity](https://core.telegram.org/bots/api#messageentity) di tipo `bot_command`, per esempio `/start@jobs_bot`.

`offset` e `length` dell'entità contano unità di codice UTF-16. Le stringhe Python sono indicizzate per code point, quindi un'emoji prima del comando sposta un normale slice. Il parser qui sotto taglia il testo in UTF-16 e rimuove `@username`. Ignora i comandi indirizzati a un altro bot. Passagli lo `username` restituito da `getMe`. I messaggi di esempio sono stati scritti per questo articolo.

```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"))
```

Stampa `('start', 'spaceship')`, `('help', '')` e `None`. Il secondo messaggio inizia con l'emoji della mano che saluta, lunga due unità UTF-16, quindi l'offset dell'entità è 3. Il primo esempio è la forma deep link `/start@your_bot spaceship` della pagina sulle funzioni.

Se preferisci mettere dei pulsanti sotto un messaggio invece di affidarti ai comandi digitati, vedi [tastiere inline e callback query dei bot Telegram](/academy/it/articles/telegram-bot-inline-keyboards-callback-queries/).

*Il team di Z-API Omni*
