Skip to main content
Socialift
Documentation sections
Setup

Telegram setup: bot token and account api_id/api_hash

Telegram offers two ways in. A bot uses the Bot API with a token from /newbot in @BotFather: it sees only what bots are allowed to see and receives updates by webhook or polling. An account uses MTProto: register an app at my.telegram.org to get api_id and api_hash, then sign in with a phone number, a login code and, if enabled, the 2FA password.

Updated:

Bot or account: which one do you need?

Use a bot for customer-facing automation: replies, notifications, channel posts, group moderation — it's official, safe and needs only a token. Use an account (MTProto) for what bots can't do: reading chat history, listing group members, acting as a real user. The risk is higher: accounts using unofficial API clients are put under observation, and flooding or spam leads to a permanent ban.

Bot vs account

Bot vs account — Capability matrix by platform
Bot (Bot API)Account (MTProto)
CredentialsToken from @BotFatherapi_id + api_hash from my.telegram.org plus phone sign-in
Sign-inNone — the token is enoughPhone → code → 2FA password (if enabled)
Group messagesIn privacy mode only commands, replies and similar (unless disabled or the bot is an admin)Everything the user sees
UpdatesWebhook (setWebhook) or getUpdates — not bothThe connected client session
Socialift dashboard“Ulanishlar” (Connections) → “Telegram bot” (no key needed)“Kalitlar” (Keys) → “Telegram API (my.telegram.org)” + “Ulanishlar” → “Telegram akkaunt” (account)
Python SDKTelegram(token=...)TelegramAccount(api_id=..., api_hash=..., session=...), pip install "socialift[telegram]"
What to keep secretThe tokenapi_hash and the session string

How to create a Telegram bot and get its token

  1. Send /newbot to @BotFather

    Open @BotFather in Telegram and send the /newbot command.

  2. Choose a name and username

    The name appears in contact details. The username must be 5–32 characters of Latin letters, digits and underscores, and must end in bot (for example shop_support_bot).

  3. Store the token

    BotFather returns a token like 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw. Anyone who has it controls the bot — keep it in an environment variable. If it leaks, generate a new one with /token in BotFather.

  4. Configure privacy mode for groups

    By default a bot runs in privacy mode: in groups it receives only commands addressed to it, replies to its messages and service messages. To see everything, use /setprivacy → Disable, then remove the bot from the group and add it again. Admin bots receive all messages regardless.

  5. Set the webhook

    setWebhook needs an HTTPS URL on port 443, 80, 88 or 8443. Pass a secret_token (1–256 characters: A-Z, a-z, 0-9, _, -) — Telegram sends it back in the X-Telegram-Bot-Api-Secret-Token header on every request. While a webhook is set, getUpdates doesn't work; undelivered updates are kept for no longer than 24 hours.

How to get api_id and api_hash and sign in to an account

  1. Sign up in an official app

    Getting an api_id requires a Telegram account registered through an official Telegram app.

  2. Register an app at my.telegram.org

    Log in to my.telegram.org with your phone number → API development tools → fill out the form. For now each phone number can have only one api_id.

  3. Copy api_id and api_hash

    api_id is a number, api_hash is 32 hex characters. Never share the api_hash: it lets anyone sign in on behalf of your application.

  4. Sign in with phone, code and 2FA

    auth.sendCode sends the code: most often it arrives as a service message inside the Telegram app, but it can also come by SMS, a call or other methods. The code goes to auth.signIn together with phone_code_hash. If two-step verification is enabled you get SESSION_PASSWORD_NEEDED and continue with the password. Other sessions are notified about the new login.

  5. Keep the session secret

    The session string you get after signing in is equivalent to a password: store it encrypted. With it, the next run connects without a code.

How to connect Telegram in the Socialift dashboard

  1. Connect the bot

    In “Ulanishlar” (Connections) → “Telegram bot” paste the token and click “Botni ulash” (Connect bot). Socialift checks the token with getMe right away — invalid tokens aren't saved. If privacy mode is on, you'll see a warning. A bot can be connected to only one Socialift user. Bots need nothing on the “Kalitlar” (Keys) page.

  2. Point the bot webhook to Socialift if needed

    The Playground section “Webhook va universal chaqiruv” (Webhook and universal call) sets the bot's webhook to the Socialift server with a separate secret_token per bot. A bot has a single webhook URL: this replaces the one your own server set (and vice versa).

  3. Add the key for accounts

    In “Kalitlar” (Keys) → “Telegram API (my.telegram.org)” enter api_id and api_hash and click “Saqlash va tekshirish” (Save and verify). Socialift checks the format and tests the pair against Telegram with MTProto auth.exportLoginToken — no phone number needed; API_ID_INVALID rejects the key. Without your own key, Socialift's key is used if one is configured.

  4. Connect the account

    “Ulanishlar” → “Telegram akkaunt”: phone number (+998901234567) → “Kod yuborish” (Send code) → the code (usually delivered in the Telegram app, not by SMS) → “Tasdiqlash” (Confirm) → the password if 2FA is on → “Kirish” (Sign in). The intermediate login state lives about 10 minutes.

  5. Disconnecting

    For an account, “Uzish” (Disconnect) also terminates the session on Telegram's side — even a leaked copy of the session stops working.

Bot: token and webhook in the Python SDK

Telegram.from_env() reads TELEGRAM_BOT_TOKEN.

telegram_bot.py
import asyncio
import os

from socialift import Telegram


async def main() -> None:
    # TELEGRAM_BOT_TOKEN, SOCIALIFT_LICENSE_KEY
    async with Telegram.from_env() as bot:
        me = await bot.get_me()  # the cheapest way to validate the token
        print(me["username"], me.get("can_read_all_group_messages"))
        await bot.set_webhook(
            "https://example.com/tg",
            secret_token=os.environ["TG_WEBHOOK_SECRET"],
            allowed_updates=["message"],
        )


asyncio.run(main())

Explicitly: Telegram(token="123456789:AA..."). Check incoming requests with socialift.webhooks.verify_telegram_request(headers, secret_token) — Telegram doesn't sign the body, so this header is the only protection.

Account: api_id, api_hash and sign-in in the Python SDK

Requires pip install "socialift[telegram]". TelegramAccount.from_env() reads TELEGRAM_API_ID, TELEGRAM_API_HASH and TELEGRAM_SESSION.

telegram_login.py
import asyncio
import os
from getpass import getpass

from socialift import TelegramAccount


async def main() -> None:
    phone = "+998901234567"
    async with TelegramAccount(api_id=os.environ["TELEGRAM_API_ID"],
                               api_hash=os.environ["TELEGRAM_API_HASH"]) as tg:
        sent = await tg.send_code(phone)
        result = await tg.sign_in(phone, code=input("Code: "), phone_code_hash=sent["phone_code_hash"])
        if result.get("two_factor_required"):
            await tg.sign_in_password(getpass("2FA password: "))
        print(tg.export_session())  # equivalent to a password — store it encrypted


asyncio.run(main())

On the next run: TelegramAccount(api_id=..., api_hash=..., session=saved_session) — no code is requested.

Common mistakes

  • The bot token is left in code, a repository or logs.
  • The bot doesn't see group messages — privacy mode is on, or the bot wasn't re-added after /setprivacy.
  • getUpdates is called while a webhook is set.
  • A webhook without secret_token — anyone who knows the URL can send fake updates.
  • The webhook uses an unsupported port or plain HTTP.
  • The same bot's webhook is set both on your server and in Socialift — the last setWebhook wins.
  • The api_hash is public, or the session string is stored unencrypted.
  • Mass messaging or flooding from an account — risk of a permanent ban.
  • Waiting for an SMS while the code was delivered in the Telegram app.

Frequently asked questions

How do I get a Telegram bot token?

Send /newbot to @BotFather and pick a name and a username ending in bot — BotFather returns the token. The token gives full control of the bot, so keep it secret; if it leaks, generate a new one with /token.

Where do I get api_id and api_hash?

Log in to my.telegram.org with your phone number and fill out the form under API development tools — you'll get api_id and api_hash. For now each phone number can have only one api_id.

Why doesn't my bot see messages in a group?

Bots run in privacy mode by default and receive only commands, replies to their messages and service messages in groups. Run /setprivacy → Disable in BotFather and re-add the bot to the group, or make the bot an admin.

Can I use a webhook and getUpdates at the same time?

No. While a webhook is set, getUpdates doesn't work. To switch to polling, call deleteWebhook first (bot.delete_webhook() in the SDK).

Is it safe to connect a personal Telegram account to the API?

It's technically possible, but be careful: accounts signing in through unofficial API clients are automatically put under observation, and flooding, spam or faking subscriber and view counts gets you banned forever. Treat the session string and api_hash like passwords.

Does a bot need keys in Socialift?

No. A bot is connected under “Ulanishlar” (Connections) → “Telegram bot” with just the BotFather token. The “Telegram API (my.telegram.org)” card on the “Kalitlar” (Keys) page is only for accounts (MTProto).

Sources

  1. Telegram: Bot features — BotFather, privacy mode
  2. Telegram Bot API: setWebhook
  3. Telegram: Obtaining api_id
  4. Telegram: User authorization

Related pages