Can I get a phone number by user id via Telegram Bot API?
Asked Answered
T

3

23

I am using Telegram Bot API for sending instant messages to users. I have installed nuget package. This package is recommend by telegram developers.

I have created a telegram bot and successfully got access to it by using code. When I send messsage to bot, bot gets some info about sender.

enter image description here

I need the phone numbers of users to identify them in our system and send the information back to them.

My question is Can i get a user phone number by telegramUserId?

I'm doing it for user convenience. If I could to get a user phone number I should't have to ask for it from the user.

Now my command like this:

debt 9811201243

I want

debt
Tongs answered 9/10, 2015 at 10:18 Comment(0)
F
21

It's possible with bots 2.0 check out bot api docs.

https://core.telegram.org/bots/api#keyboardbutton

https://core.telegram.org/bots/2-0-intro#locations-and-numbers

Felice answered 15/4, 2016 at 5:40 Comment(7)
You're wrong. phone numbers are still unavailable to bots unless user explicitly sends it to bot using special command.Sempach
you can check what is it. User can send itself phone number and also user can sand a contact. You need to compare user_id of sender of the message and user_id of contact. If it's the same that is real phone number of the user.Felice
Yes, but user can means, that by default phone numbers are unavailable to bots.That's what I was saying.Sempach
Ok it's look like permission request in mobile app. If user grand access to number, bot can do, else - dear user, sorry, but bot can not do this things without phone number. You are right.Felice
help me this link:#41519995Cyclist
If I request user's phone with request_contact - can I be sure that this is user's phone? Can not user send manually some other user's phone instead? For ex., by typing it instead of pressing button? Or even by using modified Telegram client?Arthro
I think, that you can be sure that it's actual user's number (if using official client), but I can mistake If bot ask for userphone and user answer to this request you, you get special type of message. and if user just send contact to bot, you also have a phone, but you can check, that it's forward user instead of actual user. Just try :)Felice
S
17

No, unfortunately Telegram Bot API doesn't return phone number. You should either use Telegram API methods instead or ask it explicitly from the user. You cannot get "friends" of a user as well.

You will definitely retrieve the following information:

  1. userid
  2. first_name
  3. content (whatever it is: text, photo, etc.)
  4. date (unixtime)
  5. chat_id

If user configured it, you will also get last_name and username.

Saddlebow answered 9/10, 2015 at 12:12 Comment(6)
but if we explicitly ask the user for a phone number how could we make sure he doesn't send his own number and not someone else's?Crider
There is no integrated way to do this. One way to verify though, would be to send a code to this phone number and ask him to provide this code in the chat.Saddlebow
Why unfortunately? This prevents spammers from sending their crap to all users (just like WhatsApp)Sempach
@SergeyIvanov Is it possible to find user name, using userid?Saire
To my knowledge, you can get it only if a user interact with your bot via Message content, i.e. you cannot provide user_id and username from Telegram Bot API.Saddlebow
help me this link:#41519995Cyclist
B
7

With Telegram Bot API, you can get the phone number only when you request it from the user, but the user does not have to write the number, all he must do is to press a button in the conversation and the number will be sent to you.

enter image description here

When user clicks on /myNumber

enter image description here

The user has to confirm:

enter image description here

You will get his number

enter image description here

This. is the console output:

enter image description here

Take a look at this Simple console application, but you need to do some changes to handle the number:

In Handler.ch add the following lines to BotOnMessageReceived

if (message.Type == MessageType.Contact && message.Contact != null)
{
Console.WriteLine($"Phone number: {message.Contact.PhoneNumber}");
}

This is the piece of code needed in case the repository is deleted someday:

Program.cs

public static class Program
{
    private static TelegramBotClient? bot;

    public static async Task Main()
    {
        bot = new TelegramBotClient(/*TODO: BotToken hier*/);

        User me = await bot.GetMeAsync();
        Console.Title = me.Username ?? "My awesome bot";

        using var cts = new CancellationTokenSource();

        ReceiverOptions receiverOptions = new() { AllowedUpdates = { } };
        bot.StartReceiving(Handlers.HandleUpdateAsync,
            Handlers.HandleErrorAsync,
            receiverOptions,
            cts.Token);

        Console.WriteLine($"Start listening for @{me.Username}");
        Console.ReadLine();

        cts.Cancel();
    }
}

Handlers.cs

 internal class Handlers
    {
        public static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            var errorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

        Console.WriteLine(errorMessage);
        return Task.CompletedTask;
    }

    public static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
    {
        
        var handler = update.Type switch
        {
            UpdateType.Message => BotOnMessageReceived(botClient, update.Message!),
            _ => UnknownUpdateHandlerAsync(botClient, update)
        };

        try
        {
            await handler;
        }
        catch (Exception exception)
        {
            await HandleErrorAsync(botClient, exception, cancellationToken);
        }
    }

    private static async Task BotOnMessageReceived(ITelegramBotClient botClient, Message message)
    {
        Console.WriteLine($"Receive message type: {message.Type}");

        if (message.Type == MessageType.Contact && message.Contact != null)
        {
            // TODO: save the number...
            Console.WriteLine($"Phone number: {message.Contact.PhoneNumber}");
        }

        if (message.Type != MessageType.Text)
            return;
        
        var action = message.Text!.Split(' ')[0] switch
        {
            "/myNumber" => RequestContactAndLocation(botClient, message),
            _ => Usage(botClient, message)
        };
        Message sentMessage = await action;
        Console.WriteLine($"The message was sent with id: {sentMessage.MessageId}");


        static async Task<Message> RequestContactAndLocation(ITelegramBotClient botClient, Message message)
        {
            ReplyKeyboardMarkup requestReplyKeyboard = new(
                new[]
                {
                // KeyboardButton.WithRequestLocation("Location"), // this for the location if you need it
                KeyboardButton.WithRequestContact("Send my phone Number"),
                });

            return await botClient.SendTextMessageAsync(chatId: message.Chat.Id,
                                                        text: "Could you please send your phone number?",
                                                        replyMarkup: requestReplyKeyboard);
        }

        static async Task<Message> Usage(ITelegramBotClient botClient, Message message)
        {
            const string usage = "/myNumber  - to send your phone number";

            return await botClient.SendTextMessageAsync(chatId: message.Chat.Id,
                                                        text: usage,
                                                        replyMarkup: new ReplyKeyboardRemove());
        }
    }
   
    private static Task UnknownUpdateHandlerAsync(ITelegramBotClient botClient, Update update)
    {
        Console.WriteLine($"Unknown update type: {update.Type}");
        return Task.CompletedTask;
    }
}
Burack answered 27/2, 2022 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.