Telegram Session Login API: OTP, 2FA, QR and Restore
The ticket said verify-otp failed. It had not. POST https://api.opendata-api.com/api/project/telegram-messaging/verify-otp returned HTTP 200, the gateway envelope was code: 200, and the messaging layer accepted the body. get-session still read WAITING_FOR_OTP. The digits the operator typed came from an SMS. The next send-message then failed because the session was never CONNECTED. That is the failed request this Telegram session login runbook is about: OTP, 2FA and QR are wait-states you poll, not a "get an API key" happy path.
Opening this page or copying a snippet does not start a login. A request you actually run does, and it spends credits. Sign in, copy a key from the dashboard, and read it from OPENDATA_API_KEY on the server (curl uses YOUR_API_KEY). The key rides in the query string, so those URLs do not belong in tickets. Collect the in-app login code, the cloud password and the sessionId only from accounts you own or are authorized to operate. Do not write them to logs.
The session is stuck on waiting_code
Before you submit another code, read the session. waiting_code in an on-call channel maps to status: WAITING_FOR_OTP on get-session. The other values you will see are CREATED, WAITING_FOR_SCAN, CONNECTING, CONNECTED, DISCONNECTED, LOGGED_OUT and FAILED.
HTTP status and business status are not the same layer. 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 login verdict in that envelope. The messaging service often still answers HTTP 200 and puts a failure in its own code, title and detail. Unwrap both envelopes before you decide anything. A 200 on verify-otp or submit-password only means the submit was accepted. Code and password are processed asynchronously; the verdict is the next status, or the twoFactorRequired flag.
Diagnose with a read, not another write:
curl --get 'https://api.opendata-api.com/api/project/telegram-messaging/get-session' \
--data-urlencode 'key=YOUR_API_KEY' \
--data-urlencode 'sessionId=YOUR_SESSION_ID'
Branch on what you see:
- Not
WAITING_FOR_OTP—verify-otpwill not finish the login. Wait, or you are in the wrong mode. twoFactorRequiredis true — the OTP already landed. The account is waiting for the cloud password. Submitting the code again does not help.FAILEDorLOGGED_OUT— stop polling for a code. Create a new session, or restore a saved login.DISCONNECTEDwith a stored login —get-sessionmay reconnect the account. Do not treat that as a fresh OTP flow.- No SMS at all — the login code is delivered inside the Telegram app of that account. Open Telegram on a device where the account is already signed in.
Do not create a second session for the same number while the first is still WAITING_FOR_OTP. You now have two wait-states and one code.
Create the phone session
Phone login starts with create-session. The JSON payload is sent as a string inside body. phoneNumber is the full international number with a leading +. deviceName is a label you will recognize later on the account's device list.
curl -X POST 'https://api.opendata-api.com/api/project/telegram-messaging/create-session?key=YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{"body":"{\"mode\":\"phone\",\"phoneNumber\":\"+15551234567\",\"deviceName\":\"My Bot\"}"}'
The new identifier is the innermost id (data.data.id in the raw JSON). Keep it. Every later call uses it as the sessionId query parameter. +15551234567 is a documented example shape, not a guaranteed live account.
Poll until WAITING_FOR_OTP before you ask anyone for a code. A helper that peels both envelopes and treats 200, 201, 202 and 204 as success is enough for production:
import json
import os
import time
import requests
API_KEY = os.environ["OPENDATA_API_KEY"].strip()
BASE = "https://api.opendata-api.com/api/project/telegram-messaging"
OK = {200, 201, 202, 204}
def call(method, operation, payload=None, **params):
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} HTTP {resp.status_code} {resp.text}")
body = resp.json()
while isinstance(body, dict) and "code" in body:
if body["code"] not in OK:
raise RuntimeError(f"{operation} failed: {body}")
body = body.get("data")
return body
def wait_for(session_id, wanted, timeout=120, stop_on_2fa=False):
deadline = time.time() + timeout
while time.time() < deadline:
state = call("GET", "get-session", sessionId=session_id)
status = state.get("status")
if status in wanted or (stop_on_2fa and state.get("twoFactorRequired")):
return state
if status in ("FAILED", "LOGGED_OUT"):
raise RuntimeError(f"login ended with status {status}")
time.sleep(2)
raise TimeoutError("session did not reach the expected status")
get-session also returns the login mode and phone number. While a login is pending it may include qrImage or twoFactorRequired. Raise on FAILED / LOGGED_OUT; do not keep sleeping until the HTTP timeout.
Submit the OTP, then 2FA if asked
verify-otp is only valid while status is WAITING_FOR_OTP. Send the in-app code. Do not treat the immediate response as connected, and do not store the code.
Then poll again. You want CONNECTED, or twoFactorRequired=true with status still WAITING_FOR_OTP. That flag is expected when the account has a cloud password — it is not a transport error.
submit-password is only valid while twoFactorRequired is true: after OTP in phone mode, or after the scan in QR mode. Same async rule: accept, then poll until CONNECTED.
import getpass
session = call("POST", "create-session",
{"mode": "phone", "phoneNumber": "+15551234567", "deviceName": "My Bot"})
session_id = (session or {}).get("id")
if not session_id:
raise RuntimeError(f"no session id: {session}")
wait_for(session_id, {"WAITING_FOR_OTP"})
code = input("Login code from the Telegram app: ").strip()
call("POST", "verify-otp", {"code": code}, sessionId=session_id)
state = wait_for(session_id, {"CONNECTED"}, stop_on_2fa=True)
if state.get("status") != "CONNECTED":
password = getpass.getpass("Telegram cloud password: ")
call("POST", "submit-password", {"password": password}, sessionId=session_id)
state = wait_for(session_id, {"CONNECTED"}, timeout=60)
print("status:", state.get("status"))
print("store this id for restore:", state.get("id", session_id))
In a product, collect the code and password on your own HTTPS UI, forward each once, and drop them. After CONNECTED, get-account confirms which account the session is. Persist the id that get-session reports at that point — after connect it becomes a stable account-derived value, and both the original and the stable id keep working.
QR, restore, and logout without orphaning the session
QR mode skips the phone code. Create with mode qr and a deviceName. The create response includes qrPageUrl. For your own UI, poll get-session and render qrImage (a base64 data-URI). Status while waiting is WAITING_FOR_SCAN. The owner opens Telegram, then Settings, Devices, Link Desktop Device, and scans. If the account has a cloud password, finish with submit-password the same way as phone mode.
curl -X POST 'https://api.opendata-api.com/api/project/telegram-messaging/create-session?key=YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{"body":"{\"mode\":\"qr\",\"deviceName\":\"My Bot\"}"}'
You do not repeat OTP after a process restart. create-session in restore mode takes the previous id in the JSON field sessionId and reconnects the stored login with no new code. Inbox and chat-list caches still clear on restart even when restore succeeds.
curl -X POST 'https://api.opendata-api.com/api/project/telegram-messaging/create-session?key=YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{"body":"{\"mode\":\"restore\",\"sessionId\":\"PREVIOUS_SESSION_ID\"}"}'
disconnect-session is DELETE. Default (logout=false) drops the live connection and keeps the stored login, so restore still works. logout=true also logs out of Telegram remotely and deletes the stored login — the next time needs a new code or QR. Orphaning is leaving a CONNECTED session with no stored id, or calling logout when you meant disconnect.
curl -X DELETE 'https://api.opendata-api.com/api/project/telegram-messaging/disconnect-session?key=YOUR_API_KEY&sessionId=YOUR_SESSION_ID&logout=false'
Once CONNECTED, send and read from sending Telegram messages in Python. If you only need existence of a handle or number, use the session-free Telegram number checker. Operation pages: create-session, verify-otp, submit-password, get-session, disconnect-session. Product: Telegram Messaging. Costs: pricing.
Mistakes that keep you waiting: submitting an SMS; calling verify-otp from CREATED or CONNECTING; treating the async 200 as CONNECTED; ignoring twoFactorRequired; logging the code, the cloud password or the sessionId; pasting query-string keys into tickets; logout=true on a session you still need to restore; spinning a second phone session for the same number. Operate only authorized accounts and follow Telegram's Terms of Service.