skip to Main Content

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?

4

Answers


  1. 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.

    Login or Signup to reply.
  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.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search