Skip to main content
Socialift
Platform

Telegram API integration

Socialift fully supports both kinds of Telegram connection: a user account over MTProto (built on Telethon) and a bot over the Bot API. The account acts as the user themselves — full message history, group members, channel statistics; the bot handles messaging, moderation and webhooks. Both live in the same SDK, with the same error model, as every other platform.

Updated:

What is the difference between Telegram's bot and account APIs?

Telegram has two separate APIs. The Bot API is an HTTP interface driven by a token from BotFather: the bot sends messages, moderates groups and receives updates via a webhook. The MTProto API acts on behalf of a real user account: full message history, group member lists, channel statistics and other things bots are not allowed to do.

A bot cannot message a user first (the person has to press /start) and cannot list all members of a group — that is why Socialift supports account connections too. For a detailed comparison of when to use which, see the “Bot API vs MTProto” article in the links below.

Account and bot capabilities

Account and bot capabilities — Capability matrix by platform
CapabilityAccount (MTProto)Bot (Bot API)
Send, edit, delete and pin messagesyesyes
Files: photos, video, documents, audio, voiceyesyes
Moderation: ban, restrict, promote adminsyesyes
Invite linksyesyes
Post storiesyes— with Premium or boostsno
Full conversation historyyesno
Group member listyesno
Channel statisticsyesno
Create groups and channelsyesno
Call a method the SDK does not wrapraw()call()

yesno

Notes and limits

The blank cells come from Telegram's rules: the Bot API does not give bots these capabilities. Telegram only gives channel statistics to admins of channels above a certain size — the threshold is a server-side setting (the can_view_stats flag).

Signing in to an account: phone → code → 2FA

Sign-in takes three steps. Then tg.export_session() returns the session string — store it encrypted yourself and reconnect next time with TelegramAccount(session=...), no code needed. For accounts connected in the dashboard, Socialift stores the session encrypted on its server.

telegram_account.py
import asyncio, os
from socialift import TelegramAccount

async def main(session: str | None):
    # session — a previously saved session string, or None
    async with TelegramAccount(api_id=int(os.environ["TELEGRAM_API_ID"]),
                               api_hash=os.environ["TELEGRAM_API_HASH"], session=session) as tg:
        phone = "+998901234567"
        sent = await tg.send_code(phone)
        result = await tg.sign_in(phone, code="12345", phone_code_hash=sent["phone_code_hash"])
        if result["two_factor_required"]:
            await tg.sign_in_password("...")
        new_session = tg.export_session()  # store it encrypted

        chats = await tg.dialogs(limit=50)
        history = await tg.messages("@durov", limit=50)
        members = await tg.participants("@group", limit=500)
        await tg.send_poll("@group", "Which time suits you?", ["10:00", "15:00"])
        await tg.send_file("me", "photo.jpg", caption="Report")

asyncio.run(main(session=None))

api_id and api_hash come from my.telegram.org. For account connections install the SDK with the extra: pip install "socialift[telegram]".

The Socialift server behind the dashboard and Playground keeps a pool of MTProto clients, so the handshake is not repeated per request there. In the SDK, reuse one TelegramAccount instance.

During the trial month (the first 30 days) the token unlocks every SDK feature, including TelegramAccount (the messaging licence feature). After renewal, features depend on the token's plan — “Tekshirish va muhitlar” (Check and environments) in the dashboard shows the exact list; in the dashboard Playground, account methods work regardless of plan.

What the account connection covers

01

Messages

Send, edit, delete, forward and pin; reactions, polls, scheduled messages, mark as read and the “typing” action.

02

Files and search

Send files and download media; search inside a chat or globally.

03

Group and channel data

Chat info, members, admins and the banned list, member permissions and channel statistics.

04

Group and channel management

Create, join, leave and delete groups and channels; title, description, slow mode, default permissions and chat photo.

05

Members and moderation

Invite, kick, ban and unban, restrict, promote and demote; invite links with limits, and approving or declining join requests.

06

Contacts and sessions

Add and delete contacts, block and unblock, full user info, common chats, and listing or terminating active sessions.

Telegram stories: who can post them and under what conditions

Stories exist only on the account (MTProto) side. Telegram's documentation requires calling stories.canSendStory before posting — in the SDK that is tg.can_send_story(entity), which returns the number of free story slots and raises a precise error when the conditions are not met.

telegram_story.py
import asyncio, os
from socialift import TelegramAccount

async def main(session: str):
    async with TelegramAccount(api_id=int(os.environ["TELEGRAM_API_ID"]),
                               api_hash=os.environ["TELEGRAM_API_HASH"], session=session) as tg:
        print(await tg.can_send_story("me"))
        print(await tg.story_targets())

        await tg.send_story("me", "story.mp4", caption="New product",
                            period=86400, privacy="contacts")

        active = await tg.stories("me")
        print(active)

asyncio.run(main(os.environ["TELEGRAM_SESSION"]))

Telegram sets the conditions: posting as a user requires **Telegram Premium** on the account (otherwise PREMIUM_ACCOUNT_REQUIRED), while posting as a channel or supergroup requires the post_stories admin right (CHAT_ADMIN_REQUIRED) and enough **boosts** on the channel (BOOSTS_REQUIRED). tg.story_targets() lists the channels you may post as, but being on that list is not yet permission to post — can_send_story is still called.

period is how long the story stays up before it moves to the archive: 21600 (6 hours), 43200 (12 hours), 86400 (24 hours) or 172800 (48 hours). **Without Premium only 86400 works**; Telegram rejects the rest. Omit the parameter and Telegram applies 24 hours itself.

privacy takes four values: everyone (the default), contacts, close_friends and selected — the last one requires allow. deny adds exceptions (“contacts, but not this person”). With pinned=True the story stays on the profile after it expires.

The media must be a **vertical** photo or video of at most 30 MB — the SDK checks the size locally before uploading. Telegram does not state an aspect ratio or duration as numbers, so non-vertical media ends up badly cropped in the apps.

**The Bot API cannot post stories at all** — that is Telegram's restriction and no SDK can route around it. A bot can only reply to a story sent to it. A published story can be edited with tg.edit_story(entity, story_id, caption=...) and removed with tg.delete_story(entity, story_id).

Bots: connect with a token, call any Bot API method

The bot connection covers messages, files (photo, video, document, audio, voice, animation), chat info and settings, admins, member status, moderation, invite links, webhooks and getUpdates.

telegram_bot.py
import asyncio, os
from socialift import Telegram

async def main():
    async with Telegram(token=os.environ["TELEGRAM_BOT_TOKEN"]) as bot:
        await bot.send_message("@my_channel", "Hello")

        # Any Bot API method that has no dedicated SDK wrapper
        commands = await bot.call("getMyCommands")
        print(commands)

asyncio.run(main())

The Bot API does not sign the body: pass a secret_token to set_webhook and check it comes back in the X-Telegram-Bot-Api-Secret-Token header. While a webhook is set, get_updates does not work. When a bot is connected in the dashboard, its token is checked with getMe.

bot.call("methodName", ...) reaches any Bot API method, and names the client does not wrap are forwarded automatically (bot.getChatMenuButton(...)). In the dashboard Playground's universal call, logOut and close are deliberately blocked. On the account side tg.raw(...) plays the same role, sending any Telethon TL request.

When planning a Telegram integration

  • A bot cannot message a user first — the conversation starts after the person presses /start.
  • If you need a group's member list or full conversation history, choose an account connection rather than a bot.
  • Channel statistics are available only if you are a channel admin and Telegram sets can_view_stats — the size threshold is decided server-side.
  • A session string grants full access to the account: keep it out of code and logs and store it encrypted. For accounts connected through the dashboard, Socialift stores it encrypted on the server.
  • For a bot webhook, pass your own secret in bot.set_webhook(url, secret_token=...) and check every request with Telegram.verify_webhook(request.headers, secret) — Telegram does not sign the body.
  • An account behaves like a regular user: Telegram automatically puts accounts signing in through unofficial API clients under observation and bans them permanently for flooding or spam. Do not use an account for bulk messaging.

Frequently asked questions

Can I get all members of a Telegram group through the API?

Not with a bot: the Bot API only returns admins, the member count and a single member's status. With an account connection (MTProto), participants() returns the member list, but not in full if the group's admins have hidden it (possible in larger groups).

Can a bot message a user first?

No. Under Telegram's rules the person must send /start to the bot first. An account behaves like a regular user: Telegram automatically puts accounts signing in through unofficial API clients under observation and bans them permanently for flooding or spam. Do not use an account for bulk messaging.

Is it safe to connect a Telegram account?

Sign-in happens on Telegram's side: phone number, code and, if enabled, the two-step verification password. When you connect through the dashboard, the session string is stored encrypted on the server and never reaches the browser; with the SDK you encrypt and store it yourself. You can also list active sessions and terminate them.

Why am I not getting channel statistics?

Telegram only gives statistics to admins of channels above a certain size; the exact threshold is a server-side setting reflected in channelFull.can_view_stats. The limit sits at the Telegram API level and Socialift cannot work around it.

What if the method I need is not in the SDK?

For bots, bot.call("methodName") calls any Bot API method (logOut and close are blocked only in the dashboard Playground's universal call). For accounts, tg.raw(...) sends any Telethon TL request.

Is Socialift an official Telegram partner?

No. Socialift is an independent integration layer built on Telegram's public Bot API and MTProto API. It does not hold official Telegram partner status.

Sources

  1. Telegram — Bot API
  2. Telegram — Bots FAQ
  3. Telegram — Obtaining api_id
  4. Telegram — Channel statistics
  5. Telegram — Stories
  6. Telegram — Client configuration
  7. Telegram — Channels, supergroups and groups

Related pages

Connect Telegram today

Get a token, connect a bot or an account and send your first message from the Playground.

Get a free token →