W
W
Waldemar2021-09-13 18:07:05
PHP
Waldemar, 2021-09-13 18:07:05

Why doesn't inline_keyboard work in telegram bot?

Ultra has already killed a lot of time, and this way and that, but the bot does not want to respond to pressing inline_keyboard, more precisely, to callback_data commands from the inline keyboard. I even found a very short script from another person on the Internet, as I understood it was fully working for a person, I download it for myself - it still doesn’t work ..
What have I already done? I checked / rechecked a lot of things, whether chat_id is indicated correctly, etc., etc. - everything is clearly and correctly indicated! I logged all the answers from telegram to a file, in my opinion everything is sent to telegram correctly, the telegram even gives an answer that inline_keyboard was pressed, in response it sends the command that was specified in callback_data, but the script does not stupidly process it and as a result the command does not work =(
What have I just not redone already .. I don’t understand what’s the matter. I dug into Google, I read somewhere that you need to enable inline_keyboard processing in botfather (which seems to be some kind of stupidity, how many times I used another ready-made tg bot there were a lot of inline keyboards and I never turned to BotFather to switch something there), although I still tried to switch - 0 sense.

I think the problem is probably, as usual, on the surface, in some little thing, but I can’t see / understand what exactly.
Perhaps it would be correct to install some kind of program in order to more conveniently / more accurately monitor which requests go / come to telegram, so as not to blindly probe everything, but so far I haven’t figured out such programs, I don’t know how to use them, in the near future probably I'll have to figure them out..
I thought to make a simple boat, for a simple task, literally all the code is written there in half an hour / hour .... but I want to do it on inline buttons, but they don’t want to work in any way, as a result, I’ve been suffering for 2 days already ... =(

The bot is hooked to the domain, and the files are on the hosting.Now I will attach the script that I found on the Internet, and the guy wrote that it definitely worked for him, but it doesn’t even work
for me.While I continue to rummage on the Internet and try different options, I decided to leave here is a question so as not to waste time in vain, maybe someone has already encountered a similar one and can help save time .. Thanks in advance to anyone who can help, at least just tell you what options you can still try.The

code for an example that does not work ->

bot.php

<?php
    $access_token = 'xxx';
    $api = 'https://api.telegram.org/bot' . $access_token;
    $output = json_decode(file_get_contents('php://input'), TRUE);

    #логирование ответа от telegram
    file_put_contents('log.txt', '$output: '.print_r($output, 1)."\n", FILE_APPEND);

    $chat_id = $output['message']['chat']['id'];
    $message = $output['message']['text'];
    $callback_query = $output['callback_query'];
    $data = $callback_query['data'];
    $message_id = ['callback_query']['message']['message_id'];
    $chat_id_in = $callback_query['message']['chat']['id'];

    switch($message) {
        case '/test':
        $inline_button1 = ["text" => "Google url", "url" => "http://google.com"];
        $inline_button2 = ["text" => "work plz", "callback_data" => '/plz'];
        $inline_keyboard = ;
        $keyboard = ["inline_keyboard" => $inline_keyboard];
        $replyMarkup = json_encode($keyboard); 
        sendMessage($chat_id, "ok", $replyMarkup);
        break;
    }

    switch($data){
        case '/plz':
        sendMessage($chat_id_in, "plz");
        break;
    }

    function sendMessage($chat_id, $message, $replyMarkup) {
        file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' . $replyMarkup);
    }


Response log from telegram ->
log.txt

//Когда пишу команду /test

$output: Array
(
    [update_id] => 801037387
    [message] => Array
        (
            [message_id] => 698
            [from] => Array
                (
                    [id] => 1358111111
                    [is_bot] => 
                    [first_name] => first_name
                    [username] => username
                    [language_code] => ru
                )

            [chat] => Array
                (
                    [id] => 1358111111
                    [first_name] => first_name
                    [username] => username
                    [type] => private
                )

            [date] => 1631124344
            [text] => /test
            [entities] => Array
                (
                    [0] => Array
                        (
                            [offset] => 0
                            [length] => 5
                            [type] => bot_command
                        )

                )

        )

)

//Когда нажимаю inline кнопку

$output: Array
(
    [update_id] => 801037387
    [callback_query] => Array
        (
            [id] => 5831111111111111111
            [from] => Array
                (
                    [id] => 1358111111
                    [is_bot] => 
                    [first_name] => first_name
                    [username] => username
                    [language_code] => ru
                )

            [message] => Array
                (
                    [message_id] => 699
                    [from] => Array
                        (
                            [id] => 1981111111
                            [is_bot] => 1
                            [first_name] => BOT_NAME
                            [username] => bot_username_bot
                        )

                    [chat] => Array
                        (
                            [id] => 1358111111
                            [first_name] => first_name
                            [username] => username
                            [type] => private
                        )

                    [date] => 1631124344
                    [text] => ok
                    [reply_markup] => Array
                        (
                            [inline_keyboard] => Array
                                (
                                    [0] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [text] => Google url
                                                    [url] => http://google.com/
                                                )

                                            [1] => Array
                                                (
                                                    [text] => work plz
                                                    [callback_data] => /plz
                                                )

                                        )

                                )

                        )

                )

            [chat_instance] => 3145335060324141256
            [data] => /plz
        )

)



PS Even here I manually try to send a request to the bot through the browser ->
https://api.telegram.org/bot*TOKEN*/sendMessage?chat_id=*CHAT_ID*&text=MY_MESSAGE&reply_markup={"resize_keyboard":true,"inline_keyboard":}

The request is sent, the bot shows me an inline button, I click on it, I receive a log of the telegram sent to me in response to the log.txt file (same as above), that is, it sees that I pressed the button, sends me data from callback_data, in my case it is the /test command, and I have a handler for this command in the script, but for some reason it does not want to work on inline keyboards. =(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya12345, 2021-09-14
@Ilya12345

Here is a piece of working code for you:
Then think for yourself, pay attention to the order in which input values ​​are received.

<?php
set_time_limit (0);
define('TOKEN', '');
class TG {
    public $token = '';
    public function __construct($token) {
        $this->token = $token; 
    }
    public function send($id, $message, $kb) {
        $data = array(
            'chat_id' => $id,
            'text'  => $message,
            'parse_mode' => 'HTML',
            'disable_web_page_preview'=>true,
            'reply_markup' => json_encode(array('inline_keyboard' => $kb))
        );
        $this->request('sendMessage', $data);
    }  
    public function editMessageText($id, $m_id, $m_text, $kb=''){
        $data=array(
             'chat_id' => $id,
             'message_id' => $m_id,
             'parse_mode' => 'HTML',
             'text' => $m_text
        );
        if($kb)
            $data['reply_markup']=json_encode(array('inline_keyboard' => $kb));

        $this->request('editMessageText', $data); 
    }//редактировать сообщение по id
    public function editMessageReplyMarkup($id, $m_id, $kb){
        $data=array(
             'chat_id' => $id,
             'message_id' => $m_id,
            'reply_markup' => json_encode(array('inline_keyboard' => $kb))
        );
        $this->request('editMessageReplyMarkup', $data); 
    }
    public function answerCallbackQuery($cb_id, $message) {
        $data = array(
            'callback_query_id'      => $cb_id,
            'text'     => $message
        );
        $this->request('answerCallbackQuery', $data);
    } 
    public function sendChatAction($id,$action='typing') {
        $data = array(
            'chat_id' => $id,
            'action'     => $action
        );
        $this->request('sendChatAction', $data);
    }
    public  function request($method, $data = array()) {
        $curl = curl_init();
          
        curl_setopt($curl, CURLOPT_URL, 'https://api.telegram.org/bot' . $this->token .  '/' . $method);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); 
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
          
        $out = json_decode(curl_exec($curl), true);
          
        curl_close($curl);
        return $out;
    }
}
$body = file_get_contents('php://input');
$arr = json_decode($body, true); 
$tg = new tg(TOKEN);
$tg_id = $arr['message']['chat']['id'];
$callback_query = $arr['callback_query'];
$data = $callback_query["data"];
$message_text = $arr['message']['text'];
$chatId = $callback_query["message"]["chat"]["id"]; if($chatId!==''){$tg_id = $arr['message']['chat']['id'];}
$rez_kb = array();
switch($data){ 
    case '/downyes':
    sendTelegram('sendMessage', array('chat_id' => $chatId ,'text' => 'получить треклист текстом'));
    exit('ok');
    case '/downno':
    sendTelegram('sendMessage', array('chat_id' => $chatId ,'text' => 'получить трек из поиска'));
    exit('ok');
}   
$tg->sendChatAction($tg_id);
$sms_rev='';
$tg->send($tg_id, $sms_rev, $rez_kb);
function sendTelegram($method, $response){
  $ch = curl_init('https://api.telegram.org/bot' . TOKEN . '/' . $method);  
  curl_setopt($ch, CURLOPT_POST, 1);  
  curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, false);
  $res = curl_exec($ch);
  curl_close($ch);
 
  return $res;
}
if (!empty($data['message']['text'])) {
  $text = $data['message']['text'];

  if (mb_stripos($text, '/download') !== false) {
    $inline = array("text"=>"\xE2\x9C\x85 ДА","callback_data"=>"/downyes");
    $inline1 = array("text"=>"\xF0\x9F\x9A\xAB НЕТ","callback_data"=>"/downno");
    $inline_keyboard = ;
    $keyboard=array("inline_keyboard"=>$inline_keyboard);
   $replyMarkup = json_encode($keyboard); 
sendTelegram(
      'sendMessage', 
      array(
        'chat_id' => $data['message']['chat']['id'],
        'parse_mode' => 'html',
         	'reply_markup' =>$replyMarkup,
        'text' => '&#129302; Вы уверены что хотите скачать плейлист?'
)
);
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question