【问题标题】:How To Obtain Username, First Name Or Last Name Of A Telegram User With Python-Telegram-Bot?如何使用 Python-Telegram-Bot 获取 Telegram 用户的用户名、名字或姓氏?
【发布时间】:2017-04-20 13:59:27
【问题描述】:

我正在使用Python-Telegram-Bot 创建一个电报机器人

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

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用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()
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-04
        • 2016-10-05
        • 2016-02-23
        • 1970-01-01
        • 2022-11-10
        • 2020-02-15
        • 2018-02-10
        • 1970-01-01
        相关资源
        最近更新 更多