1

I faced the problem with handling of user message inputs in telegram bot.

I'm writing telegram bot on php without any libraries. Bot receives information from telegram via webhook and two switch-case are handling messages and callback_query.

Short version looks like this, it's also without saving to DB:

$output = json_decode(file_get_contents('php://input'), TRUE);
$chat_id = $output['message']['chat']['id'];
$message = $output['message']['text'];
$callback_query = $output['callback_query'];
$data = $callback_query['data'];
$callback_query_id = $callback_query['id'];
$message_id = $output['callback_query']['message']['message_id'];
$message_id_message = $output['message']['message_id'];
$chat_id_in = $callback_query['message']['chat']['id'];]

//Handler of messages
switch($message) {
    case '/start':
        $button1 = ['text'=>'Almaty', 'callback_data'=>"almaty"];
        $button2 = ['text'=>'Astana', 'callback_data'=>"astana"];
        $inline_keyboard = [[$button1],[$button2]];
        $keyboard=["inline_keyboard"=>$inline_keyboard];
        $replyMarkup = json_encode($keyboard);
        sendMessage($chat_id, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", $replyMarkup);

        // Save User to bd if it new, or catch to file.txt
        try
        {
            $first_name = isset($output["message"]['from']['first_name']) ? $output["message"]['from']['first_name'] : null;
            $username = isset($output["message"]['from']['username']) ? $output["message"]['from']['username'] : null;
            $pdo = getPDO();
            $stmt = $pdo->prepare("
                    INSERT INTO 
                      users (chat_id,first_name,username)
                    VALUES (:chat_id, :first_name, :username)
                ");
        } catch (Exception $e) {
            file_put_contents('file.txt', $e->getMessage()."\n", FILE_APPEND);
        }
        break;
}
    
//handler of callback_query
switch($data){
    case 'almaty':
        deleteMessage($chat_id_in, $message_id);
        deleteMessage($chat_id_in, $message_id-1);

        $inline_keyboard = [
            [
                ['text'=>'aujezovskij', 'callback_data'=>"aujezovskij"]
            ],
            [
                ['text'=>'alatauskij', 'callback_data'=>"alatauskij"]
            ],
            [
                ['text'=>'almalinskij', 'callback_data'=>"almalinskij"]
            ],
            [
                ['text'=>'bostandykskij', 'callback_data'=>"bostandykskij"]
            ],
            [
                ['text'=>'zhetysuskij', 'callback_data'=>"zhetysuskij"]
            ],
            [
                ['text'=>'medeuskij', 'callback_data'=>"medeuskij"]
            ],
            [
                ['text'=>'nauryzbajskiy', 'callback_data'=>"nauryzbajskiy"]
            ],
            [
                ['text'=>'turksibskij', 'callback_data'=>"turksibskij"]
            ],
            [
                ['text'=>'Go back', 'callback_data'=>"goback"]
            ]
        ];
        $keyboard=["inline_keyboard"=>$inline_keyboard];
        $replyMarkup = json_encode($keyboard);
        sendMessage($chat_id_in, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", $replyMarkup);
        break;

    case 'astana':
        deleteMessage($chat_id_in, $message_id);
        deleteMessage($chat_id_in, $message_id-1);

        $inline_keyboard = [
            [
                ['text'=>'esilskij', 'callback_data'=>"esilskij"]
            ],
            [
                ['text'=>'almatinskij', 'callback_data'=>"almatinskij"]
            ],
            [
                ['text'=>'saryarkinskij', 'callback_data'=>"saryarkinskij"]
            ],
            [
                ['text'=>'r-n-bajkonur', 'callback_data'=>"r-n-bajkonur"]
            ],
            [
                ['text'=>'Go back', 'callback_data'=>"goback"]
            ]
        ];
        $keyboard=["inline_keyboard"=>$inline_keyboard];
        $replyMarkup = json_encode($keyboard);
        sendMessage($chat_id_in, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", $replyMarkup);
        break;

    case "goback":
        deleteMessage($chat_id_in, $message_id);
        $button1 = ['text'=>'Almaty', 'callback_data'=>"almaty"];
        $button2 = ['text'=>'Astana', 'callback_data'=>"astana"];
        $inline_keyboard = [[$button1],[$button2]];
        $keyboard=["inline_keyboard"=>$inline_keyboard];
        $replyMarkup = json_encode($keyboard);
        sendMessage($chat_id_in, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", $replyMarkup);
        break;

    case "aujezovskij":
    case "alatauskij":
    case "almalinskij":
    case "bostandykskij":
    case "zhetysuskij":
    case "medeuskij":
    case "nauryzbajskiy":
    case "turksibskij":
    case "esilskij":
    case "almatinskij":
    case "saryarkinskij":
    case "r-n-bajkonur":
        deleteMessage($chat_id_in, $message_id);

        $inline_keyboard = [
            [
                ['text'=>'flats', 'callback_data'=>"kvartiry"]
            ],
    

        [
                    ['text'=>'rooms', 'callback_data'=>"komnaty"]
                ],
                [
                    ['text'=>'all', 'callback_data'=>"all"]
                ],
                [
                    ['text'=>'Go back', 'callback_data'=>"$city"]
                ]
            ];
            $keyboard=["inline_keyboard"=>$inline_keyboard];
            $replyMarkup = json_encode($keyboard);
            sendMessage($chat_id_in, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", $replyMarkup);
            break;
}

All next steps I was using only callback_query with inline buttons. But on few next steps I need to send Message with question "Write price range" and two buttons Go back and "Doesn't matter": picture of message to user "Write price range"

The main problem is that there will be same questions where users should write integer range and I need to know to which DB column I should save this answer.

The most recent attempt was to make a table with queues that would be created at a certain step and signal where to save the answer. For this I added switch default where I was Selecting fields from this queue table and through IF statement I was checking from which step user came. Everything worked except those buttons Go back and "Doesn't matter", because in the presence of row in the queue table the script was stucked in the switch-default which was handling messages, and can't go to switch-case which was handling callback query Short example of the code:

// Message handler
switch($message) {
    case '/start':
        $button1 = ['text'=>'Алматы', 'callback_data'=>"almaty"];
        $button2 = ['text'=>'Астана', 'callback_data'=>"astana"];
        $inline_keyboard = [[$button1],[$button2]];
        $keyboard=["inline_keyboard"=>$inline_keyboard];
        $replyMarkup = json_encode($keyboard);
        sendMessage($chat_id, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", $replyMarkup);

        // Save User to bd if it new, or catch to file.txt
        try
        {
            $first_name = isset($output["message"]['from']['first_name']) ? $output["message"]['from']['first_name'] : null;
            $username = isset($output["message"]['from']['username']) ? $output["message"]['from']['username'] : null;
            $pdo = getPDO();
            $stmt = $pdo->prepare("
                    INSERT INTO 
                      users (chat_id,first_name,username)
                    VALUES (:chat_id, :first_name, :username)
                ");
        } catch (Exception $e) {
            file_put_contents('file.txt', $e->getMessage()."\n", FILE_APPEND);
        }
        break;

    default:
        $pdo = getPDO();
        $stmt = $pdo->prepare("
                        SELECT suspense, suspense_from from user_suspense
                        WHERE chat_id = 201502307
                    ");

        $stmt->execute();
        $status = $stmt->fetch();
        if ($status['suspense_from'] == "price" AND $status['suspense'] == 'wait'){
            try
            {
                $pdo = getPDO();
                $stmt = $pdo->prepare("
                        UPDATE users
                        SET price=:price
                        WHERE chat_id = $chat_id
                    ");

                $stmt->execute([
                    ':price' => $message
                ]);

                $stmt = $pdo->prepare("
                        UPDATE user_suspense
                        SET suspense = :suspense
                        WHERE chat_id = $chat_id
                    ");

                $stmt->execute([
                    ':suspense' => 'proceed'
                ]);
            } catch (Exception $e) {
                file_put_contents('file.txt', $e->getMessage() . "\n", FILE_APPEND);
            }
                $pdo = getPDO();
                $stmt = $pdo->prepare("
                            SELECT suspense from user_suspense
                            WHERE chat_id = $chat_id
                        ");

                $stmt->execute();
                $status = $stmt->fetch();
            deleteMessage($chat_id, $status['chat_id_in']);
            deleteMessage($chat_id, $message_id_message);
            sendMessageNomarkup($chat_id, 'fffff');
        }
        break;
}

//Callback Query handler
switch($data){
case "price":
            try
            {
                $pdo = getPDO();
                $stmt = $pdo->prepare("
                    INSERT INTO 
                      user_suspense (chat_id)
                    VALUES (:chat_id)
                ");

                $stmt->execute([
                    ':chat_id'=> $chat_id_in
                ]);
            } catch (Exception $e) {
                file_put_contents('file.txt', $e->getMessage()."\n", FILE_APPEND);
            }

            try
            {
                $pdo = getPDO();
                $stmt = $pdo->prepare("
                        UPDATE user_suspense
                        SET suspense=:suspense, suspense_from=:suspense_from, chat_id_in=:chat_id_in
                        WHERE chat_id = $chat_id_in
                    ");

                $stmt->execute([
                    ':suspense' => 'wait',
                    ':suspense_from' => $data,
                    ':chat_id_in' => $message_id+1
                ]);
            } catch (Exception $e) {
                file_put_contents('file.txt', $e->getMessage() . "\n", FILE_APPEND);
            }
            deleteMessage($chat_id_in, $message_id);
            $inline_keyboard = [
                [
                    ['text'=>"Doesn't matter", 'callback_data'=>"commission"]
                ],
                [
                    ['text'=>'Go back', 'callback_data'=>"remont"]
                ]
            ];
            $keyboard=["inline_keyboard"=>$inline_keyboard];
            $replyMarkup = json_encode($keyboard);
            sendMessage($chat_id_in, "Write price range \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n Example: 100-200", $replyMarkup);
        break;
}

Right now I don't know how to solve this problem, without global changes in code. I wanted to add full code but it's limited with 30000 characters, so I hope I showed and described the problem clearly. Thank You in advance for help.

Akim
  • 41
  • 5

0 Answers0