How to get the user's name in Telegram Bot?

32,273

Solution 1

The getMe() function you are using is for getting information about the bot. But you want the name of the person who sent the message.

In the message API, there is a from attribute (from_user in python) which contains a User object, which contains the details of the person who sent the message.

So you'll have more luck with something like name = message.from_user.first_name.

Solution 2

try this:

message.from_user.id
message.from_user.first_name
message.from_user.last_name
message.from_user.username

or read this https://core.telegram.org/bots/api#user

Solution 3

Access the user's first_name via message param passed with the method wich has the Message object, which then can access the Chat object, getting you the name via message.chat.first_name, as shown in the example below with the greet method:

@bot.message_handler(commands=['Start'])
def greet(message):
  user_first_name = str(message.chat.first_name) 
  bot.reply_to(message, f"Hey! {user_first_name} \n Welcome To The...")
Share:
32,273
Sundararajan
Author by

Sundararajan

I'm an enthusiastic person who push myself a lot to learn about technologies especially in computer programming, I love to code a lot but the problem is I'm a self learner with minimal guidance, i'm working as a software analyst in an emerging IT company. I would like to build some useful stuffs with the help of PYTHON. Yes, I'm a python lover... Please help me out guys when I got myself ended up queries... Don't worry I won't throw any stupid questions, I would think well and search well before I ask... :-)

Updated on January 02, 2022

Comments

  • Sundararajan
    Sundararajan over 2 years

    I'm working in Telegram bot with a handler. where I need to get the user's name or users id once they use the command.

    MY CODE

    import telebot  #Telegram Bot API
        
    bot = telebot.TeleBot(<BotToken>)
        
    @bot.message_handler(commands=['info'])
    def send_welcome(message):
        name = bot.get_me()
        print(name)
        bot.reply_to(message, "Welcome")
    
    bot.polling()
    

    However, I get only info about the bot. I can't retrieve info about the user who used handler.

    OUTPUT

    {'first_name': 'SPIOTSYSTEMS', 'id': 581614234, 'username': 'spiotsystems_bot', 'is_bot': True, 'last_name': None, 'language_code': None}
    

    How do I get the user id or name of the person who uses info command? which method i shall use? please advise.

    NOTE:

    My bot is linked with the Telegram group. and I've removed the Telegram TOKEN from my MVC for security reasons.

  • Diego Ramirez
    Diego Ramirez over 2 years
    Hello! Answers with just a piece of code are not the best. Edit your answer and explain what does the new code will do.