LIVE PORTAL Telegram v11.8 API Synchronized Free Animated Stickers
translate Translated
admin_panel_settings ADMIN CONTROLS Guide #18460 • Beginner Basics

Inline Bots Architecture: @gif, @pic & Inline Queries Engine

[Telegram 187] Inline Bots Architecture: @gif, @pic & Inline Queries Engine
Module 08: Bots, TMA Mini Apps & Web3 TON Ecosystem

Step 087: Inline Bots Architecture: @gif, @pic & Inline Queries Engine

87% Complete (87/100)

Most chat platforms force users to disrupt conversations by leaving their active chat room to search external services, open web browsers, or interact with standalone chatbots. Telegram's Inline Bots Architecture completely shatters this friction. By typing a bot's handle directly in any message input field—such as @gif happy, @pic sunsets, or custom developer bots like @tgway_helper_bot btc—users invoke real-time search queries without ever adding the bot as a member or exposing chat histories. In this comprehensive guide, we dissect the end-to-end mechanics of the MTProto Inline Handshake, answerInlineQuery payload construction, Edge CDN caching (cache_time), pagination offsets, and conversion-driving Switch PM onboarding hooks.

Inline Bots Architecture Banner
Figure 87.1: Real-Time Inline Query Cycle, MTProto Edge Cache & Client Viewport Popups. TELEGRAM 187 • INLINE ENGINE

1. Anatomy of the MTProto Inline Query Handshake

When a user types @botname query into any chat input box, the Telegram client automatically initiates a debounced query handshake:

Stage 1: Keystroke Debounce

Client-Side Rate Throttling

Telegram clients debounce input keystrokes by approximately 300 milliseconds. Only when the user pauses typing is the query payload dispatched over MTProto to Telegram's edge servers.

Stage 2: Edge CDN Lookup

Zero-Latency Cache Hit

Telegram's edge proxies inspect their global distributed cache for identical queries previously answered within the cache_time window. Cache hits return to the user in <15ms without touching your bot server.

Stage 3: Webhook Dispatch

InlineQuery Event Delivery

On a cache miss, an inline_query update is delivered to your bot's webhook containing the query string, user identity, and chat type category.

2. Implementing answerInlineQuery with Rich Result Payloads

Bots answer inline queries by sending an HTTP POST request to /answerInlineQuery containing an array of up to 50 result objects. Below is a production Python implementation handling articles, GIFs, and interactive callback buttons:

python_inline_query_handler.py Python 3.11+ / PTB v20
from telegram import InlineQueryResultArticle, InputTextMessageContent, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, InlineQueryHandler

async def handle_inline_query(update, context):
    query = update.inline_query.query.strip().lower()
    user = update.inline_query.from_user
    chat_type = update.inline_query.chat_type  # 'sender', 'private', 'group', 'supergroup', or 'channel'

    results = []

    # Example 1: Rich Article Card with Inline Action Button
    results.append(
        InlineQueryResultArticle(
            id="1",
            title=f"Telegram 100 Guide: {query or 'Basics'}",
            description="Official TGWAY Curriculum & Developer Documentation",
            thumbnail_url="https://tgway.com/images/guides/guide_18459.webp",
            input_message_content=InputTextMessageContent(
                message_text=f"TGWAY Masterclass

Explore Telegram engineering: {query}",
                parse_mode="HTML"
            ),
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton("Open Full Curriculum ➔", url="https://tgway.com/guides?category=basics")]
            ])
        )
    )

    # Edge CDN Caching Strategy:
    # cache_time=300: Telegram caches this response for 5 minutes.
    # is_personal=False: Shared across all users worldwide querying the same string.
    await update.inline_query.answer(
        results,
        cache_time=300,
        is_personal=False,
        switch_pm_text="⚡ Connect Telegram Stars Wallet",
        switch_pm_parameter="stars_auth"
    )

3. Edge Caching Mechanics & The "Switch PM" Onboarding Funnel

Inline bots possess an extraordinary growth feature: the Switch PM Button (switch_pm_text). When configured, Telegram displays a permanent, styled call-to-action button at the very top of the inline results popup:

1. Zero-Friction Chat Transition

Tapping the Switch PM button instantly navigates the user into a private 1-on-1 DM with your bot, transmitting a deep-linked /start <switch_pm_parameter> payload.

2. Private Authentication & Wallet Binding

Because users cannot enter private credentials or sign TON transactions inside a public group chat, the Switch PM button routes them to DM to connect their Web3 wallet, authenticate with OAuth, or configure user preferences.

3. Return to Origin Chat with Prepared Payload

After completing onboarding in private DM, bots can utilize an inline button with switch_inline_query to immediately bounce the user back to their original conversation with the query already populated!

Interactive Lab Simulator

Inline Query Engine & Result Dispatcher Simulator

ENGINE: MTPROTO_INLINE_V2

Inline Query Input

Telegram Client Popup Viewport LATENCY: 12ms (CACHE HIT)
⚡ Connect Wallet & Authorize Bot
TGWAY Telegram 187: Inline Bots Architecture
Tap to send rich card with inline keyboard button to chat...
TON Ecosystem Guide: Jettons & Wallets
Deploy smart contracts & handle Web3 wallet sign-ins.
INLINE MTPROTO TELEMETRY STREAM CONNECTED
[INIT] Inline handler listening for keystrokes...

5. Complete System Architecture Blueprint: Inline Queries & Edge CDN

Examine the comprehensive architectural infographic detailing query debouncing, MTProto edge CDN caching, answerInlineQuery object models, and Switch PM deep linking:

Inline Bots Architecture Blueprint
Click to Enlarge High-Res Blueprint
Figure 87.2: Full 2:3 Masterclass Infographic Summary. Click to inspect high-resolution vector details.

6. Comparison: Inline Bots vs. Bot Commands vs. Keyboard Buttons vs. Mini Apps

Feature Inline Mode (@bot) Slash Commands (/cmd) Inline Keyboard Buttons Mini Apps (TMA)
Chat Scope Universal (Any Chat) Member chats only Attached to bot message Universal / Menu Button
User Friction Zero (No /start needed) High (Must start bot) Zero (One tap) Zero (Modal popup)
Edge CDN Caching Built-in (cache_time) None (Hits backend) None Standard HTTP Cache
Interactive Depth Search & Pick List Conversational text Callback triggers Full HTML5/WebGL/Web3

7. Frequently Asked Questions (FAQ)

Q1: How do I enable inline queries for my existing bot?

Open @BotFather in Telegram → send /setinline → select your bot → enter an inline placeholder string (e.g., "Search articles or crypto pairs..."). Inline capabilities will be activated immediately across all Telegram clients globally.

Q2: Can an inline bot see which group chat a user is currently typing in?

No. Telegram protects user privacy completely. The incoming inline_query object contains only the query string, user ID, and a coarse chat_type enum ('sender', 'private', 'group', 'supergroup', or 'channel'). The bot is never given the group's title, group ID, or member list.

Q3: How can I know which inline result the user actually selected?

By default, Telegram does not notify bots when a user selects a result. To receive telemetry on sent items, enable inline feedback in @BotFather via /setinlinefeedback (select 100% or 10%). Telegram will then send chosen_inline_result webhook updates whenever a user sends an item into chat.

Q4: How does pagination work in inline queries?

Use the next_offset parameter inside answerInlineQuery. When the user scrolls to the bottom of the 50 results in their Telegram popup, the client automatically dispatches another inline_query with the offset field set to your previous next_offset value, creating seamless infinite scrolling.

Q5: When should I set is_personal=true vs is_personal=false?

Set is_personal=false (default) for generic searches like GIFs, news headlines, and documentation. This enables global caching on Telegram's Edge servers. Set is_personal=true only when the result contains private user-specific data (such as wallet balances or recent transactions), ensuring one user's private data is never cached or rendered to another user.

MODULE 08 • MILESTONE ACHIEVED Next Architecture Milestone: Step 088

Ready for Step 088: Telegram Mini Apps (TMA) Architecture: WebApp SDK & Viewports

While inline bots provide instant card results, modern Web3 applications demand immersive full-stack web experiences. In Step 088, we enter the revolutionary world of Telegram Mini Apps (TMA), exploring the official Telegram WebApp SDK (window.Telegram.WebApp), viewport sizing, theme event synchronization, and native haptic feedback.

Continue to Step 088 (Telegram Mini Apps Architecture) →
← Prev: [Telegram 186] BotFather Deep Dive: Creating Bots & API Tokens Next: [Telegram 188] Telegram Mini Apps (TMA) Architecture: WebApp SDK & Viewports →
admin_panel_settings ADMIN Guide #18460 Actions
Enlarged Preview
Click anywhere outside or press ESC to close viewer
smart_display Telegram Video Short
1080p HD
Official Source: @TelegramTips Post #44 Press ESC or click outside to close