How to Create an Inline Keyboard in a Telegram Bot Using PHP

Learn how to create Telegram bot inline keyboards in PHP with callback buttons, dynamic menus, and message updates. Full example code included.

How to Create an Inline Keyboard in a Telegram Bot Using PHP

Telegram bots have revolutionized how we interact with messaging platforms. From delivering news and managing tasks to building mini-apps within chats, bots can handle just about anything. Among the most useful features in the Telegram Bot API is the inline keyboard—a dynamic set of buttons that appear directly beneath a message and let users take actions without typing a word.

Imagine sending a message with “Yes” or “No” buttons, or creating a navigation menu for your bot. With inline keyboards, you can design intuitive, user-friendly interfaces that make interacting with your bot fast and simple. Whether you're developing a voting system, a quiz, a product browser, or a multi-step menu, inline keyboards will be a core feature of your bot’s functionality.

In this in-depth tutorial, we’ll explore how to create an inline keyboard using pure PHP—no frameworks required. You’ll learn how to use Telegram’s sendMessage method to attach inline buttons, how to handle button clicks with callback_query, and how to update or remove the keyboard after interaction. We’ll also touch on using a PHP SDK for those who prefer structured development.

Why Use Inline Keyboards?

  • They allow for quick and clean user interaction without requiring input.
  • Perfect for creating multi-level menus, confirmation dialogs, or data filtering.
  • Can be updated or removed dynamically, giving you full control over the chat flow.
  • Better UI/UX for mobile users than sending typed commands.

Many developers confuse reply keyboards with inline keyboards. While both are used to create buttons, inline keyboards are more powerful. They appear directly below a message and can trigger callbacks handled by your server. In contrast, reply keyboards simulate user input and do not offer callback data or dynamic control.

What You Need to Get Started

  • A Telegram account and a bot token from @BotFather
  • Basic knowledge of PHP and how to send HTTP requests
  • A live server or localhost with HTTPS support (for webhooks)
  • Optional: a PHP Telegram Bot SDK for cleaner structure and faster development

This tutorial is beginner-friendly but also packed with tips for more experienced developers. Even if you’ve never created a Telegram bot before, we’ll guide you through setting up everything from scratch.


What You'll Learn

  • How to structure an inline keyboard in JSON and send it via PHP
  • How to handle user interaction using callback queries
  • How to dynamically edit or remove inline keyboards after a button click
  • How to use a PHP SDK for Telegram bot development (optional)

How to Send an Inline Keyboard Using PHP

Below is a simple PHP example that sends a message with an inline keyboard to your Telegram bot user. Make sure you've created your bot with @BotFather and replaced the token with your own.

<?php
$token = "YOUR_BOT_TOKEN";
$chat_id = "USER_CHAT_ID"; // Replace with actual chat ID

$keyboard = array(
  "inline_keyboard" => array(
    array(
      array("text" => "👍 Like", "callback_data" => "like"),
      array("text" => "👎 Dislike", "callback_data" => "dislike")
    ),
    array(
      array("text" => "Visit Website", "url" => "https://example.com")
    )
  )
);

$data = array(
  'chat_id' => $chat_id,
  'text' => "What do you think about this tutorial?",
  'reply_markup' => json_encode($keyboard)
);

file_get_contents("https://api.telegram.org/bot{$token}/sendMessage?" . http_build_query($data));
?>

This will send a message with two callback buttons (👍 Like and 👎 Dislike) and one external link button. The callback buttons can be captured in your webhook to handle user interaction in real time.


How to Handle Inline Keyboard Callbacks in PHP

When a user clicks a button with callback_data, Telegram sends a callback_query update to your webhook. You can capture this to perform actions or show a response.

<?php
// Read incoming JSON from Telegram
$content = file_get_contents("php://input");
$update = json_decode($content, true);

// Replace with your bot token
$token = "YOUR_BOT_TOKEN";

// Check if it's a callback query
if (isset($update["callback_query"])) {
    $callback_id = $update["callback_query"]["id"];
    $chat_id = $update["callback_query"]["message"]["chat"]["id"];
    $data = $update["callback_query"]["data"]; // like or dislike

    // Respond to callback to remove "loading..." animation
    $response = [
        'callback_query_id' => $callback_id,
        'text' => "You clicked: " . strtoupper($data),
        'show_alert' => false
    ];

    file_get_contents("https://api.telegram.org/bot{$token}/answerCallbackQuery?" . http_build_query($response));

    // Optionally send a reply message
    $reply = [
        'chat_id' => $chat_id,
        'text' => "Thanks for your feedback: " . ucfirst($data)
    ];

    file_get_contents("https://api.telegram.org/bot{$token}/sendMessage?" . http_build_query($reply));
}
?>

This webhook code listens for button clicks and responds both through the inline callback and as a follow-up message.


How to Remove Inline Keyboard After a Button is Clicked

Once a user clicks a button, you may want to remove the inline keyboard to avoid duplicate responses or to show a cleaner UI. Here's how you can do that using editMessageReplyMarkup.

<?php
// This example assumes you are inside the same webhook handling code

$message_id = $update["callback_query"]["message"]["message_id"];
$chat_id = $update["callback_query"]["message"]["chat"]["id"];

$remove_keyboard = [
    'chat_id' => $chat_id,
    'message_id' => $message_id,
    'reply_markup' => json_encode(['inline_keyboard' => []]) // empty array removes keyboard
];

file_get_contents("https://api.telegram.org/bot{$token}/editMessageReplyMarkup?" . http_build_query($remove_keyboard));
?>

This API call tells Telegram to update the message and remove its inline keyboard. You can also replace it with a new one if needed, simply by modifying the reply_markup content.


Conclusion

Congratulations! You've now learned how to create and manage inline keyboards in a Telegram bot using pure PHP. From sending buttons with callback_data to capturing user interactions and removing keyboards dynamically, you're now equipped to build interactive, user-friendly bots.

Inline keyboards are perfect for creating quick polls, navigation menus, confirmation prompts, or anything that requires one-tap interaction. They're far more flexible than reply keyboards and give you precise control over the chat flow.

To take things even further, consider exploring the PHP Telegram Bot SDK which can help organize your code and scale your bot more efficiently with command handlers, logging, and middleware support.

If you found this tutorial helpful, consider bookmarking this blog and sharing it with other developers or Telegram enthusiasts. More PHP-based Telegram bot guides are coming soon!


Did you build something cool with this tutorial? Share your bot link in the comments below or contact us for feature highlights!

Post a Comment