如何使用 Python-Telegram-Bot 获取 Telegram 用户的用户名、名字或姓氏?

How To Obtain Username, First Name Or Last Name Of A Telegram User With Python-Telegram-Bot?

我正在使用 Python-Telegram-Bot

创建 Telegram 机器人

我知道 update.message.chat_id Returns 用户的聊天 ID,但我需要知道如何获取用户的用户名或名字 And/Or 姓氏。

我在 Telegram 的文档中找到 This 但我不知道如何使用它(我试过 bot.getChat(update.message.chat_id) 但没有结果)

有关用户的所有信息(如用户名、ID、first/last 姓名和个人资料照片)可从 telegram.User object. You can easily get it using telegram.Message

获得
user = update.message.from_user
print('You talk with user {} and his user ID: {} '.format(user['username'], user['id']))

您可以使用json文件并访问用户名、ID等信息。您可以自行打印此文件以获取有关json文件的信息。请参阅下面的示例。

# pip install python-telegram-bot==12.0.0
from telegram.ext import Updater
from telegram.ext import CommandHandler
updater = Updater('token')

def start(bot, update):
    # print('json file update : ' ,update)
    # print("json file bot : ', bot)
    chat_id = update.message.chat_id
    first_name = update.message.chat.first_name
    last_name = update.message.chat.last_name
    username = update.message.chat.username
    print("chat_id : {} and firstname : {} lastname : {}  username {}". format(chat_id, first_name, last_name , username))
    bot.sendMessage(chat_id, 'text')

start_command = CommandHandler('start',start)
updater.dispatcher.add_handler(start_command)
updater.start_polling()
updater.idle()