Programming

Telegram Bot API Example: Building Your First Bot

A direct guide to implementing a basic Telegram bot using Python and the official Bot API.

By · · 5 min read

Short answer

To build a Telegram bot, first create it via @BotFather to receive an API token. Use the requests library in Python to interact with the API via getUpdates or set a webhook with setWebhook. The fundamental interaction involves sending POST requests to the Telegram server with your token and required parameters.

Key takeaways

  • Always store your BotFather API token in environment variables, never hardcode it.
  • Polling (getUpdates) is suitable for development, but Webhooks are necessary for production scale.
  • The Telegram API uses standard HTTPS POST requests with JSON payloads.
  • Handle the chat_id and text fields carefully to ensure responses reach the correct user.

Getting Started with BotFather

Every Telegram bot begins its life with @BotFather. This is the official bot used to manage all other bots on the platform. Think of it as the control panel for your bot's metadata and authentication credentials.

To start, open Telegram and search for the @BotFather username. Initiate a chat and send the /newbot command. The bot will guide you through a short registration process where you specify a display name and a unique username that must end in 'bot'. Once the bot is registered, it generates an API token.

The token looks like a long string of characters separated by a colon. Treat this token as a password; anyone who possesses it has full control over your bot. Never share it, and avoid committing it to version control systems like GitHub or GitLab. If your token is ever exposed, you must immediately revoke it via BotFather to prevent unauthorized use.

Once you have your token, you can use BotFather to edit the bot description, change the profile picture, or enable 'Privacy Mode'. Privacy mode is a specific setting that determines whether your bot can see all messages in a group chat or only those messages that directly mention it. Understanding these settings is necessary before you begin writing your application code.

How to Send a Message Using the API

The Telegram Bot API is a JSON-based interface over HTTPS. To interact with it, you make POST requests to specific endpoints. The base URL structure for every request follows the format: https://api.telegram.org/bot<token>/METHOD_NAME.

The most common method is sendMessage. You must provide at least a chat_id and the text content. When you send these fields as a JSON payload, the Telegram server processes your request and returns a JSON object confirming the status of the operation.

To make these calls from Python, the requests library is the standard tool. It handles the low-level HTTP details, allowing you to focus on the application logic. Below is a simple Python implementation using the requests library.

When constructing your payload, you can add extra parameters like parse_mode to support Markdown or HTML formatting. For example, setting parse_mode to 'Markdown' allows you to send bold or italic text by wrapping your strings in specific characters. This flexibility is essential for creating clean, readable bot messages that guide users through your workflow.

import requests
import os

TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
BASE_URL = f'https://api.telegram.org/bot{TOKEN}'

def send_message(chat_id, text):
    url = f'{BASE_URL}/sendMessage'
    payload = {'chat_id': chat_id, 'text': text}
    response = requests.post(url, json=payload)
    return response.json()

# Example usage
# send_message('123456789', 'Hello from my Python bot!')

Polling vs Webhooks

You have two ways to receive updates from Telegram: long polling and webhooks. Choosing between these methods depends on your infrastructure and your bot's traffic requirements.

Long polling involves your script repeatedly asking Telegram for new messages. When you use the getUpdates method, your script opens a connection and waits for the Telegram server to return any pending messages. If no messages exist, the server waits until the timeout period expires before closing the connection. This approach is easy to set up for local development.

Webhooks push messages to your server instantly. You tell Telegram your URL using setWebhook, and they call your endpoint whenever a user interacts with your bot. This model is much more efficient for production because your server only executes code when an actual event happens, rather than constantly checking for updates.

When using webhooks, you need a public HTTPS URL. You can use services like Nginx to serve as a reverse proxy, forwarding requests to your local Python process. This ensures that your webhook receiver is secure and accessible to Telegram’s servers at all times.

MethodBest ForSetup DifficultyPerformance
Long PollingDevelopment / Low usageLowModerate
WebhooksProduction / High usageMediumHigh

Common Gotchas and Debugging

One common mistake is failing to handle the API response structure. If a request fails, Telegram returns a JSON object with ok: false and an error description. You should verify the ok field in your code before proceeding with any post-message logic.

If you are using a VPS for your production bot, ensure your firewall allows HTTPS traffic on the port your server listens on. Webhook updates originate from Telegram's servers. If you use a port other than 80 or 443, your webhook might fail to receive data. Always check your server logs for incoming requests from the official Telegram IP ranges.

If you notice your bot is not responding, check if the chat_id is an integer or string. Telegram expects IDs to be passed as integers, though sometimes strings are accepted by middleware. Additionally, ensure the user has actually started your bot. A bot cannot initiate a conversation with a user; the user must first send a message to the bot to create a valid chat context.

Another point of failure is character encoding. If you are sending complex strings or user-generated input, ensure your application handles UTF-8 correctly. The Telegram API expects valid UTF-8 strings, and improper encoding can lead to unexpected 400 'Bad Request' errors.

Is the Telegram Bot API Free?

Yes, the Telegram Bot API is free for all developers. There are no fees to create a bot or send messages to your users. Telegram provides this infrastructure as part of its core offering to encourage the ecosystem of third-party tools.

However, Telegram enforces rate limits to maintain stability. If you send too many messages too quickly to a single user or across the whole platform, your bot will receive a 429 'Too Many Requests' error. The API limits dictate that you should not exceed 30 messages per second to different users, and you should limit messages to the same user to one per second.

Use backoff strategies in your code to handle these errors gracefully if you are sending bulk notifications. A simple exponential backoff—where you wait for an increasing amount of time after each 429 response—is often enough to stay within the platform's requirements. These limits exist to prevent spam and ensure the platform remains responsive for all users.

Frequently asked questions

How do I find my chat_id?

The easiest way to find your chat_id is to message a bot like @userinfobot. It will reply with your numerical ID, which you can use for testing your bot's sendMessage function.

Why is my webhook not receiving data?

Check if your endpoint is publicly accessible and using HTTPS. Telegram requires a valid SSL certificate for webhooks; self-signed certificates are only allowed if you upload the public key file to Telegram.

Can I hide my bot token?

You should use environment variables (.env files) to manage your token. Never commit your token to version control systems like GitHub to prevent unauthorized access.

Sources & further reading

About the author

Tushar Gautam is a full-stack & ai product engineer in India. He builds AI SaaS products such as an AI video ad generator, a RAG chatbot platform and a Razorpay-powered report service, mostly with Next.js, Flask and the Gemini API. See the projects, GitHub or LinkedIn.

This article was drafted with the help of AI (Google Gemini) from official documentation and published by Tushar Gautam. Spotted an error? Let me know.