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

Sad*_*aie 1 python telegram python-telegram-bot telegram-bot

我正在使用Python-Telegram-Bot创建一个Telegram Bot

我知道update.message.chat_id返回用户的聊天ID,但我需要知道如何获取用户的用户名或名字和/或姓氏.

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

Dud*_*kof 7

有关用户的所有信息(如用户名,ID,名字/姓氏和个人资料照片),可从telegram.User对象获得.您可以使用telegram.Message轻松获取它

user = update.message.from_user
print('You talk with user {} and his user ID: {} '.format(user['username'], user['id']))
Run Code Online (Sandbox Code Playgroud)


sae*_*oor 6

可以使用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()
Run Code Online (Sandbox Code Playgroud)