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
peterh
  • 11,875
  • 18
  • 85
  • 108
isxaker
  • 8,446
  • 12
  • 60
  • 87

3 Answers3

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

Comrade Che
  • 619
  • 8
  • 25
Danil Pyatnitsev
  • 2,172
  • 2
  • 26
  • 39
  • 4
    You're wrong. phone numbers are still unavailable to bots **unless** user explicitly sends it to bot using special command. – Groosha Apr 18 '16 at 16:04
  • 6
    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. – Danil Pyatnitsev Apr 19 '16 at 11:22
  • 4
    Yes, but `user can` means, that by default phone numbers are unavailable to bots.That's what I was saying. – Groosha Apr 19 '16 at 16:46
  • 1
    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. – Danil Pyatnitsev Apr 20 '16 at 04:36
  • help me this link:http://stackoverflow.com/questions/41519495/how-to-solve-disturbance-in-my-bot-in-c?noredirect=1#comment70247673_41519495 – cyrus2500 Jan 07 '17 at 12:22
  • 5
    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? – LA_ Apr 08 '17 at 16:52
  • 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 :) – Danil Pyatnitsev Apr 08 '17 at 16:57
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.

Sergey Ivanov
  • 3,719
  • 7
  • 34
  • 59
  • 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? – azerafati Dec 13 '15 at 08:13
  • 4
    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. – Sergey Ivanov Dec 20 '15 at 10:27
  • 2
    Why `unfortunately`? This prevents spammers from sending their crap to all users (just like WhatsApp) – Groosha Apr 18 '16 at 16:05
  • @SergeyIvanov Is it possible to find user name, using userid? – VSB Jul 22 '16 at 17:52
  • 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. – Sergey Ivanov Jul 23 '16 at 15:08
  • help me this link:http://stackoverflow.com/questions/41519495/how-to-solve-disturbance-in-my-bot-in-c?noredirect=1#comment70247673_41519495 – cyrus2500 Jan 07 '17 at 12:22
4

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;
    }
}
Husam Ebish
  • 4,893
  • 2
  • 22
  • 38