在电报机器人中清除 "pending_update_count"

Clear "pending_update_count" in Telegram Bot

我想清除我的机器人中的所有 pending_update_count

以下命令的输出:

https://api.telegram.org/botxxxxxxxxxxxxxxxx/getWebhookInfo

显然我用 xxx

替换了真正的 API 令牌

这是:

{
 "ok":true,"result":
    {
     "url":"",
     "has_custom_certificate":false,
     "pending_update_count":5154
    }
}

如您所见,到目前为止,我有 5154 个未读更新!! (我很确定这个待定更新是错误的!因为没有人使用这个 Bot!它只是一个测试 Bot)

顺便说一句,这个pending_update_count的数字增长得真快! 现在我正在写这个 post 数字增加了 51 并达到了 5205 !

我只想清除这个待处理的更新。 我很确定这个机器人已经陷入了无限循环!

有什么方法可以摆脱它吗?

P.S:

我还清除了 webhook url。但是什么都没有改变!

更新:

getWebhookInfo 的输出是这样的:

{
   "ok":true,
   "result":{
      "url":"https://somewhere.com/telegram/webhook",
      "has_custom_certificate":false,
      "pending_update_count":23,
      "last_error_date":1482910173,
      "last_error_message":"Wrong response from the webhook: 500 Internal Server Error",
      "max_connections":40
   }
}

为什么我得到 Wrong response from the webhook: 500 Internal Server Error

我想你有两个选择:

  1. 设置什么都不做的 webhook,只对电报的服务器说 200 OK。 Telegram 将向此 url 发送所有更新,并且队列将被清除。
  2. 禁用 webhook 并在使用 getUpdates 方法获取更新后,再次打开 webhook

更新:

您这边的 webhook 有问题。您可以尝试在 URL 上模拟电报的 POST 查询。 它可以是这样的:

{"message_id":1,"from":{"id":1,"first_name":"FirstName","last_name":"LastName","username":"username"},"chat":{"id":1,"first_name":"FirstName","last_name":"LastName","username":"username","type":"private"},"date":1460957457,"text":"test message"}

例如,您可以使用 PostMan 将此文本作为 POST 查询正文发送,然后尝试调试您的后端。

只需在钩子方法的末尾添加 return 1;

更新:

发生这种情况的原因通常是数据库查询延迟。

我是这样解决的

POST tg.api/bottoken/setWebhook to emtpy "url"
POST tg.api/bottoken/getUpdates
POST tg.api/bottoken/getUpdates with "offset" last update_id appeared before

重复几次

POST tg.api/bottoken/getWebhookInfo

看看是不是都走了

POST tg.api/bottoken/setWebhook with filled "url"

我通过更改文件访问权限文件解决它 - 将权限文件设置为 755

和 php.ini 文件中的第二次增加内存限制

对于在 2020 年及以后查看此内容的任何人,Telegram API 现在支持通过 setWebhookdeleteWebhook 中的 drop_pending_updates 参数清除未决消息,根据 API documentation.

一种快速而简单的方法是在此处获取临时网络挂钩:https://webhook.site/ 和 将你的 webhook 设置为那个(它每次都会用 HTTP/200 代码回答,将你的待处理消息重置为零)

在用户编辑现有消息后,我的远程机器人遇到了同样的问题。我的机器人不断收到 editedMessage 的更新,但 update.hasMessage() 是空的。结果更新数量激增,我的机器人堆栈。

我通过添加对消息丢失时用例的处理来解决这个问题 - 发送 200 代码:

    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {

        update = MAPPER.readValue(event.getBody(), Update.class);

        if (!update.hasMessage()) {
            return new APIGatewayProxyResponseEvent()
                    .withStatusCode(200) // -> !!!!!! return code 200
                    .withBody("message is missing")
                    .withIsBase64Encoded(false);
        }
        ... ... ...