phptelegram-botphp-telegram-bot

How can wait my Telegram Bot for a incoming message?


How can I let interact my Telegram Bot with Users? E.g.:

User: /buy

Bot: What do you want to buy?

User: Icecream

Bot: You have successfully bought Icecream!

So how can I do this?

switch($message) {
[...]
case "/buy":
    sendMessage($chatID, "What do you want to buy?");
    //Here I need your help :D
    break;
}

Solution

  • Assuming you are using a webhook to receive updates, your php script runs again on every update you are receiving. In this case, you will need to save a certain "status" of the user which you are checking everytime your bot receives a message to indicate what you have to do next. An example would be:

    switch($message) {
    case "/buy":
        sendMessage($chatID, "What do you want to buy? Icecream, Water or Sprite?");
        $storage[$chatID]['status'] = 'awaitingProductChoice';
        saveStorage();
        break;
    }
    

    You need to save $storage[$userId] somehow (saveStorage();). Ideally would be to use a database, if you haven't got one, use file_put_contents('storage.json', json_encode($storage)); or something similar to serialize it. SESSIONS won't work, since Telegram Servers do not send cookies.

    Then place some similar code before your switch statement:

    $storage = readStorage(); // load from DB or file_get_contents from file
    if ($storage[$chatID]['status'] === 'awaitingProductChoice') {
        // return " You have successfully bought Icecream!"
        $storage[$chatID]['product choice'] = $message['text'];
    } else if ($storage[$chatID]['status'] === 'other stuff') {
        // other step
    }
    else switch($message) [...]