【问题标题】:Can't get updated messages from Telegram Bot after script started脚本启动后无法从 Telegram Bot 获取更新的消息
【发布时间】:2016-11-27 08:40:33
【问题描述】:

我正在尝试创建一个脚本来通过 Bot API 操作我的机器人,我在我的服务器上使用简单的 PHP 文件,它有一个设置的 Webhook,以便 Telegram 每次收到消息时都会引用这个文件。但问题是我无法在脚本已经运行时收到新消息,如果我试图获取并分配更新的消息以改变流程中的工作流程,我只会收到旧消息(这是在启动脚本时出现)

$update = file_get_contents('php://input');///get new data
$update = json_decode($update, TRUE);///decode data
$message = $update["message"]["text"];///assign message
switch($message) {////vary actions accordingly to first message
case "number1":
////send smth to user and wait for answer
$update = file_get_contents('php://input'); ////get new data with updated message
$update = json_decode($update, TRUE); ////decode
$message = $update["message"]["text"]; ////assign
switch($message) {////vary further actions accordingly to new message
    case "number2":
    ////further actions
    }
}
...

【问题讨论】:

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


    【解决方案1】:

    您无法从电报中多次获取数据 {('php://input')}。你可能会问为什么?

    让我描述一下会发生什么: 0- 有人想通过 Telegram 客户端向您的机器人发送消息

    1- Telegram 服务器抓取该消息并运行您的预定义 脚本。(设置 webhook 时给 Telegram 的脚本。

    2- 使用('php://input') whole 时只有一次 数据(包括该消息)将提供给您的脚本,现在 Telegram 没有什么可以给你的了。

    3- 您的脚本会在几毫秒内运行并处理该消息,或者 少(在这额外的时间里,没有人可以打字和输入东西 更多在客户端)

    4- 你的脚本完成它的工作。

    5- 下次用户输入内容时(1 秒后或 1 年后!),Telegram 将再次调用您的脚本并提供新消息。

    如您所见,只有第一次调用 ('php://input') 有有用的数据(因为电报有数据给您并调用您的机器人脚本。('php://input') 的其他调用没有给您任何信息。

    作为一种体验: 只在代码顶部获取一次数据(在处理消息之前)然后处理它。如果您需要以前的消息,可以在接收时将它们保存在数据库中。

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 2019-03-09
      • 2022-08-18
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2020-08-02
      相关资源
      最近更新 更多