如何在 Telegram Bot 中获取用户名?

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

我正在使用处理程序在 Telegram 机器人中工作。一旦他们使用命令,我需要在其中获取用户名或用户 ID。

我的代码

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()

但是,我只获得了有关该机器人的信息。我无法检索有关使用处理程序的用户的信息。

输出

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

如何获取使用 info 命令的人的用户 ID 或姓名? 我应该使用哪种方法?请指教

注意:

我的 bot 已链接到 Telegram 组。出于安全原因,我已经从我的 MVC 中删除了 Telegram TOKEN。

您正在使用的 getMe() 函数用于获取有关机器人的信息。但是你想要发消息的人的名字。

message API, there is a from attribute (from_user in python) which contains a User 对象中,其中包含发送消息的人的详细信息。

所以你会有更多的运气,比如 name = message.from_user.first_name

试试这个:

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

或者阅读这个 https://core.telegram.org/bots/api#user

访问用户的 first_namemessage 参数,该参数通过具有 Message object, which then can access the Chat 对象的方法传递,通过 message.chat.first_name 获取名称,如示例所示下面使用 greet 方法:

@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...")