How to Make a Telegram Bot Custom Keyboard Send Specific Codes?

I’m trying to set up a custom keyboard for my Telegram bot. Right now when a user taps a button it just sends the button text to the bot. But I want each button to send a different code instead.

For example I’ve got buttons that say ‘Hello’ and ‘Hi’. But I want ‘Hello’ to send ‘100’ and ‘Hi’ to send ‘200’ when pressed.

Is there a way to do this with the Telegram Bot API? I couldn’t find any info on adding custom data or tags to keyboard buttons.

Here’s what my current keyboard setup looks like:

$buttons = ['Hello', 'Hi'];
$keyboard = [
  'keyboard' => [$buttons],
  'one_time_keyboard' => true,
  'resize_keyboard' => true
];

$params = [
  'chat_id' => $chatId,
  'text' => 'Pick an option',
  'reply_markup' => $keyboard
];

sendApiRequest('sendMessage', $params);

Any ideas on how to make the buttons send codes instead of their labels? Thanks!

The solution lies in utilizing inline keyboards instead of regular ones. With inline keyboards, you can assign specific callback data to each button, allowing you to send custom codes rather than just the button text.

To implement this, you’ll need to modify your keyboard structure to use ‘inline_keyboard’ instead of ‘keyboard’. Each button should have a ‘text’ field for display and a ‘callback_data’ field for the code you want to send.

After implementing the inline keyboard, ensure your bot is set up to handle callback queries. This involves creating a separate function to process the incoming callback data and respond accordingly.

Remember to thoroughly test your implementation to ensure it functions as expected across different devices and Telegram clients.

I’ve faced a similar challenge with Telegram bots before. To send specific codes instead of button text, you’ll need to use inline keyboards rather than regular keyboards.

With inline keyboards, you can set a callback_data parameter for each button. This allows you to specify the exact data sent when a button is pressed.

Here’s how you could modify your code:

$keyboard = [
  'inline_keyboard' => [
    [
      ['text' => 'Hello', 'callback_data' => '100'],
      ['text' => 'Hi', 'callback_data' => '200']
    ]
  ]
];

$params = [
  'chat_id' => $chatId,
  'text' => 'Pick an option',
  'reply_markup' => json_encode($keyboard)
];

sendApiRequest('sendMessage', $params);

You’ll then need to handle the callback query in your bot code to process the received data. This approach gives you much more flexibility in terms of what data is sent when buttons are pressed.

yo, u can use inline keyboards for that. they let u set custom callback data for each button. so instead of sending the button text, it’ll send whatever code u want. just swap ur regular keyboard for an inline one and add the callback_data parameter. works like a charm!