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

时间:2016-12-06 02:16:26

标签: python telegram telegram-bot python-telegram-bot

我使用Python-Telegram-Bot

创建电报机器人

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

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

2 个答案:

答案 0 :(得分:5)

telegram.User对象提供的有关用户的所有信息(作为用户名,ID,名字/姓名和个人资料照片)。您可以使用telegram.Message

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

答案 1 :(得分:1)

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

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