怎么可以等待我的Telegram Bot收到传入消息?

时间:2017-05-07 16:16:20

标签: php telegram-bot php-telegram-bot

如何让我的Telegram Bot与用户互动? E.g:

  

用户:/ buy

     

Bot:你想买什么?

     

用户:冰淇淋

     

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

那我怎么能这样做呢?

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

1 个答案:

答案 0 :(得分:0)

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

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

你需要以某种方式(saveStorage();)保存$ storage [$ userId]。理想情况下,如果您没有数据库,请使用file_put_contents('storage.json', json_encode($storage));或类似的数据库进行序列化。 SESSIONS不起作用,因为Telegram Servers不发送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) [...]
相关问题