I
I
Igor2018-11-28 17:29:18
PHP
Igor, 2018-11-28 17:29:18

How to make a questionnaire type in Telegram bot?

Good day everyone, like when you click on the button:
Continue the dialogue with the bot so that the bot remembers previous answers

<?php
include('db.php'); // Подключаем БД
include('../vendor/autoload.php'); //Подключаем библиотеку
use Telegram\Bot\Api;

/*
* Собираем данные с балансами
*/

$telegram = new Api('APITOKEN'); //Устанавливаем токен, полученный у BotFather
$result = $telegram -> getWebhookUpdates(); //Передаем в переменную $result полную информацию о сообщении пользователя

$text = $result["message"]["text"]; //Текст сообщения
$chat_id = $result["message"]["chat"]["id"]; //Уникальный идентификатор пользователя
$name = $result["message"]["from"]["username"]; //Юзернейм пользователя
$keyboard = ; //Клавиатура


if($text){
    if ($text == "/start") {
        $reply = "\xF0\x9F\x8E\xAC Добро пожаловать в сервис
            Если вы готовы к заказу нажмите <code>Заказать</code>";

        $reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]);
        $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply, 'reply_markup' => $reply_markup ]);
        
        //Проверяем есть ли такой Chat_ID в БД
            $result = mysqli_query($db, "SELECT * FROM bot_kino_user WHERE chat_id LIKE '%".$chat_id."%'");
                if (mysqli_num_rows($result) == 0) {
                    $userlogin = $name;
                    mysqli_query ($db,"INSERT INTO `bot_kino_user` (`chat_id`, `username`) VALUES ('$chat_id', '$userlogin')");//добавление в базу
            }
            
    }elseif ($text == "\xF0\x9F\x8E\xAC Заказать") {
        $reply = "Для заказа пришлите: 
        1. Город
        2. Возраст
        3. Имя";
        
        $telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply ]);
    }

After pressing the "Order" button
You need to ask - City
Save
Ask - Age
Save
Ask - Name
Save
Next, we show the entered data, and ask if everything is correct, if yes
Then we return to the main menu
I was looking for examples, I did not find this anywhere ..
Help someone with what can please)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey S., 2018-11-29
@m0pfin

Your logic is lame, you yourself write in the example, for example "city: your city"
therefore it should work something like this:
bot:

Для заказа билета пришлите: 
        Пример - Город: Ваш город"

You: Город: Москва
bot:
Ваш город Москва, введите Кинотеатр (пример: Кинотеатр: Ваш Кинотеатр)

You: Кинотеатр: Восход
etc...
and, accordingly, first check the text for compliance with the beginning (to find the City: or Cinema: , and after the colon, then search until the end of the line that you wrote there.
ps such logic is terrible, a normal person will not use it)
If you do it humanly, then the bot should ask ... What city? and remembers the step="city" variable, then with any user's answer, it looks at what is in the step variable, understands what stage it is at, remembers the user's answer, asks a new question and put a new stage in the step variable, for example step="cinema"

A
Andrew, 2018-11-28
@prolisk

Store in variables.
I wrote in python, but the essence is the same - you declare a variable, write the answer into it, then output it at the end and, if necessary, save it to the database.

I
Igor, 2018-11-29
@m0pfin

It may be useful for someone, I developed the following code a little further:
(I can’t save the value of the variable within the script yet, empty variables are written to the database)

elseif ($text == "\xF0\x9F\x8E\xAC Заказать билет") {
        $reply = "Для заказа билета пришлите: 
        Пример - <code>Город: Ваш город</code>";
        
        $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply ]);
        
    }elseif(strstr($text, "Город")){
            
            $_SESSION['city'] = $text;
            $city = $_SESSION['city'];
            
            $reply = "$city - Сохранен! \nПример - <code>Кинотеатр: Ваш кинотеатр</code>"; 
            
            $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply ]);
            
            }elseif(strstr($text,"Кинотеатр")){
            
            $_SESSION['kinoteatr'] = $text;
            $kinoteatr = $_SESSION['kinoteatr'];
            
            $reply = "$kinoteatr - Сохранен! \nПример - <code>Фильм: Название фильма 20:45 (время сеанса)</code>"; 
            
            $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply ]);
            
            }elseif(strstr($text,"Фильм")){
            
            $_SESSION['film'] = $text;
            $film = $_SESSION['film'];
            
            $reply = "$film - Сохранен! \nПример - <code>Ряд: 7 ряд, 5 6 7 8 место</code>"; 
            
            $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply ]);
            }elseif(strstr($text,"Ряд")){

            $_SESSION['count'] = $text;
            $count = $_SESSION['count'];
            
            $reply = "$count,$film,$kinoteatr,$city - Сохранен! \nПример - <code>Сумма заказа: 690 р</code>"; 
            
            $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply ]);
            
            }elseif(strstr($text,"Сумма")){
            
            $_SESSION['cost'] = $text;
            $cost = $_SESSION['cost'];
            
            
            if (empty($city || $kinoteatr || $film || $count || $cost)){
                
                $reply = "$cost - Сохранен! \nВаш заказ сформирован! № Заказа: 2034"; 
                $userlogin = '@'.$name;
                mysqli_query($db, "INSERT INTO `bot_order`(`date`, `chat_id`, `username`, `city`, `kinoteatr`, `film`, `count`, `cost`) VALUES (NOW(),'$chat_id','$userlogin','$city','$kinoteatr','$film','$count','$cost')");
                 $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply ]);
                 $_SESSION  = array();
                 unset($_SESSION); // или $_SESSION = array() для очистки всех данных сессии
                 session_destroy();
                }
                else{
                     $reply = "Какое-то поле вы пропустили :( \nПожалуйста, начните сначала.\n\nДля заказа билета пришлите: \nПример - <code>Город: Ваш город</code>"; 
                     $telegram->sendMessage([ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', 'text' => $reply ]);
                     $_SESSION  = array();
                     unset($_SESSION); // или $_SESSION = array() для очистки всех данных сессии
                     session_destroy();
                }
           
          }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question