Search code examples
phplaraveltelegram-botphp-telegram-bottelegram-webhook

PHP - Telegram Bot interactive query


I'm trying to query some data from my database. there is three option for searching data from database

  1. User id
  2. Phone no.
  3. E-mail

I've created an inline keyboard by choosing a search option from the above list Screenshot of bot chat

I'm looking for a solution where if I choose user_id then the bot will ask me to insert user_id. And will accept the only user_id as input. otherwise, it will return with an error message.

if I choose email from the inline keyboard at that time bot will accept only email that time. other bot commands will not be accepted until any error or success is returned from the bot.

I'm using Laravel as my backend.


Solution

  • You should have a column called state for each user_id. And when you receive any message you should check the state before responding.

    So, This is pseudo-code:

    $Bot = new TelegramBot(getenv('BOT_TOKEN'));
    
    function MessageHandler($message)
    {
        $state = DB::table('users')->row(['user_id' => $message->from->id])->column('state');
    
        if ($state === false)
        {
            # Create new row for this user..
        }
    
        switch ($state)
        {
            case 'SEARCHING_BY_ID':
                # Check if message is number
                break;
    
            case 'SEARCHING_BY_PHONE':
                # Check if message is phone number
                break;
    
    
            case 'SEARCHING_BY_MAIL':
                # Check if message is E-mail
                break;
    
            default:
                # Now you should process by any command
                break;
        }
    }
    
    $Bot->OnMessage(MessageHandler);