如何chat_id
在 Telegram bot API 中获取用户?文档说:
整数 | 消息接收者的唯一标识符 - 用户或 GroupChat id
您通过getUpdates
或您的 webhook 收到的消息更新将包含特定消息的聊天 ID。它将包含在message.chat.id
密钥下。
这似乎是您能够检索聊天 ID 的唯一方法。因此,如果您想在机器人发起对话的地方编写一些内容,您可能必须将与用户相关的聊天 ID 存储在某种 key->value 存储中,例如 MemCache 或 Redis。
我相信他们的文档在这里提出了类似的建议,https://core.telegram.org/bots#deep-linking-example。您可以使用深层链接来发起对话,而无需用户先键入消息。
我创建了一个机器人来获取 User 或 GroupChat id,只需将其发送/my_id
到电报机器人@get_id_bot
。
它不仅适用于用户聊天 ID,也适用于群聊 ID。
要获取群聊 ID,首先您必须将机器人添加到群中,然后/my_id
在群中发送。
这是机器人的链接。
There is a bot that echoes your chat id upon starting a conversation.
Just search for @chatid_echo_bot
and tap /start
. It will echo your chat id.
Another option is @getidsbot
which gives you much more information. This bot also gives information about a forwarded message (from user, to user, chad ids, etc) if you forward the message to the bot.
您可以只与您的机器人共享联系人,然后通过 /getUpdates 获得“联系人”对象
使用 Perl API,您可以通过以下方式获取它:首先您从 Telegram 向机器人发送消息,然后发出 getUpdates 并且聊天 ID 必须存在:
#!/usr/bin/perl
use Data::Dumper;
use WWW::Telegram::BotAPI;
my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
token => $TOKEN
) or die "I can't connect";
my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";
id 应该在chat_id中,但它可能取决于结果,所以我还添加了整个结果的转储。
您可以从https://github.com/Robertof/perl-www-telegram-botapi安装 Perl API 。这取决于您的系统,但我很容易安装在我的 Linux 服务器上运行它:
$ sudo cpan WWW::Telegram::BotAPI
希望这可以帮助
直接从文档中得出:
假设 example.com 网站想通过 Telegram 机器人向其用户发送通知。以下是他们可以为 ID 为 123 的用户启用通知的方法。
memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
/start
。如果密钥存在,则将传递给 webhook 的 chat_id 记录为用户 123 的 telegram_chat_id。从 Memcache 中删除密钥。telegram_chat_id
。如果是,请使用sendMessage
Bot API 中的方法在 Telegram 中向他们发送消息。chat_id 只不过是用户的 id(电报用户帐户 id)。您可以与 开始聊天@get_my_chat_id_bot
。它会将您的 chat_id(您的 user_id)发回给您。常用的id有以下几种:channel id、group id、bot id、chat id(user id)。
每当用户与机器人通信时,它都会发送如下信息:
$response = {
"update_id":640046715,
"message":{
"message_id":1665,
"from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
"chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
"date":1604381276,
"text":"1"
}
}
所以你可以像这样访问聊天:
$update["message"]["chat"]["id"]
假设您使用的是 PHP。