使用 Telegram 机器人检索所有聊天 ID

Retrieve all chat ids using Telegram bot

主要问题是如何获取与机器人进行过的所有对话的聊天 ID?

假设在机器人执行期间与用户 A 进行对话。

现在我停止机器人进程并重新启动它。

如何获取与用户 A 过去聊天的聊天 ID?

我知道当用户向您发送消息时您会获得聊天 ID,并且您使用该 ID 进行回复,但是如果用户 A 在当前执行期间不再向 bot 发送消息怎么办?如何获取过去的对话 ID?

是唯一一种存储 ID 并在第二次执行开始时检索它们的选项吗?

更新:

看起来当前的解决方案是将聊天 ID 存储在安全的地方,正如@Tick Tock 所回答的那样。

我不清楚你的问题,但根据你的问题我了解到我写了一些东西给你希望对你有所帮助。您可以检索 chat_id 并使用它向 chat 发送内容。我会给出一个示例代码,但在让我解释一下之前。

In Telegram Bot API there is two definitions: chat_id and from_id.

1-When we are in private chat with some one chat_id and from_id are equal.

2-When our bot is a group member, then chat_id is id of that group and is different from that person id(from_id) may be send something to group(and maybe our bot receive it too-when privacy_mode is off)

我假设你的机器人在私人聊天中: 当用户向您的机器人发送任何内容时,Telegram 将该消息发送给您的 BOT(调用您的脚本),此示例代码向该用户发送“Hello chat_id”。(在 PHP)

define('BOT_TOKEN','12345:abcde');//replace with your bot token
$command_prefix_url='https://api.telegram.org/bot' . BOT_TOKEN ;

$update = json_decode(file_get_contents('php://input')); //retrieves data sent by telegram

$chat_id=$update->message->chat->id; //retrives `chat_id`

$rep = json_decode(file_get_contents($command_prefix_url . '/SendMessage?chat_id=' .
    $chat_id    . '&text=' . urldecode('Hello '.(string)$chat_id))); //send something to that `chat_id` (sender)

更新:(由于版本问题)

首先,chat_id 对那个用户来说是唯一的并且永远是永久的(在私人聊天中) 即使您的机器人的用户离开您的机器人并再次加入。 到目前为止,我没有听到或读到任何东西,Telegram 已经提供了一种方法来告诉你的 bot 整个用户 chat_id ,所以了解你的用户的最好方法是保存他们的 chat_id 和数据库中的其他信息(您从用户收到的消息中收集的信息)。

如果您至少将他们的 chat_id 保存在一个简单的数据库中,那么您就有了您的机器人订阅用户的列表。由于 chat_id 是永久性的,您可以向用户发送任何您想要的内容。

而且,据我从你的问题中了解到,如果你没有数据库但用户 A 是你的机器人的订阅用户,据我所知,你应该等到 she/he 向你发送一条消息,然后你抓取 her/him chat_id 并将其添加到你的数据库中。现在您可以随时发送 her/him。