如何让我的 Telegram 机器人与用户互动?例如:
用户:/购买
机器人:你想买什么?
用户:冰淇淋
机器人:您已成功购买冰淇淋!
那么我该怎么做呢?
switch($message) {
[...]
case "/buy":
sendMessage($chatID, "What do you want to buy?");
//Here I need your help :D
break;
}
假设您使用 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));
或类似的东西来序列化它。会话不起作用,因为 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) [...]
如果您使用 Webhook 来接收更新,请务必注意,您的 php 脚本将在每次收到更新时执行。因此,有必要存储用户的特定“状态”,每次您的机器人收到消息时都会检查该状态。该“状态”将作为需要采取的后续行动的指示器。请允许我提供一个例子以便更好地理解。