Telegram Bot API

Telegram Inline Bot: How to Enable Inline Mode and Answer Inline Queries

· 8 min read

A Telegram inline bot answers queries typed right in the message field: the user writes @your_bot and some text in any chat, your bot receives an inline_query update and replies with answerInlineQuery, and the user taps one of the results to send it. To build one, enable inline mode (with /setinline in @BotFather or, since Bot API 10.5, with setMySettings), handle inline_query updates and return up to 50 results. Below: each step plus a complete Python and JavaScript example.

How inline mode works

Inline mode works in any chat, even where the bot is not a member. The flow:

  1. The user types the bot's username and a query in the input field, for example @your_bot hello. Nothing is sent to the chat yet.
  2. The bot gets an inline_query update.
  3. The bot calls answerInlineQuery with a list of results: articles, photos, GIFs, videos, stickers, locations and more.
  4. The user taps a result. The message is sent by the user, and the bot's username is shown next to the sender's name; in the Bot API such a message has the via_bot field.
  5. Optionally, the bot receives a chosen_inline_result update telling which result was sent.

Enable inline mode for your Telegram bot

Inline mode is off for new bots. If you don't have a bot yet, start with how to create a Telegram bot. Then pick one of two ways.

Option 1: @BotFather

  1. Send /setinline to @BotFather and choose your bot.
  2. Enter the placeholder text users see in the input field after typing the bot's username, e.g. Type text to format…
  3. Optional: /setinlinegeo requests user location with each query; /setinlinefeedback enables chosen_inline_result updates.

Option 2: setMySettings (Bot API 10.5)

Since Bot API 10.5 a bot can change its own settings with setMySettings. Settings you don't pass stay unchanged:

curl "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/setMySettings" \
  -H "Content-Type: application/json" \
  -d '{"supports_inline_queries": true, "inline_query_placeholder": "Type text to format…", "inline_feedback_share_denominator": 1}'

The inline parameters are:

To check the result without code, open setMySettings in the Bot API Tester, paste your token and run it, then call getMe: its BotFullInfo result contains supports_inline_queries and, if you set a custom one, inline_query_placeholder.

The inline_query update

While the user types, the bot receives InlineQuery objects with these fields:

FieldMeaning
idUnique query ID; pass it to answerInlineQuery as inline_query_id
fromThe user who typed the query
queryQuery text, up to 256 characters; may be empty — return default or trending results then
offsetOffset of the results to return; controlled by your bot through next_offset
chat_typeOptional: sender (private chat with the query sender), private, group, supergroup or channel; usually unknown for secret chats
locationOptional; only if the bot requests user location

If you pass allowed_updates to getUpdates or setWebhook, include inline_query (and chosen_inline_result if you need it), otherwise these updates won't arrive.

answerInlineQuery parameters

answerInlineQuery returns True on success. No more than 50 results per query are allowed.

ParameterDescription
inline_query_idRequired. The id of the query
resultsRequired. Array of InlineQueryResult objects (≤ 50)
cache_timeMaximum time in seconds the result may be cached on the server; default 300
is_personaltrue caches results only for this user; by default any user sending the same query may get them
next_offsetOffset the client sends with the next query of the same text; empty string if there are no more results; up to 64 bytes
buttonInlineQueryResultsButton shown above the results

Inline result types

Telegram clients support 20 result types. Twelve describe new content (article, photo, gif, mpeg4_gif, video, audio, voice, document, location, venue, contact, game), and eight InlineQueryResultCached… types reuse files already stored on Telegram servers via file_id. Every result needs a type and an id of 1–64 bytes. The most common ones:

All URLs in inline results become visible to end users, so treat them as public. Formatting rules for parse_mode are the same as in sending messages with the Bot API.

Example: an inline bot in Python and JavaScript

This bot formats the query as bold, italic or monospace. An empty query gets a button to the private chat, where /start replies with buttons that switch back to inline mode. Set the BOT_TOKEN environment variable before running.

import html
import os
import requests

TOKEN = os.environ["BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}"


def call(method, **params):
    data = requests.post(f"{API}/{method}", json=params, timeout=40).json()
    if not data["ok"]:
        raise RuntimeError(f"{method}: {data['error_code']} {data['description']}")
    return data["result"]


def article(result_id, title, text, message_html):
    return {
        "type": "article",
        "id": result_id,  # 1-64 bytes, unique within one answer
        "title": title,
        "description": text[:100],
        "input_message_content": {"message_text": message_html, "parse_mode": "HTML"},
    }


def on_inline_query(query):
    text = query["query"].strip()
    if not text:  # empty query: no results, only a button that opens the private chat
        call("answerInlineQuery", inline_query_id=query["id"], results=[], cache_time=5,
             button={"text": "How to use this bot", "start_parameter": "help"})
        return
    safe = html.escape(text)
    results = [
        article("bold", "Bold", text, f"<b>{safe}</b>"),
        article("italic", "Italic", text, f"<i>{safe}</i>"),
        article("mono", "Monospace", text, f"<code>{safe}</code>"),
    ]
    call("answerInlineQuery", inline_query_id=query["id"], results=results, cache_time=5)


def on_message(msg):
    if msg.get("text", "").startswith("/start"):  # also "/start help" from the button
        call("sendMessage", chat_id=msg["chat"]["id"],
             text="Type my username and some text in any chat to format it.",
             reply_markup={"inline_keyboard": [[
                 {"text": "Try it here", "switch_inline_query_current_chat": "Hello"},
                 {"text": "Choose a chat", "switch_inline_query": "Hello"},
             ]]})


offset = 0
while True:
    updates = call("getUpdates", offset=offset, timeout=30,
                   allowed_updates=["message", "inline_query", "chosen_inline_result"])
    for update in updates:
        offset = update["update_id"] + 1
        try:
            if "inline_query" in update:
                on_inline_query(update["inline_query"])
            elif "chosen_inline_result" in update:
                chosen = update["chosen_inline_result"]
                print("chosen:", chosen["result_id"], "for query:", chosen["query"])
            elif "message" in update:
                on_message(update["message"])
        except RuntimeError as err:
            print(err)
const TOKEN = process.env.BOT_TOKEN;
const API = `https://api.telegram.org/bot${TOKEN}`;

async function call(method, params = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
    signal: AbortSignal.timeout(40_000),
  });
  const data = await res.json();
  if (!data.ok) throw new Error(`${method}: ${data.error_code} ${data.description}`);
  return data.result;
}

const escapeHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

function article(id, title, text, messageHtml) {
  return {
    type: "article",
    id, // 1-64 bytes, unique within one answer
    title,
    description: text.slice(0, 100),
    input_message_content: { message_text: messageHtml, parse_mode: "HTML" },
  };
}

async function onInlineQuery(query) {
  const text = query.query.trim();
  if (!text) { // empty query: no results, only a button that opens the private chat
    await call("answerInlineQuery", {
      inline_query_id: query.id, results: [], cache_time: 5,
      button: { text: "How to use this bot", start_parameter: "help" },
    });
    return;
  }
  const safe = escapeHtml(text);
  const results = [
    article("bold", "Bold", text, `<b>${safe}</b>`),
    article("italic", "Italic", text, `<i>${safe}</i>`),
    article("mono", "Monospace", text, `<code>${safe}</code>`),
  ];
  await call("answerInlineQuery", { inline_query_id: query.id, results, cache_time: 5 });
}

async function onMessage(msg) {
  if (msg.text?.startsWith("/start")) { // also "/start help" from the button
    await call("sendMessage", {
      chat_id: msg.chat.id,
      text: "Type my username and some text in any chat to format it.",
      reply_markup: { inline_keyboard: [[
        { text: "Try it here", switch_inline_query_current_chat: "Hello" },
        { text: "Choose a chat", switch_inline_query: "Hello" },
      ]] },
    });
  }
}

let offset = 0;
while (true) {
  const updates = await call("getUpdates", {
    offset, timeout: 30, allowed_updates: ["message", "inline_query", "chosen_inline_result"],
  });
  for (const update of updates) {
    offset = update.update_id + 1;
    try {
      if (update.inline_query) await onInlineQuery(update.inline_query);
      else if (update.chosen_inline_result) {
        const chosen = update.chosen_inline_result;
        console.log("chosen:", chosen.result_id, "for query:", chosen.query);
      } else if (update.message) await onMessage(update.message);
    } catch (err) {
      console.error(err.message);
    }
  }
}

Run the JavaScript version as bot.mjs with Node.js 18+, then type @your_bot hello in any chat. The same handlers work with a webhook — see Telegram bot webhook setup.

Pagination with next_offset

More than 50 matches? Return pages: offset is empty in the first request, and your next_offset comes back when the user scrolls down:

PAGE_SIZE = 20  # answerInlineQuery accepts at most 50 results


def answer_page(query, items):
    start = int(query["offset"] or 0)  # offset is "" in the first request
    page = items[start:start + PAGE_SIZE]
    more = start + PAGE_SIZE < len(items)
    call("answerInlineQuery", inline_query_id=query["id"], results=page,
         next_offset=str(start + PAGE_SIZE) if more else "")  # "" = no more results
const PAGE_SIZE = 20; // answerInlineQuery accepts at most 50 results

async function answerPage(query, items) {
  const start = Number(query.offset || 0); // offset is "" in the first request
  const page = items.slice(start, start + PAGE_SIZE);
  const more = start + PAGE_SIZE < items.length;
  await call("answerInlineQuery", {
    inline_query_id: query.id, results: page,
    next_offset: more ? String(start + PAGE_SIZE) : "", // "" = no more results
  });
}

chosen_inline_result and inline feedback

With feedback enabled, the bot receives a ChosenInlineResult object with result_id, from, query, optional location and optional inline_message_id. Because of caching, popular bots can receive more chosen results than actual queries, so under high load receive only 1/10, 1/100 or 1/1000 of them.

inline_message_id is present only if the sent message has an inline keyboard. Store it to edit the message later with editMessageText (pass inline_message_id instead of chat_id and message_id); button presses on that message arrive as callback_query with the same inline_message_id.

Results button and switching back to the chat

The button parameter shows an InlineQueryResultsButton above the results (or instead of them). It has a text and exactly one of:

Typical use: ask the user to connect an account first, then send an inline keyboard button with switch_inline_query (the user picks a chat), switch_inline_query_current_chat (inserts @your_bot query in the current chat) or switch_inline_query_chosen_chat (limits the choice to users, bots, groups or channels).

Troubleshooting

SymptomLikely cause and fix
Nothing happens after typing @your_botInline mode is not enabled: use /setinline or setMySettings.
No inline_query updatesallowed_updates was set earlier without inline_query (the list is remembered), or a webhook is active and getUpdates returns 409 Conflict.
Old results keep showingServer-side caching: lower cache_time (default 300 s) and use is_personal for per-user results.
400 Bad Request: query is too old and response timeout expired or query ID is invalidThe answer came too late or with a wrong ID. Answer right away, do slow work in the background.
No chosen_inline_resultInline feedback is off: /setinlinefeedback or inline_feedback_share_denominator.
Photo results don't appearphoto_url must be a public JPEG up to 5 MB, and thumbnail_url is required.

Busy inline bots should also respect the Telegram Bot API limits.

Frequently asked questions

How do I enable inline mode for a Telegram bot?

Send /setinline to @BotFather, choose the bot and enter the placeholder text. Since Bot API 10.5 the bot can also do it itself with setMySettings and supports_inline_queries: true (plus an optional inline_query_placeholder).

How many results can answerInlineQuery return?

No more than 50 results per call. For longer lists, return a page and pass next_offset (up to 64 bytes); the client sends it back in offset when the user scrolls.

Why do my inline results not change after I update the code?

Results may be cached on Telegram's servers for cache_time seconds, 300 by default. Use a small cache_time while developing, and is_personal: true if results depend on the user.

Does an inline bot need to be added to the chat?

No. The user types the bot's username and a query in the input field of any chat; the bot gets an inline_query update and the chosen result is sent by the user, marked with the bot's username (via_bot).

How do I know which inline result the user sent?

Enable inline feedback with /setinlinefeedback in @BotFather or inline_feedback_share_denominator in setMySettings (1, 10, 100 or 1000). The bot then receives chosen_inline_result updates with result_id and query.

Why is inline_message_id missing in chosen_inline_result?

It is only present when the sent message has an inline keyboard attached. Add reply_markup to the result if you want to edit the message later or receive callback queries from it.

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.

How to Deploy a Telegram Bot: VPS, Docker and Serverless Hosting

How to deploy a Telegram bot: polling vs webhook, a systemd service on a VPS, Docker, Cloudflare Workers with secret_token, plus a launch checklist.

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 Errors: What Each Error Means and How to Fix It

Telegram Bot API errors explained: 400 chat not found, 403 bot was blocked by the user, 409 Conflict, 429 retry_after. Causes, fixes and handling code.

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.

Telegram Bot Commands: setMyCommands, Command Scopes and /start Deep Links

Set up Telegram bot commands: @BotFather /setcommands, setMyCommands with scopes and languages, /start deep link parameters and /cmd@bot in groups.

Telegram Bot Keyboards: Inline Keyboard, Callback Buttons and Reply Keyboard

Add Telegram bot buttons: inline keyboard with callback_data, answerCallbackQuery, editing the message after a press, reply keyboard and ForceReply.

n8n Telegram Integration: Connect a Telegram Bot, Trigger Workflows and Send Messages

Connect n8n to Telegram: bot token as Access Token, Telegram Trigger webhook over public HTTPS, sending messages by chat id, and fixes for common errors.

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 Stars Payments for Bots: Invoices, Pre-Checkout, Refunds and Subscriptions

Accept Telegram Stars payments in your bot: sendInvoice with XTR, pre_checkout_query, successful_payment, refunds, subscriptions, Python/JS code.

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.

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

Add Telegram to your website: the new Telegram Login (OIDC), the legacy Login Widget with hash check code, post embeds, comments and a share button.

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.