如何确保 chat_id 存在?

How to ensure that chat_id exists?

我编写了一段代码,用于向 Telegram 机器人发送消息。为此,我使用了通过 getUpdates method.

检索到的最后一次对话的 chat_id
id = requests.get(f"https://api.telegram.org/bot{token}/getUpdates").json()['result'][-1]['message']['chat']['id']

我的理解是,如果有人通过 /start 与机器人开始对话,就会存在对话。

如何从我的代码发起对话以确保 chat_id 可用?(= 我可以查询转换)。

我也确信对话(如果存在)不会无限期保留(这是请求更新可能产生空结果的另一个原因)

My understanding is that the a conversation exists if someone started one with the bot via /start.

是的,对话总是initiated by a user:

Bots can't initiate conversations with users. A user must either add them to a group or send them a message first. People can use telegram.me/ links or username search to find your bot.

请注意,/start 不是此处唯一的选项。

如果您尝试向未开始与机器人对话的用户发送消息,您将收到如下信息:{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}


How can I initiate, from my code, a conversation to make sure a chat_id is available? (= that there is a conversion I can query).

通常情况下,您不必为此担心。 Bot 不会用 getUpdates 查询特定用户 actions/requests,它会查询所有用户的所有交互,然后根据您提供的内部逻辑决定要做什么。

每次收到 getUpdates 中特定用户的 Update 请求时,您可能希望将有关用户 and/or 的请求的信息存储在数据库中。

基于此,bot 可以决定向他发送例如一条消息。


I am also sure that the conversations, should they exist, are not kept indefinitely (this is another reason why requesting an update can yield empty results)

是的,docs clearly state那个

Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.

Telegram 服务器上的 Update 是生命周期较短的实体。

如果您没有保存有关现有用户的信息,或者丢失了数据库,无法从电报服务器检索该数据。


P.S.: 作为旁注,我建议使用长轮询,如 Telegram Bot API is designed to be used with long polling 如果您使用 getUpdates。最重要的是getUpdates方法的timeout请求参数:

(timeout is) Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.

如问题所述,您正在使用短轮询。