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

3

15

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.

Filbert answered 25/5, 2018 at 3:21 Comment(0)
T
25

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.

Teth answered 25/5, 2018 at 6:26 Comment(0)
I
9

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

Impartial answered 10/10, 2021 at 10:4 Comment(0)
C
2

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...")
Cosetta answered 30/12, 2021 at 12:47 Comment(1)
Hello! Answers with just a piece of code are not the best. Edit your answer and explain what does the new code will do.Gio

© 2022 - 2024 — McMap. All rights reserved.