How to obtain Telegram chat_id for a specific user?

做~自己de王妃 提交于 2019-11-27 11:46:12

The message updates you receive via getUpdates or your webhook will contain the chat ID for the specific message. It will be contained under the message.chat.id key.

This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis.

I believe their documentation suggests something similar here, https://core.telegram.org/bots#deep-linking-example. You can use deep-linking to initiate a conversation without requiring the user to type a message first.

I created a bot to get User or GroupChat id, just send the /my_id to telegram bot @get_id_bot.

It does not only work for user chat ID, but also for group chat ID.

To get group chat ID, first you have to add the bot to the group, then send /my_id in the group.

Here's the link to the bot.

You can just share the contact with your bot and, via /getUpdates, you get the "contact" object

Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:

#!/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"; 

The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.

You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:

$ sudo cpan WWW::Telegram::BotAPI 

Hope this helps

There is a bot that echoes your chat id upon starting a conversation.

Just search for @chat_id_echo_bot and tap /start. It will echo your chat id.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!