Telegram Bot API
Developer guide for creating a Telegram bot, sending messages, and handling incoming updates through Telegram's HTTP API.
The examples call Telegram directly using your bot token. Host the bot's backend in your own application and replace the example webhook URL with your application's HTTPS endpoint.
Reference checked: 20 November 2026.
Create a bot
- Open @BotFather in Telegram.
- Send
/newbotand follow the prompts to choose a name and username. - Store the issued token as the server-side secret
TELEGRAM_BOT_TOKEN. - Open your bot's chat and send
/start.
The token controls the bot; revoke and replace it through BotFather if exposed. See Telegram's bot setup tutorial.
For ordinary private chats, the user must contact the bot first. Knowing someone's phone number is not sufficient to send them a bot message. See how bots work.
Authentication and requests
The examples use Bash and cURL. Load TELEGRAM_BOT_TOKEN from your secret store, then verify it:
: "${TELEGRAM_BOT_TOKEN:?Set TELEGRAM_BOT_TOKEN before continuing}"
TELEGRAM_API="https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}"
curl --silent --show-error --fail-with-body \
"${TELEGRAM_API}/getMe"
Requests use HTTPS with the token in the URL. Successful JSON responses contain ok: true and result; failures contain ok: false, error_code, and description. Inspect optional parameters for recovery details. See the request contract.
Keep tokens out of source control, browser code, screenshots, and request logs. Redact URL paths in HTTP tracing because these URLs contain the credential. Avoid shell tracing (set -x) while running the examples.
Receive messages with long polling
Start with a new test bot that has no webhook configured. Polling and webhooks cannot be active together. See Telegram's update FAQ.
curl --silent --show-error --fail-with-body \
--max-time 40 \
-H 'Content-Type: application/json' \
-d '{"timeout":30,"allowed_updates":["message","callback_query"]}' \
"${TELEGRAM_API}/getUpdates"
Example incoming update inside the response's result array:
{
"update_id": 700001,
"message": {
"message_id": 12,
"from": {
"id": 123456789,
"is_bot": false,
"first_name": "Alex"
},
"chat": {
"id": 123456789,
"first_name": "Alex",
"type": "private"
},
"date": 1795176000,
"text": "/start"
}
}
Save message.chat.id as the destination. For the remaining examples, replace the sample value:
TELEGRAM_CHAT_ID='123456789'
After processing a batch, persist its highest update_id. Send that value plus one as offset on the next poll. For the sample above:
curl --silent --show-error --fail-with-body \
--max-time 40 \
-H 'Content-Type: application/json' \
-d '{"offset":700002,"timeout":30,"allowed_updates":["message","callback_query"]}' \
"${TELEGRAM_API}/getUpdates"
Advancing the offset acknowledges earlier updates. Only advance after durable storage or successful processing. Run one polling consumer per bot and persist the offset across restarts. See the polling acknowledgement rules.
Updates are retained for at most 24 hours. Keep your own event history if needed. See getting updates.
Send text and files
Send a plain-text message to the captured chat:
curl --silent --show-error --fail-with-body \
--data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode 'text=Your build has finished. Open the dashboard for details.' \
"${TELEGRAM_API}/sendMessage"
Text messages allow up to 4,096 characters after entity parsing. Save the returned result.message_id with the chat ID for later edits. See sendMessage.
Use plain text initially. If you add HTML or Markdown formatting, escape dynamic content for that format before sending it.
Upload a local document using multipart form data:
curl --silent --show-error --fail-with-body \
-F "chat_id=${TELEGRAM_CHAT_ID}" \
-F 'document=@./report.pdf' \
-F 'caption=Build report' \
"${TELEGRAM_API}/sendDocument"
Replace ./report.pdf with your file. Check method-specific limits in sendDocument or sendPhoto.
Commands and inline buttons
Register a small command menu:
curl --silent --show-error --fail-with-body \
-H 'Content-Type: application/json' \
-d '{"commands":[
{"command":"start","description":"Connect and get started"},
{"command":"help","description":"Show available commands"},
{"command":"status","description":"Check the latest build"}
]}' \
"${TELEGRAM_API}/setMyCommands"
Your backend still needs handlers for these commands. A displayed command menu does not grant authorization. Validate the requesting user and resource for every action. Group commands can include the bot username, such as /status@your_bot. See commands and scopes.
Add a button below a message:
curl --silent --show-error --fail-with-body \
--data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode 'text=Check your latest build:' \
--data-urlencode 'reply_markup={"inline_keyboard":[[{"text":"View status","callback_data":"build_status"}]]}' \
"${TELEGRAM_API}/sendMessage"
Handle the resulting callback_query update. Treat its data as an action identifier, then authorize callback_query.from.id against your application account. Inline buttons differ from reply-keyboard text buttons, which send a chat message. See inline keyboards.
Set TELEGRAM_CALLBACK_QUERY_ID from the received callback_query.id and acknowledge promptly with answerCallbackQuery:
curl --silent --show-error --fail-with-body \
--data-urlencode "callback_query_id=${TELEGRAM_CALLBACK_QUERY_ID}" \
--data-urlencode 'text=Checking your build.' \
"${TELEGRAM_API}/answerCallbackQuery"
For account linking, a URL such as https://t.me/your_bot?start=opaque_nonce supplies a /start payload. Generate a short-lived, single-use nonce bound to the signed-in application user. Confirm the link in your application before enabling account actions; never put API credentials in the link. See deep linking.
Receive updates with a webhook
Deploy an HTTPS endpoint with a valid certificate before registering it. Use port 443 for the example below. See Telegram's webhook deployment guide.
Stop your polling worker, set your application's URL, and generate a separate webhook secret:
TELEGRAM_WEBHOOK_URL='https://bot.example.com/webhooks/telegram'
TELEGRAM_WEBHOOK_SECRET="$(openssl rand -hex 32)"
Save that secret in the webhook receiver's secret store before registering the URL. Keep it distinct from the bot token.
curl --silent --show-error --fail-with-body \
--data-urlencode "url=${TELEGRAM_WEBHOOK_URL}" \
--data-urlencode "secret_token=${TELEGRAM_WEBHOOK_SECRET}" \
--data-urlencode 'allowed_updates=["message","callback_query"]' \
"${TELEGRAM_API}/setWebhook"
Telegram sends JSON updates by POST and includes the configured secret in X-Telegram-Bot-Api-Secret-Token. Non-2xx responses can trigger retries. See setWebhook.
Recommended receiver flow:
- Compare the secret header with your stored value; reject missing or incorrect values.
- Validate the JSON envelope and supported update type.
- Durably enqueue the update with a unique key of
(bot_id, update_id). - Return
200after the queue accepts it. Return200for an already-enqueued duplicate too. - Process the event in a worker, authorize any account action, and record its outcome.
If storage fails, return a failure status so the event can be retried. Deduplicate business actions as well as incoming updates: a worker can crash after completing an action but before marking the job done.
Inspect webhook health:
curl --silent --show-error --fail-with-body \
"${TELEGRAM_API}/getWebhookInfo"
Review pending_update_count and last_error_message. To switch back to polling, remove the webhook:
curl --silent --show-error --fail-with-body \
-X POST "${TELEGRAM_API}/deleteWebhook"
Omit drop_pending_updates to preserve the backlog. See getWebhookInfo and deleteWebhook.
Rate limits and error handling
Telegram's default guidance is roughly one message per second per chat, 20 messages per minute in a group, and 30 messages per second for bulk notifications. Queue outgoing work and respect 429 responses. See the broadcasting FAQ.
On flood-control errors, wait parameters.retry_after seconds before retrying. See ResponseParameters.
Recommended application behavior:
| Situation | Action |
|---|---|
| Invalid credentials | Stop the worker and check the configured token; avoid an endless retry loop. |
| Recipient or permission failure | Mark the destination unavailable and investigate membership or access. |
| Invalid payload | Correct the request before retrying. Preserve a sanitized error for debugging. |
| Rate limit | Delay queued work; avoid retrying every job simultaneously. |
| Network timeout during a send | Record an uncertain result. A blind resend can create a duplicate message. |
| Repeated incoming update | Reuse the stored processing result instead of repeating account actions. |
A useful local model separates received update, authorized action, and outgoing message records. Store their identifiers and outcomes so a retry does not accidentally repeat a purchase, booking, or notification.
Troubleshooting and verification
- No private-chat updates: send
/startto the correct bot, confirm its identity withgetMe, and check which update consumer is running. - Group messages missing: privacy mode filters which messages reach a bot. Test an explicit
/help@your_botcommand before changing group settings. See privacy mode. - Webhook backlog: check certificate validity, public reachability, response status, queue health, and the last webhook error. See the webhook guide.
- Unexpected account access: inspect your account-linking and authorization checks; a chat identifier alone should not authorize an application action.
Before enabling a bot for users, exercise these cases with a separate test bot:
- Start a private conversation, capture its chat ID, and send a reply.
- Receive a command and a button callback.
- Replay the same incoming update and confirm that its action runs once.
- Reject an incorrect webhook secret and retain work when the queue is unavailable.
- Restart the worker and verify that polling offsets or queued updates survive.
- Simulate a rate-limit response and an ambiguous send timeout.
Telegram recommends using a separate bot account for testing. See testing your bot.