Telegram· 6 min read

Telegram bot in Python: getMe, getUpdates and sendMessage


A first Telegram bot in Python needs three Bot API methods and nothing outside the standard library. getMe confirms the token works, getUpdates long-polls for new messages, and sendMessage replies. Every call is an HTTPS request to https://api.telegram.org/bot<token>/METHOD_NAME, over GET or POST, with application/json accepted for anything that isn’t a file upload (Bot API reference, accessed 2026-11-04). This post follows Bot API 10.3, released August 24, 2026. Telegram publishes no request samples for these methods, so every code block below is assembled from the reference’s parameter tables.

Get a token and test it with getMe

You set up the bot account with @BotFather inside Telegram, then connect it to your own backend through the Bot API (Bots FAQ, accessed 2026-11-04). BotFather gives you the token that goes into the URL. The token is the only credential in each request, so anyone who has it can call any method as your bot. Keep it in an environment variable, out of your source and your logs.

getMe is “a simple method for testing your bot’s authentication token” (getMe). It requires no parameters and returns the bot as a BotFullInfo object (a User object before Bot API 10.5, 22 November 2026). Call it once at startup. An ok: false here points to a bad token, and every later call will fail the same way.

Every response follows the same shape. The JSON object “always has a Boolean field ‘ok’”. When ok is true, the data sits in result. When it’s false, description explains the error in readable text (Making requests). Telegram also returns an integer error_code, but says its “contents are subject to change in the future”. Branch on ok, log description, and don’t build logic on specific code values. Some errors add a parameters object with extra detail.

Long-poll getUpdates with offset

Telegram offers “two mutually exclusive ways of receiving updates”: getUpdates and webhooks. Either way, updates wait on Telegram’s servers until your bot fetches them, “but they will not be kept longer than 24 hours” (Getting updates). A bot that stays offline for longer loses messages.

Parameter What it does (getUpdates)
offset First update to return; set it one above the highest update_id you’ve received
limit 1 to 100 updates per call, default 100
timeout Seconds to hold the connection open; the default 0 is short polling, meant for testing only
allowed_updates Update types to receive; if you omit it, the previous setting stays

The offset is how you confirm updates. getUpdates returns the earliest 100 unconfirmed updates. Pass offset as the last processed update_id plus one. The FAQ says every update with an update_id up to that offset “will be marked as confirmed on the server” (Bots FAQ). Skip that step and the same messages come back on every call. The reference adds that you should “recalculate offset after each server response” to avoid duplicates.

Set timeout to a positive number such as 30. The call then waits up to that many seconds for an update instead of returning at once, so your loop doesn’t hammer the API. Make your HTTP client’s own timeout longer than that value, or the client gives up before Telegram answers.

An empty allowed_updates list gives you every type except chat_member, message_reaction and message_reaction_count. The setting also sticks between calls. Pass ["message"] explicitly so a value left behind by an earlier script doesn’t surprise you.

Reply with sendMessage and HTML formatting

sendMessage sends text and returns the sent Message on success (sendMessage).

Parameter Required Notes
chat_id Yes Integer chat id, or @username of a supergroup or channel
text Yes 1 to 4096 characters after entities parsing
parse_mode No HTML, MarkdownV2, or the legacy Markdown
reply_parameters No The message you’re replying to
reply_markup No Inline keyboard, reply keyboard, keyboard removal or force reply

Pick HTML for text that includes user input. MarkdownV2 requires a backslash before 18 characters outside entities, including ., -, ! and (, so ordinary sentences break it (Formatting options). In HTML mode, any <, > or & that isn’t part of a tag “must be replaced with the corresponding HTML entities”. Python’s html.escape() does that. It also turns quotes into &quot; and &#x27;. Telegram accepts &quot; by name and states that “all numerical HTML entities are supported”, so both pass. Using html.escape() here is our recommendation, not Telegram’s.

The supported tags include <b>, <i>, <u>, <s>, <code>, <pre>, <a href> and <blockquote>, and the reference states that “only the tags mentioned above are currently supported”. If you build HTML yourself, stick to that list and escape everything else.

The complete bot

Save this as bot.py. It runs on Python 3.9 or later with no packages to install.

import html
import json
import os
import time
import urllib.error
import urllib.request

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


class TelegramError(Exception):
    pass


def call(method, params=None, timeout=10):
    request = urllib.request.Request(
        API + method,
        data=json.dumps(params or {}).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            body = json.loads(response.read())
    except urllib.error.HTTPError as err:
        # urllib raises on non-2xx statuses; the body still holds ok and description.
        try:
            body = json.loads(err.read())
        except ValueError:
            raise TelegramError(f"{method}: HTTP {err.code}") from err
    if not body.get("ok"):
        raise TelegramError(f"{method}: {body.get('description')}")
    return body["result"]


def handle(message):
    text = message.get("text")
    if text is None:
        return  # photos, stickers and other non-text messages
    reply = "You said: <b>" + html.escape(text[:4000]) + "</b>"
    call("sendMessage", {
        "chat_id": message["chat"]["id"],
        "text": reply,
        "parse_mode": "HTML",
    })


def main():
    me = call("getMe")
    print(f"Running as @{me.get('username')} (id {me['id']})")

    if call("getWebhookInfo")["url"]:
        raise SystemExit("A webhook is set. Call deleteWebhook before polling.")

    offset = None
    while True:
        params = {"timeout": 30, "allowed_updates": ["message"]}
        if offset is not None:
            params["offset"] = offset
        try:
            updates = call("getUpdates", params, timeout=40)
        except (TelegramError, OSError) as err:
            print("getUpdates failed:", err)
            time.sleep(5)
            continue
        for update in updates:
            offset = update["update_id"] + 1
            if "message" in update:
                try:
                    handle(update["message"])
                except (TelegramError, OSError) as err:
                    print("update", update["update_id"], "failed:", err)


if __name__ == "__main__":
    main()

Run it with TELEGRAM_BOT_TOKEN=YOUR_TOKEN python3 bot.py and send the bot a message from your Telegram account. It echoes the text back in bold. The slice to 4,000 characters keeps the reply under the 4,096 limit once the prefix is added.

The loop catches errors per update. One failed sendMessage gets logged and the loop moves on, while offset still advances, so a message the bot can’t answer won’t come back forever. Network failures surface as OSError subclasses and trigger a five-second pause before the next poll.

When getUpdates fails because a webhook is set

getUpdates “will not work if an outgoing webhook is set up” (getUpdates). This happens when the same token was used earlier with a webhook, from an automation tool or another server. Workflows built with n8n’s Telegram Trigger or Make’s Telegram scenario may have registered one. Telegram’s own pages don’t document the exact error code or text, so the script checks state before polling. getWebhookInfo returns “an object with the url field empty” when the bot is on getUpdates (getWebhookInfo).

If url is set, remove the webhook:

curl -X POST "https://api.telegram.org/botYOUR_TOKEN/deleteWebhook"

deleteWebhook takes one optional parameter, drop_pending_updates. Pass it as true only when the queue holds test junk you want gone (deleteWebhook). Remember which tool set the webhook. Once you delete it, that tool stops receiving updates.

Sending limits for a first bot

The FAQ gives three rough ceilings. In one chat, avoid more than one message per second. In a group, a bot can send at most 20 messages per minute. Across all chats, the limit is about 30 messages per second, and going past it returns 429 errors (Bots FAQ). An echo bot won’t come close. A bot that sends notifications to many users will, and the Telegram rate-limits guide covers how to pace it.

Next: buttons and webhooks

Pass reply_markup to attach buttons. Inline keyboards and callback queries shows the payloads and how to answer a tap. To show your commands in the client’s menu, use setMyCommands.

Long polling suits development and small bots that run on one machine. For production, setWebhook makes Telegram send each update to your HTTPS URL. Its secret_token parameter, 1 to 256 characters, comes back in the X-Telegram-Bot-Api-Secret-Token header on every request (setWebhook). Telegram webhooks with a secret token walks through the handler that checks it.

Z-API Omni team