如何等待我的 Telegram Bot 收到传入消息?

How can wait my Telegram Bot for a incoming message?

如何让我的 Telegram 机器人与用户互动?例如:

User: /buy

Bot: What do you want to buy?

User: Icecream

Bot: You have successfully bought Icecream!

那我该怎么做呢?

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

假设您使用 webhook 接收更新,您的 php 脚本会在您收到的每个更新上再次运行。 在这种情况下,您将需要保存某个 "status" 的用户,每次您的机器人收到一条消息以指示您下一步必须做什么时,您正在检查该用户。 一个例子是:

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

您需要以某种方式保存 $storage[$userId] (saveStorage();)。理想情况下是使用数据库,如果您没有数据库,请使用 file_put_contents('storage.json', json_encode($storage)); 或类似的东西来序列化它。 SESSIONS 将不起作用,因为 Telegram 服务器不发送 cookie。

然后在您的 switch 语句之前放置一些类似的代码:

$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) [...]