Telegram Send Message API in Python: Text, Media, Inbox or History
| You need | Call | Why not the others |
|---|---|---|
| A sentence to a username, phone, or Saved Messages | send-message | No file field; inbox and history do not send |
| An image, video, voice note, or document | send-media | Base64 data plus type; the text POST cannot carry bytes |
| Messages that arrived while this session was connected | list-inbox | Rolling 500, newest first, no outbound, cleared on restart |
| Older messages for one peer, live from Telegram | chat-history | Needs a peer; not the live feed |
| Confirm the peer resolves | check-exists | A miss still spends a send; this is not the session-free number checker |
Those five rows on Telegram Messaging share one connected user session and one authorized platform key. They are not extras on a single POST. Match the job — send a sentence, attach a file, watch inbound, or fetch a thread — then write to and text.
Sign in and copy a key from the dashboard. Python reads OPENDATA_API_KEY; curl uses YOUR_API_KEY. The key and sessionId ride the query string, so those URLs do not belong in tickets, screenshots, or browser apps. Opening this page or copying a snippet does not send a message. Running a command does, and it spends credits. Use only accounts you own or are authorized to operate.
Pick the chat action before the payload
Every operation lives at https://api.opendata-api.com/api/project/telegram-messaging/<operation>. GET and DELETE put remaining fields on the query string. POST and PUT send the operation JSON as a string inside body. There is no bot token on this project: the sender is a logged-in user account, identified by sessionId.
This article is not the Telegram session login OTP runbook. That guide creates, polls, restores, and disconnects a session. Here the session is already CONNECTED. If get-session is anything else, stop composing text and go there. It is also not a WhatsApp send pipeline: different project, different device link, different peer rules. If you only need “does this number or username exist?” and will not send, the session-free Telegram number checker is the cheaper tool — it does not take this sessionId.
HTTP status and business status are two layers. A missing or unauthorized key, a validation error, or a transport failure shows up as HTTP 4xx/5xx or as a gateway code other than 200 — there is no Telegram send verdict in that envelope. Platform 401 is a bad key; 403 is insufficient credits or an inactive account. The messaging service often still answers HTTP 200 and puts a refusal in its own code, title, and detail. Unwrap both envelopes before you retry anything.
import json
import os
import requests
API_KEY = os.environ["OPENDATA_API_KEY"].strip()
SESSION_ID = os.environ["TELEGRAM_SESSION_ID"].strip()
BASE = "https://api.opendata-api.com/api/project/telegram-messaging"
OK = {200, 201, 202, 204}
def call(method, operation, payload=None, **params):
"""Return the innermost payload. POST JSON goes in a string `body` field."""
params["key"] = API_KEY
kwargs = {"params": params, "timeout": 60}
if payload is not None:
kwargs["json"] = {"body": json.dumps(payload)}
resp = requests.request(method, f"{BASE}/{operation}", **kwargs)
if not resp.ok:
raise RuntimeError(f"{operation} failed: HTTP {resp.status_code}")
body = resp.json()
# Peel {"code": 200, "data": {"code": 201, "data": ...}}; inner 200 is not enough
while isinstance(body, dict) and "code" in body:
if body["code"] not in OK:
raise RuntimeError(f"{operation} failed: inspect redacted diagnostics")
body = body.get("data")
return body
get-account is a cheap identity read — numeric id, phone, username, name, bot flag — not a send. Call it when you need to confirm which account the session is speaking as.
Text is the first send that should work
Prove the envelope with Saved Messages. to set to me posts into the account's own notes; nobody else receives anything. Documented shapes below are not guaranteed live peers.
# Documented shape only — running it spends credits and requires a CONNECTED session.
curl -X POST 'https://api.opendata-api.com/api/project/telegram-messaging/send-message?key=YOUR_API_KEY&sessionId=YOUR_SESSION_ID' \
-H 'Content-Type: application/json' \
-d '{"body":"{\"to\":\"me\",\"text\":\"Hello from the API\"}"}'
to accepts @username or a bare username, a +phone in full international format, or me. A bare numeric user ID is not supported unless the account already knows that peer. A successful inner payload confirms to, text, and sent. Treat that as a confirmation of this call, not a promise that a later retry is safe.
call(
"POST",
"send-message",
{"to": "@some_username", "text": "Your order has shipped."},
sessionId=SESSION_ID,
)
call(
"POST",
"send-message",
{"to": "+15551234567", "text": "Hi, this is Anna from support."},
sessionId=SESSION_ID,
)
Unknown handles waste a send. check-exists resolves a peer and returns exists plus id, username, and display name on a hit, or exists=false with a reason on a miss. Cache the answer per recipient. requests encodes the leading plus; if you paste a raw URL, write it as %2B or it is read as a space.
info = call("GET", "check-exists", sessionId=SESSION_ID, peer="+15551234567")
if not info.get("exists"):
raise RuntimeError("peer did not resolve; skip send")
If a send raises, read get-session before you POST again. Offline-with-saved-login can reconnect on that GET. A missing login is a create/restore problem, not a payload typo.
Media, history, and the inbox are different doors
send-media is not send-message with a file attached. type is image, video, audio, voice, or document. data is the file as base64. Optional caption, fileName, and mimeType override the inferred name and type. Large files make large bodies: use a stable link and a generous timeout. The same to forms apply.
import base64
with open("invoice.pdf", "rb") as fh:
encoded = base64.b64encode(fh.read()).decode("ascii")
call(
"POST",
"send-media",
{
"to": "@some_username",
"type": "document",
"data": encoded,
"fileName": "invoice.pdf",
"caption": "Invoice for October",
},
sessionId=SESSION_ID,
)
Inbound is not history. list-inbox returns messages received in real time while this session was connected, newest first, excluding the account's own outbound. Each item has id, chatJid, sender, type, text, and timestamp. Default limit is 50. The window holds the most recent 500 messages per session and is wiped when the service restarts. Poll, dedupe on id, and write what you need to your own store. chatJid values such as user:<id>, chat:<id>, or channel:<id> are valid peers for history, mark-read, and group calls.
chat-history fetches recent messages for one peer directly from Telegram — including traffic from before this process started — newest first. Default limit is 20. peer can be @username, +phone, me, or a typed id taken from the inbox or list-chats. list-chats itself is built from messages observed since the session connected; it is not a complete dialog archive.
inbox = call("GET", "list-inbox", sessionId=SESSION_ID, limit=50) or []
history = call(
"GET",
"chat-history",
sessionId=SESSION_ID,
peer="@some_username",
limit=50,
)
Edit, react, and revoke need a numeric messageId from one of those two reads. Only the account's own messages can be edited. revoke-message deletes for everyone. An empty-string emoji on react-message clears your reaction. Those are follow-on writes, not a fifth send door.
What a send client still must not do
Do not open this catalog to mint a bot token, and do not paste a Bot API payload into body. The sender is a user session. Do not start a second login for the same account because a send failed — read get-session first.
Do not retry send-message or send-media on a timeout. There is no idempotency key. After a network cut, read chat-history for that peer and look for your text (or fromMe) before you POST the same payload again.
Do not treat list-inbox as storage, and do not page it as if it were chat-history. Five hundred messages, this session, gone on restart. Do not feed a phone into chat-history when you meant the live inbox, and do not call send-media because the text endpoint “might accept a path.”
Do not spray identical copy to many peers, and do not message people who did not expect to hear from you. Unsolicited bulk traffic violates Telegram's terms and can limit the account; local privacy rules still apply. Phone numbers are personal data. Keep sessionId in the environment or a secret store — it authorizes everything the account can do. disconnect-session drops the live link and keeps the stored login by default; logout=true also signs out remotely.
Group and channel admin calls exist on the same session. They are not substitutes for the four rows in the table. If the session is not CONNECTED, this chooser has nothing to pick; go back to the login runbook.