Creating a simple PHP-based Telegram bot with quiz functionality and button answers?

Hey everyone! I’m trying to set up a basic Telegram bot using PHP. My goal is to create a quiz feature with multiple-choice answers displayed as buttons. But I’m running into some issues.

Here’s what I’ve got so far:

$token = 'your_bot_token_here';
$api_url = 'https://api.telegram.org/bot' . $token;

$options = [['A', 'B', 'C']];
$keyboard = [
    'keyboard' => $options,
    'one_time_keyboard' => true,
    'resize_keyboard' => true
];

$encoded_keyboard = json_encode($keyboard);
$message = 'Choose an answer:';

$request_url = $api_url . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' . urlencode($encoded_keyboard);

file_get_contents($request_url);

The buttons show up, but they’re not inline like I want. They appear as a regular keyboard instead. Any ideas on how to fix this? Thanks in advance for your help!

I’ve been down this road before, and I can tell you it’s a bit tricky at first. The key is using inline keyboards instead of regular ones. Here’s what worked for me:

Change your $keyboard array to this:

$keyboard = [
    'inline_keyboard' => [
        [
            ['text' => 'A', 'callback_data' => 'quiz_A'],
            ['text' => 'B', 'callback_data' => 'quiz_B'],
            ['text' => 'C', 'callback_data' => 'quiz_C']
        ]
    ]
];

This setup creates those nice inline buttons you’re after. Don’t forget to handle the callback queries in your webhook script to process the user’s choice. It took me a while to get it right, but once you do, it’s smooth sailing. Good luck with your quiz bot!

hey mate, ur close! swap out ‘keyboard’ for ‘inline_keyboard’ in ur $keyboard array. that’ll give ya the inline buttons. also, use ‘callback_data’ instead of just text for each button. lemme know if ya need more help!

I see the issue with your code. You’re using a regular keyboard instead of an inline keyboard, which is why the buttons aren’t appearing as you want. To fix this, you need to modify your keyboard array structure. Here’s how you can adjust it:

$options = [
    [['text' => 'A', 'callback_data' => 'A'],
     ['text' => 'B', 'callback_data' => 'B'],
     ['text' => 'C', 'callback_data' => 'C']]
];
$keyboard = [
    'inline_keyboard' => $options
];

This change will create inline buttons as you desire. Remember to handle the callback queries in your webhook to process user selections. Also, ensure you’re using the sendMessage method correctly with the chat_id parameter. Good luck with your quiz bot!