skip to Main Content

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

3

Answers


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

    Login or Signup to reply.
  2. 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;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search