How to get user_id of a phone number in telegram
Asked Answered
A

4

23

Im creating a bot to send message to multiple contact in Telegram. user can share contact with bot. then i use getUpdates and obtain the phone number. For using the sendMessage Method i need the chat_id. now how to get chat_id of a user with his phone number? Is there any way better than this method to do this?

About answered 16/1, 2017 at 23:5 Comment(2)
A bot can not contact a user that did not write to the bot before. – Ganesa
If someone sends a contact to the bot with a phone number registered in Telegram, there is an additional field user_id in the contact, but as I said before, your bot can't contact that user if the user didn't write to the bot before. – Ganesa
U
32

For internet services to stay alive, they need to fight with any type of spam. As the result, Telegram bots can't start sending messages to users that didn't start using the bot yet!

Only when a user starts using the bot you can see his/hers chat_id and send messages to him.

That being said, if a user (User A) sends you a contact details of another user (Let's call this one, User B), you can see user_id of the user B. However you still can't send any messages directly, unless he/she also started using the bot before.

This behavior allows us to make a workaround and query users by phone number or at least confirm a user's phone number if required.

To do so, first, you need to create contact message. It doesn't matter who sents the message, even the bot can send the message. The idea is to let Telegram fill the user_id of the new contact message. You can read about this object here: Contact Object

The method we need to use is sendContact and it needs a target chat_id, a first_name and a phone_number. Now first_name can be any string and its value is irrelevant to the process. Also, chat_id can be the identification of any user's chat with the bot, even yours. It can also be the name of a group or a channel in which the bot is an administrator with write access, for example, @my_private_bot_channel. In short, anywhere that bot can post a message. So you only need to provide the phone_number.

After sending the message, you will get a server response, along with the Message that your bot just posted. The contact field of this newly created message contains information about the user you just shared his contact, possibly along with his/hers telegram user_id which is the same thing as the user's chat id.

Right afterward you can delete your message with the deleteMessage method.

Following is an example of doing so in plain request/response format, but you should probably use a framework for this:

https://api.telegram.org/{BOT_TOKEN}/sendContact?chat_id=123456789&phone_number=+989123456789&first_name=Some+Random+String

The response to this request is as follow:

{
    "ok": true,
    "result": {
        "message_id": 12345678987654321,
        "from": {
            "id": 987654321,
            "first_name": "The Bot Name",
            "username": "mybot_bot"
        },
        "chat": {
            "id": 123456789,
            "first_name": "Your Chat Party",
            "last_name": "Your Chat Party",
            "type": "private"
        },
        "date": 1484612850,
        "contact": {
            "phone_number": "989123456789",
            "first_name": "Some Random String",
            "user_id": 654789321
        }
    }
}

"user_id": 654789321 is the part that we are interested in. Now you can delete your message.

Ubiety answered 17/1, 2017 at 11:54 Comment(15)
excuse me for poor English grammar. any editor to my sentences is welcome 😊 – Negotiation
Thanks for sharing your method. If I just have a phone number how can I get the user_id of telegram user. Since we need to pass chat_id and first_name of user to make your method work. – Paranoiac
@AlenooshBaghumian no! note that the first_name can be any string. chat_id also can be your own chat_id! – Negotiation
Thanks alot for your reply – Paranoiac
bot111:2222222 should replace with what? – Ronnieronny
@pedram 111:2222222 must be replace with bot token. – Negotiation
@Ubiety You use chat_id inside api url but we have not chat_id !!! I need to get chat_id by mobile number – Tyrocidine
Where chat_id and first_name come from? – Unconditional
first_name can be any name such as john – Negotiation
chat_id must be a chat_id of one of telegram user that start the bot. for example your own chat_id! – Negotiation
Definitely the best answer – Isometry
There is a limitation on the number of user_ids you can get with this method. You can only use "sendContact" 20 times in a day. After that any attempt to use sendContact to any chat_id, will result in "Error:429 Too Many Requests: retry after XXXX". But all other functionalities of the bot remain intact. This is not well documented. – Reena
yes, this stupid limitation apply by Telegram, but unofficial Telegram app (like Mobogram) easily can extract all Iranian chat_id by its 2M users for goverment! – Negotiation
i think telegram change the policy, because about 1 month i can only see my user_id by sendcontact , another phone number return 0 for user_id @Ubiety – Soapy
THIS DOESN'T WORK ANYMORE. – Costanza
P
3

As of May 2021 the accepted answer no longer works, and as best I've been able to tell, Telegram has removed the ability for bots to lookup user_ids based on phone numbers.

It is possible to do this from a user account, instead of a bot, by following the instructions outlined here (essentially by using the importContacts API).

Plastered answered 12/5, 2021 at 13:5 Comment(0)
L
2

There is a problem: you can't send a message from a bot to a user as the conversation initiator even if you have the user_id.

Largescale answered 18/1, 2018 at 17:40 Comment(1)
@AnkitBajpai Yes, it does provide an answer to the question. Saying you can't do it is an answer. If you don't think it's a useful answer you can reflect that opinion with a downvote. – Ozuna
M
1

Knowing the user_id can be usefull for ban and unban. Here the way I do that on my web site:

1) create a small random code and show it to the user, telling him to send it to your bot.

2) read the message using getUpdate. So in PHP:

 $url = "https://api.telegram.org/bot"._TELEGRAM_BOT_TOKEN."/getUpdates?offset=-1";
 $response = file_get_contents($url, false, NULL);
 $jsondata = json_decode($response,true);
 echo "<pre>";
 print_r($jsondata);
 echo "</pre><br>";

You'll get 3 informations:

  $chat_id = $jsondata['result'][0]['message']['chat']['id'];
  $first_name = $jsondata['result'][0]['message']['chat']['first_name'];
  $text = $jsondata['result'][0]['message']['text'];

You just have to compare the text you read with the code you ask the user to send. If it's the same you can read the chat_id and the first_name.

At this point, you have the chat_id which is enough to write to the user in "private". For that, no need to know the user_id.

If you want the user id, you must send another message. Like this one:

   $num = "+55888888888888";
   $url = "https://api.telegram.org/bot"._TELEGRAM_BOT_TOKEN."/sendContact?chat_id=".$chat_id."&phone_number=".$num."&first_name=".$first_name;
  $response = file_get_contents($url, false, NULL);
  $jsondata = json_decode($response,true);
  echo "<pre>";
  print_r($jsondata);
  echo "</pre><br>";

As you can see, to send this second message you need 3 informations:

1) the phone number of the user. You CAN'T get it from Telegram. Meaning you need to ask it from the user.

2) the chat_id. You get it from the previous call

3) the first_name you get it also from the previous call

The user_id is located at:

      $jsondata['result']['contact']['user_id']

Some details:

1) It seems Telegram don't check the first_name. So if you send for the second call, a different first_name than the one you get from the first call, it doesn't matter (but maybe more secure to send the same. In all cases, you get it from first call!)

2) if you perform the second call wih a wrong phone number, you'll get a result WITHOUT the user_id entry.

So you must do:

   $a = isset( $jsondata['result']['contact']['user_id']);
   if ($a == false)
   {
      $user_id = 0;  // No user_id
   }
   else
   {
      $user_id = $jsondata['result']['contact']['user_id'];
   }

3) The phone number must have the country code. +5599888887777 is OK but 99888887777 is not and will give you an answer without the user_id entry.

Now you can talk to the user using the chat_id and also ban him from group or channel using his user_id.

Microampere answered 5/12, 2018 at 12:11 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.