Telegram API with Python: Bot API, MTProto and Linked Accounts

Python Implementation Guide

Die Telegram API Python guide: working code for every approach

A code-first walkthrough of the Python Telegram Bot API: the sendMessage call with Anfragen, a minimal bot with python-telegram-bot, a real linked account with Telethon, Pyrogram, or the Unipile SDK, and how to handle rate limits without your script crashing on the first 429. Whether you landed here looking for a telegram bot api python example or the full telegram api python picture, every approach below ships with working code.



telegram_bot.py
import Anfragen TOKEN = "123456:ABC-your-bot-token" URL = f"https://api.telegram.org/bot{TOKEN}/sendMessage" Nutzlast = { "chat_id": 123456789, "Text": "Hello from Python", "parse_mode": "MarkdownV2" } response = Anfragen.Beitrag(url, json=payload) print(Antwort.json())
200 OK: Nachricht gesendet
Entscheidungsleitfaden

Three ways to build the Telegram API in Python, and which one to pick

Once you have credentials, there are three concrete ways to talk to Telegram from a Python codebase. They are not interchangeable libraries for the same job: each one authenticates as a different kind of sender, with different code and different constraints.
Python Telegram Bot API
A bot token from BotFather, called from Python with Anfragen or a wrapper library like python-telegram-bot. The fastest way to ship, but a bot can only message a user who has written to it first.
Best for notifications and support bots
Telethon / Pyrogram (MTProto)
A Python client library that speaks the raw Telegram protocol with your own api_id und api_hash. Logs in as a real account, but you own session storage, reconnects and the 2FA flow.
Best for a fully custom Python client
Unipile Python SDKUnipile
A linked account, called from Python with a few SDK lines instead of a raw MTProto client. No session files to persist, no 2FA branch to write yourself.
Best for shipping fast without owning MTProto
This section is about the Python code once you have credentials. For the full arbitration between the Bot API and the Telegram Client API (limits, identity, what each one can and cannot do), see our dedicated comparison: Telegram Bot API vs Telegram API. For getting your bot token or api_id / api_hash in the first place, see the step-by-step access guide.


Build your Python integration
Code-Tutorial

The Python Telegram Bot API with requests

The most direct way to call the Telegram Bot API in Python is a plain HTTP call with Anfragen, no wrapper library involved. As of Bot API 10.2 (July 14, 2026), a bot token from BotFather and two parameters are all that sendMessage requires.
1
Get a bot token, then call sendMessage
BotFather issues a token shaped like 123456:ABC-your-bot-token. Every Bot API call, including sendMessage, is a POST zu https://api.telegram.org/bot<TOKEN>/sendMessage with a JSON body.



send_message.py
import Betriebssystem import Anfragen TOKEN = os.Umgebung["TELEGRAM_BOT_TOKEN"] URL = f"https://api.telegram.org/bot{TOKEN}/sendMessage" Nutzlast = { "chat_id": 123456789, "Text": "Your order #4821 has shipped.", "parse_mode": "MarkdownV2" } response = Anfragen.Beitrag(URL, json=payload, timeout=10)
2
Check the response, don't assume it worked
The Bot API always answers with a JSON body containing an ok boolean. A non-200 status code or ok: false means the message was not sent, and the payload includes a human-readable Beschreibung to log.



send_message.py
Daten = Antwort.json() wenn response.status_code == 200 und Daten.bekommen.("ok"): message_id = Daten["result"]["message_id"] print(f"sent, message_id={message_id}") sonst: print(f"failed: {data.get('description')}")
ParameterTypBeschreibung
chat_id Erforderlichint or strTarget chat identifier, or @username for a public channel.
text ErforderlichStrMessage text, 1 to 4096 characters after entity parsing.
parse_mode OptionalStrMarkdownV2 oder HTML, to render bold, links and code formatting in the text.
disable_notification OptionalboolSends the message silently, without a push notification sound.
reply_parameters OptionalWörterbuchSends the message as a reply to an existing message in the chat.


Build past the bot-only limit
Code-Tutorial

The Telegram Bot API in Python with python-telegram-bot

Raw Anfragen calls work fine for a single outbound message. Past that, most Python codebases wrap the Telegram Bot API in python-telegram-bot, a library that turns the same HTTP endpoints into an async Python object model with built-in update polling.
What the library adds over raw requests
Eine Anmeldung object that manages the update loop for you (polling or webhook)
Typed methods like bot.send_message() instead of hand-built JSON payloads
Command and message handlers, so replying to /start is a decorator, not a loop
The parameters are the same ones covered above: chat_id, text, parse_mode. The library still cannot make a bot message a user first, that restriction lives in Telegram's platform rules, not in the client you use to call it.



bot.py
from Telegramm import Aktualisieren from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes asynchron def Start(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.bot.Nachricht senden( chat_id=update.effective_chat.id, Text="Hello from python-telegram-bot", parse_mode="MarkdownV2" ) app = ApplicationBuilder().Token("123456:ABC-your-bot-token").bauen() app.add_handler(CommandHandler("Start", start)) App.run_polling()
Client API / MTProto

A real user account in Python: Telethon and Pyrogram

Sending as a real Telegram account from Python, not a bot, means going through the Client API with api_id und api_hash from my.telegram.org. Two Python libraries do the MTProto heavy lifting: Telethon and Pyrogram.
Python

Telethon

A pure-Python MTProto implementation built around async/await, with a client API that reads close to plain Python rather than raw protocol calls.
Python

Pyrogram

Another Python MTProto client, with its own take on session handling and a client surface designed to feel like a conventional SDK rather than a protocol library.



telethon_client.py
from telethon import TelegramClient from telethon.errors import SessionPasswordNeededError api_id = 1234567 api_hash = "your_api_hash_from_my.telegram.org" # "my_account" is the session file name on disk, reused on every run client = TelegramClient("my_account", api_id, api_hash) asynchron def Haupt(): await Klient.Start(phone="+15551234567") await Klient.Nachricht senden("username_or_id", "Hello from Telethon") mit Kunde client.loop.run_until_complete(main())
The 2FA wall every home-built login has to handle
1
Send the login code
client.start(phone=...) wraps auth.sendCode, which texts a login code to the phone number and returns a phone_code_hash used for the next call.
2
Validate the code
The library prompts for the code and calls auth.signIn with it. This is where a happy-path-only implementation stops.
3
Hit SESSION_PASSWORD_NEEDED
If the account has two-factor authentication enabled, Telegram answers with a 400 error: SESSION_PASSWORD_NEEDED. Telethon raises this as SessionPasswordNeededError, an expected branch, not a bug to catch and ignore.
4
Clear it with the cloud password
Passing the account's cloud password to client.start(password=...) runs the SRP exchange and auth.checkPassword for you. Calling the raw MTProto layer directly means building the InputCheckPasswordSRP object yourself.
Persist the session, or log in every run
Telethon and Pyrogram both write a local session file (or an in-memory StringSession) after the first successful login. Lose it, or deploy without persisting it, and your script has to run the phone-code and 2FA flow again on every restart.
Errors to expect on this path
SESSION_PASSWORD_NEEDED
PASSWORD_HASH_INVALID
API_ID_PUBLISHED_FLOOD
Only Telegram's own official apps get Firebase-based SMS code delivery. A Python script also needs its own api_id from my.telegram.org: reusing the example ID shipped in open-source sample code triggers API_ID_PUBLISHED_FLOOD for your end users, and only one api_id is issued per phone number.
The Unipile approach
For the full list of Telegram capabilities exposed by Unipile, see the Telegram API product page.

A real Telegram account in Python, without writing MTProto

The Unipile Python SDK connects an existing Telegram user account through Telegram's own Devices feature, either a QR code scan or Hosted Auth with providers: "TELEGRAM". There is no api_id, no session file to persist, and no SESSION_PASSWORD_NEEDED branch to write yourself: the linked account either shows as verbunden or it doesn't.
Once an account is linked, sending a message from Python is a handful of SDK calls, all running on Unipile's v2 API underneath. start_chat takes the linked account's ID and a user_ids list, and either opens a new conversation or delivers into the existing one if a chat already exists with that recipient.
Nein api_id / api_hash pair to request or rotate
No session file, no SRP handshake, no 2FA branch in your code
Same account status handling for group participant management
Installing the SDK is not covered here since the exact package name is best confirmed against the current docs, see developer.unipile.com/docs/getting-started for the install step and full Python reference.
Every capability shown here is listed endpoint by endpoint on the Unipile Telegram API product page, including what is supported and what is not.



send_telegram.py
import unipile configuration = einspurig.Configuration() configuration.api_key["apiKey"] = "apikey" api_client = einspurig.ApiClient(configuration) messaging_api = einspurig.MessagingApi(api_client) Chat = messaging_api.start_chat( "acc_123456789", {"user_ids": ["0123456789"], "Text": "Hi, following up on your request."} )
What the Unipile Telegram integration does not cover
Channels, communities and broadcasts
Group administration: approving or promoting members
Chat archiving
Sprach- und Videoanrufe
Build with the Python SDK
Errors and limits

Handling errors and rate limits in Python

A script that sends one message in a test chat and a script that runs in production hit different problems. The second one eventually gets a 429 or a FLOOD_WAIT_X, and what your Python code does next decides whether that is a five-second pause or a banned account.
1/sec
Maximum Bot API messages to the same individual chat
20/min
Maximum Bot API messages inside a single group
~30/sec
Approximate Bot API ceiling when broadcasting across chats
429
Status returned once any of these limits is crossed
Retry loops for both sides of the API
The Bot API and the Client API signal the same problem with two different shapes. Both need to be caught explicitly, not logged and retried blindly.



bot_api_retry.py
import Zeit import Anfragen def mit_wiederholung_senden(url, payload, max_retries=3): für Versuch in Reichweite(max_wiederholungen): r = Anfragen.Beitrag(url, json=payload) wenn r.status_code != 429: return r retry_after = r.json().bekommen.("parameters", {}).bekommen.("retry_after", 1) Zeit.Schlaf(retry_after) erhöhen RuntimeError("too many 429 responses")



telethon_flood_wait.py
from telethon.errors import FloodWaitError import asyncio asynchron def send_safely(client, entity, text): versuchen: await Klient.Nachricht senden(entity, text) außer FloodWaitError als e: # e.seconds is the FLOOD_WAIT_X value Telegram sent back await asyncio.Schlaf(e.seconds) await Klient.Nachricht senden(entity, text)
Pacing guidance that keeps you under the limits in the first place
Avoid sending heavy volume from brand-new accounts, they get flagged faster than established ones.
Ramp up sending volume progressively instead of starting a script at full throughput.
Keep at least 10 to 20 seconds between messages sent from the same account, this is Unipile's own recommendation for linked accounts, not just a Bot API ceiling.
Recap

Python Telegram Bot API vs Telethon/Pyrogram vs Unipile SDK

The same recap in table form: what each Python path actually requires, and where it stops.
DimensionBot API (requests / python-telegram-bot)Telethon / Pyrogram (MTProto)Unipile Python SDK
Can message a user firstNeinYes, privacy-dependentJa
Setup requirementBot token from BotFatherapi_id / api_hash from my.telegram.orgLinked account via QR code or Hosted Auth
Verwaltung der SitzungenToken-based, nothing to persistYou persist the session file yourselfManaged by Telegram's own Devices feature
2FA / SESSION_PASSWORD_NEEDEDNicht anwendbarYou handle the SRP exchangeFür Sie erledigt
Group participants (get / add / remove)Limited to bot permissionsYes, self-builtYes, dedicated v2 endpoints
Channels, communities, broadcastsYes, if added as adminJaNicht unterstützt
Am besten fürNotifications and support botsA fully custom Python MTProto clientShipping fast without owning MTProto
Can message a user first
Bot APINein
Telethon / PyrogramYes, privacy-dependent
Unipile SDKJa
Setup requirement
Bot APIBot token
Telethon / Pyrogramapi_id / api_hash
Unipile SDKLinked account
Verwaltung der Sitzungen
Bot APINothing to persist
Telethon / PyrogramSelf-persisted session
Unipile SDKManaged via Devices
2FA / SESSION_PASSWORD_NEEDED
Bot APINicht anwendbar
Telethon / PyrogramSelf-built SRP
Unipile SDKFür Sie erledigt
Group participants (get / add / remove)
Bot APILimited to bot permissions
Telethon / PyrogramSelf-built
Unipile SDKDedicated v2 endpoints
Channels, communities, broadcasts
Bot APIYes, as admin
Telethon / PyrogramJa
Unipile SDKNicht unterstützt
Am besten für
Bot APINotifications, support bots
Telethon / PyrogramFully custom client
Unipile SDKShipping fast, no MTProto

Telegram API in Python - FAQ

Common questions about the Python Telegram Bot API, python-telegram-bot, Telethon, Pyrogram, and connecting a real account with Unipile.

Ja. Die Telegram Bot API is a plain HTTP interface, so a single POST request with Python's Anfragen library to https://api.telegram.org/bot<TOKEN>/sendMessage, with a chat_id und text in the JSON body, is enough. No SDK or wrapper library is required for this call.

Die Telegram Bot API is Telegram's own HTTP interface, callable from Python with Anfragen or any HTTP client. python-telegram-bot is a third-party Python library that wraps those same HTTP endpoints in an async object model, with an Anmeldung class, typed methods like bot.send_message, and built-in update polling or webhook handling.

This is a structural rule of the Bot API, not a bug in your code. A bot cannot call sendMessage against a chat_id until that user has sent at least one message to the bot first. No parameter or Python library works around it. A real linked Telegram account, through Telethon, Pyrogram, or the Unipile SDK, does not have this restriction.

No. The Bot API only needs a bot token issued by BotFather. api_id und api_hash from my.telegram.org are required for the Client API (MTProto), the protocol used by Telethon, Pyrogram, and any client that logs in as a real user account instead of a bot.

SESSION_PASSWORD_NEEDED is a 400 error Telegram returns from auth.signIn when the account has two-factor authentication enabled. Telethon raises it as SessionPasswordNeededError. Clearing it means running the SRP protocol and calling auth.checkPassword with the account's cloud password, which Telethon and Pyrogram both handle when you pass the password to their login method.

The Bot API returns a 429 status once you exceed roughly one message per second to the same chat, 20 messages per minute in a group, or about 30 messages per second when broadcasting across chats. The response includes a retry_after value in seconds. On the MTProto side, the equivalent is a 420 FLOOD error or a FLOOD_WAIT_X exception, where X is the number of seconds to wait before retrying.

Ja. Die Unipile Python SDK connects an existing Telegram user account through Telegram's own Devices feature, either a QR code scan or Hosted Auth, and exposes messaging through a few SDK calls such as start_chat. There is no api_id to request, no MTProto implementation, and no session file or 2FA branch to write yourself.

Group participant management is supported: listing, adding, and removing participants through dedicated v2 endpoints. Channels, communities, broadcasts, group administration actions like approving or promoting members, chat archiving, and voice or video calls are not supported.

Haben Sie noch Fragen? Unser Team ist für Sie da.

Sprechen Sie mit einem Experten
Telegram API Python, done right

Build your telegram bot api python integration with Unipile

Skip the MTProto session files, skip the bot-only limitation. Connect an existing Telegram account through Unipile's Python SDK and unify it with WhatsApp, LinkedIn, Instagram, Gmail, Outlook and IMAP in one API.
de_DEDE