Telegram Bot API

Telegram Widgets for Your Website: Login Widget, Post Embed, Discussion and Share Button

· 9 min read

Telegram offers four widgets for websites: Telegram Login (let users sign in with their Telegram account), the post widget (embed a message from a public channel or group), the discussion widget (show a channel post's comments) and the share button. Each one is a small snippet you paste into your own HTML. These are not the interactive widgets that bots send inside chat messages since Bot API 10.4; for those, see Telegram widgets in bot messages.

Telegram widgets for websites at a glance

WidgetWhat it doesNeeds a bot?How to get the code
Telegram LoginSign up and log in with a Telegram account (OpenID Connect)Yes, plus Allowed URLs and a Client ID from @BotFatherConfigurator on core.telegram.org/bots/telegram-login
Login Widget (legacy)The older iframe login button, now archivedYes, with the domain linked via /setdomaincore.telegram.org/widgets/login-legacy
Post widgetEmbeds a message from a public channel or groupNot.me link → EMBED, or the post configurator
Discussion widgetShows a channel post with its commentsNoDiscussion configurator
Share buttonLets a visitor send your link to a chat, group, channel or Saved MessagesNoShare constructor or a plain link

Telegram Login: the new login with Telegram (OpenID Connect)

The current Telegram Login is a JavaScript library plus a standard OpenID Connect provider using the Authorization Code Flow with PKCE. You can use the library's button, any OIDC-compatible library or identity platform (Telegram names Keycloak, Authentik and Auth0 as examples), or the native SDKs for iOS and Android.

  1. Set up a bot that represents your site (how to create a Telegram bot). Users see its name and profile picture in the confirmation box, so match them to your site's name and logo.
  2. Register Allowed URLs. Open the @BotFather mini app, select the bot, then Login Widget. Add the origins where you embed the button (e.g. https://example.com) and your OIDC redirect URIs (e.g. https://example.com/auth/callback). Telegram processes logins and redirects only for these pre-registered URLs.
  3. Save the Client ID and Client Secret shown in the same section. Keep the secret on the server.
  4. Add the button to your page.
  5. Validate the ID token on your server before trusting any user data.

The embed code generated by the official configurator looks like this (data-request-access is optional: write lets your bot message the user, phone asks for the verified phone number):

<script async src="https://oauth.telegram.org/js/telegram-login.js?6" data-client-id="123456789" data-onauth="onTelegramAuth(data)" data-request-access="write"></script>

<button class="tg-auth-button">Sign In with Telegram</button>

<script>
  function onTelegramAuth(data) {
    if (data.error) return console.warn(data.error);
    // Send data.id_token to your server and verify it there
    fetch('/auth/telegram', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({id_token: data.id_token})
    });
  }
</script>

The callback receives id_token (an OIDC JWT), user (the decoded claims) or error. The library also has a JS API: Telegram.Login.init(InitOptions, callback), Telegram.Login.open([callback]) and Telegram.Login.auth(InitOptions, callback), with options client_id, scope, lang and nonce (a server-generated random string placed into the id_token against replay attacks).

Popup and COOP: telegram-login.js talks to a popup window. If your site sends Cross-Origin-Opener-Policy: same-origin, login fails; remove the header or use same-origin-allow-popups.

Scopes and OIDC endpoints

ScopeGives youClaims
openidRequired. Unique identifier and auth timestampsub, iss, iat, exp
profileUser ID, name, username, photo URLid, name, preferred_username, picture
phoneVerified phone number, with user consentphone_number
telegram:bot_accessYour bot may message the user after login—

For an OIDC client, use the discovery document https://oauth.telegram.org/.well-known/openid-configuration, response type code and PKCE with S256. If you implement the flow by hand, the endpoints are https://oauth.telegram.org/auth, https://oauth.telegram.org/token (server-side POST with Basic auth base64(client_id:client_secret)) and https://oauth.telegram.org/.well-known/jwks.json. Telegram has no separate UserInfo endpoint: all data is in the ID token, so configure your library to skip the userinfo request if it expects one.

Validate the ID token

Verify the JWT signature with the keys from the JWKS endpoint, then check that iss is https://oauth.telegram.org, aud matches your bot ID (the value you pass as client_id) and exp has not passed. Tokens are signed with RS256 by default; ES256, EdDSA and ES256K can be chosen under Login Widget > Advanced in @BotFather (EdDSA and ES256K allow only the openid scope). A Node.js example with the jose library:

import { createRemoteJWKSet, jwtVerify } from 'jose';

const JWKS = createRemoteJWKSet(new URL('https://oauth.telegram.org/.well-known/jwks.json'));

export async function verifyTelegramIdToken(idToken) {
  const { payload } = await jwtVerify(idToken, JWKS, {
    issuer: 'https://oauth.telegram.org',
    audience: '123456789' // your Client ID (bot ID)
  });
  return payload; // sub, id, name, preferred_username, picture, phone_number...
}

Classic Telegram Login Widget (legacy)

Many sites still run the original iframe-based Login Widget. Its documentation is archived, so use the flow above for new projects, but here is how the legacy one works if you maintain it.

  1. Send /setdomain to @BotFather to link your website's domain to the bot.
  2. Embed the script. With a callback:
<script async src="https://telegram.org/js/telegram-widget.js?24" data-telegram-login="your_bot" data-size="large" data-onauth="onTelegramAuth(user)" data-request-access="write"></script>
<script type="text/javascript">
  function onTelegramAuth(user) {
    alert('Logged in as ' + user.first_name + ' ' + user.last_name + ' (' + user.id + (user.username ? ', @' + user.username : '') + ')');
  }
</script>

Instead of data-onauth you can set data-auth-url="https://example.com/auth/telegram": the user is redirected there with id, first_name, last_name, username, photo_url, auth_date and hash as query parameters. Other options from the configurator: data-size (large, medium, small), data-userpic="false", data-radius and data-request-access="write".

Check the hash on the server

Never trust the data until you verify it. The algorithm: take all received fields except hash, sort them alphabetically, join them as key=value with a line feed (\n) to get the data-check-string; the secret key is SHA256 of the bot token (raw bytes); compute HMAC-SHA-256 of the data-check-string with that key and compare its hex form with hash. Then check that auth_date (a Unix timestamp) is recent. Pass only the fields Telegram sent, not your own query parameters.

import hashlib
import hmac
import time

def check_telegram_auth(data: dict, bot_token: str, max_age: int = 86400) -> bool:
    fields = {k: v for k, v in data.items() if k != "hash"}
    data_check_string = "\n".join(f"{k}={fields[k]}" for k in sorted(fields))
    secret_key = hashlib.sha256(bot_token.encode()).digest()
    calc_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(calc_hash, str(data.get("hash", ""))):
        return False
    return time.time() - int(fields["auth_date"]) <= max_age

# Flask: check_telegram_auth(request.args.to_dict(), BOT_TOKEN)
const crypto = require('crypto');

function checkTelegramAuth(data, botToken, maxAgeSec = 86400) {
  const { hash, ...fields } = data;
  const dataCheckString = Object.keys(fields).sort()
    .map((k) => `${k}=${fields[k]}`)
    .join('\n');
  const secretKey = crypto.createHash('sha256').update(botToken).digest();
  const calcHash = crypto.createHmac('sha256', secretKey).update(dataCheckString).digest('hex');
  if (typeof hash !== 'string' || hash.length !== calcHash.length) return false;
  if (!crypto.timingSafeEqual(Buffer.from(calcHash), Buffer.from(hash))) return false;
  return Date.now() / 1000 - Number(fields.auth_date) <= maxAgeSec;
}

// Express: checkTelegramAuth(req.query, process.env.BOT_TOKEN)

A wrong token is the most common cause of a mismatch. Check that the token on your server belongs to the login bot with getMe in the Bot API Tester: the returned username must equal data-telegram-login. If you need to find or rotate the token, see the bot token guide. Note that this differs from Mini App initData validation, which derives its key with HMAC and the string WebAppData.

Telegram post embed

You can embed any message from a public channel or group. Open its t.me link (e.g. t.me/durov/43) in a browser and click < > EMBED, or paste the link into the post widget configurator. The result is one script tag:

<script async src="https://telegram.org/js/telegram-widget.js?24" data-telegram-post="durov/43" data-width="100%"></script>

Options from the configurator: width (data-width, default 100%), author photo (data-userpic="true" to always show, "false" to hide, omit for auto), accent color (data-color with a hex value such as 13B4C6) and dark theme (data-dark="1"; with a color the configurator may also add data-dark-color).

Discussion widget: Telegram comments on your site

The discussion widget shows a public channel post together with its comments. Give it a link to a post with comments:

<script async src="https://telegram.org/js/telegram-widget.js?24" data-telegram-discussion="contest/198" data-comments-limit="5"></script>

You can also pass only the channel (data-telegram-discussion="your_channel"). Then each article page shows the discussion of the channel post that links to it, as soon as you post that link in the channel. For this mode your page header must contain <link rel="canonical" href="%page_url%"> with the page's canonical URL. Options: comments limit (data-comments-limit, 3–50 in the configurator), data-height, data-colorful="1" for different name colors, data-color and data-dark="1".

Telegram share button

When a visitor presses the share button, Telegram asks them to pick a chat, group or channel and lets them edit the optional text before sending. The constructor on core.telegram.org/widgets/share produces:

<script async src="https://telegram.org/js/telegram-widget.js?24" data-telegram-share-url="https://example.com/article" data-comment="Check this out!" data-size="large"></script>

Omit data-size for the medium button; data-text="notext" shows the icon only. For your own design, link to https://t.me/share/url?url={url}&text={text} with both values URL-encoded:

<a href="https://t.me/share/url?url=https%3A%2F%2Fexample.com%2Farticle&text=Check%20this%20out%21">Share in Telegram</a>
const shareUrl = 'https://t.me/share/url?url=' + encodeURIComponent(location.href)
  + '&text=' + encodeURIComponent(document.title);
document.querySelector('#tg-share').href = shareUrl;

Troubleshooting

Next steps

Frequently asked questions

How do I add a Telegram login button to my website?

Pick a bot, open the @BotFather mini app, select the bot and then Login Widget, add your site origin and redirect URIs as Allowed URLs and copy the Client ID. Then add the telegram-login.js snippet with data-client-id to your page and verify the returned id_token on your server.

Is the old Telegram Login Widget still supported?

Its documentation is archived at core.telegram.org/widgets/login-legacy. Telegram now documents the Telegram Login library and an OpenID Connect flow as the main way to log in with Telegram, so prefer those for new projects.

How do I verify Telegram Login Widget data on the server?

For the legacy widget, build the data-check-string from all received fields except hash, sorted alphabetically as key=value lines joined by \n. Compute HMAC-SHA-256 of it with SHA256(bot_token) as the key and compare the hex result with hash; also check auth_date. For the new login, validate the id_token JWT against Telegram's JWKS.

How do I embed a Telegram post on my website?

Open the post's t.me link (for example t.me/durov/43) in a browser and click EMBED, or use the configurator on core.telegram.org/widgets/post. Only posts from public channels and groups can be embedded.

How do I make a custom Telegram share button?

Link to https://t.me/share/url?url={url}&text={text}, where both values are URL-encoded, for example with encodeURIComponent in JavaScript. The text is optional and the user can edit it before sending.

How to Create a Telegram Bot: Step by Step with BotFather and Python

How to create a Telegram bot step by step: register it with @BotFather, get the token, test it with getMe and send a first message with curl or Python.

Telegram Bot API 10.0–10.5: Bot Settings, Widgets, Rich Messages, Ephemeral Messages, Guest Mode and More

What's new in Telegram Bot API 10.0–10.5: setMySettings and BotFullInfo, HTML widgets, rich and ephemeral messages, guest mode, with JSON examples.

Telegram Bot API Limits: Rate Limits, 429 Errors, File Sizes and Message Length

Telegram Bot API rate limits explained: 30 msg/s, 1 msg/s per chat, 20/min in groups, handling 429 retry_after, plus file size and message length limits.

How to Send a Message with the Telegram Bot API (sendMessage)

Telegram Bot API send message guide: sendMessage with curl, Python and JavaScript, HTML and MarkdownV2 formatting, inline buttons and error fixes.

Telegram Bot Token: How to Get It, Find It Again, Check It and Keep It Safe

Telegram bot token guide: get one from @BotFather, find the token of an existing bot, check it with getMe, revoke a leaked token and store it safely.

How to Set Up a Telegram Bot Webhook: setWebhook, Secret Token and Troubleshooting

Set up a Telegram bot webhook: setWebhook URL requirements, secret_token header check, getWebhookInfo debugging, deleteWebhook and fixes for n8n.

How to Get a Telegram Chat ID for a User, Group, Channel or Topic

How to get a Telegram chat ID for a user, group, supergroup, channel or forum topic with getUpdates, plus fixes for an empty result and 409 Conflict.

Telegram Test Server: How to Test a Bot in the Telegram Test Environment

Use the Telegram test server for bots: log in to the test environment, create a test bot, call the Bot API via /test/ and switch our tester to TEST.

TelegramWidget JavaScript API: Reference, Events, Error Codes and Limits

TelegramWidget JavaScript API reference: properties, request(), events, error codes, CSS variables, widget_query and answerWidgetQuery, plus every limit.

Telegram Widget Examples: Complete HTML and Python Bot Code

Working Telegram widget examples with full code: a static order card, a counter with widget_query requests, a shared live poll and a local preview stub.

Telegram Widgets: Interactive HTML Inside Bot Messages

Telegram widgets (Bot API 10.4): what they are, how sendWidget, chat_data and public_data work, where they run today and how they differ from Mini Apps.

How to Test a Telegram Mini App: From Browser Mock to Real Telegram

Test a Telegram Mini App step by step: browser mock mode, localhost via HTTPS tunnel, test environment, DevTools per platform, initData validation.