0

如何让我的 Telegram Bot 与用户交互?例如:

用户:/买

博特:你想买什么?

用户:冰淇淋

Bot:你已经成功购买了冰淇淋!

那么我该怎么做呢?

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

1 回答 1

1

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

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) [...]
于 2017-05-07T16:44:32.767 回答