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?
How to get user_id of a phone number in telegram
apitelegramtelegram-bot
Best Answer
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 seeuser_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 theuser_id
of the newcontact
message. You can read about this object here: Contact ObjectThe method we need to use is sendContact and it needs a target
chat_id
, afirst_name
and aphone_number
. Nowfirst_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 thephone_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 telegramuser_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:
The response to this request is as follow:
"user_id": 654789321
is the part that we are interested in. Now you can delete your message.