【问题标题】:How to get the user's name in Telegram Bot?如何在 Telegram Bot 中获取用户名?
【发布时间】:2018-11-04 08:54:26
【问题描述】:

我在 Telegram bot 中使用处理程序。一旦他们使用该命令,我需要在其中获取用户名或用户 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 或姓名? 我将使用哪种方法?请指教。

注意:

我的机器人与 Telegram 群组相关联。并且出于安全原因,我已从 MVC 中删除了 Telegram TOKEN。

【问题讨论】:

    标签: python python-3.x telegram telegram-bot python-telegram-bot


    【解决方案1】:

    您使用的getMe() 函数用于获取有关机器人的信息。但是您需要发送消息的人的姓名。

    message API 中,有一个from 属性(python 中的from_user)包含一个User 对象,其中包含发送消息的人的详细信息。

    因此,name = message.from_user.first_name 之类的内容会让您更加幸运。

    【讨论】:

      【解决方案2】:

      试试这个:

      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

      【讨论】:

        【解决方案3】:

        通过message 访问用户的first_name 参数,通过具有Message 对象的方法传递,然后可以访问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...")
        

        【讨论】:

        • 您好!只用一段代码的答案并不是最好的。编辑您的答案并解释新代码的作用。
        猜你喜欢
        • 2017-04-20
        • 2019-02-14
        • 2022-07-28
        • 2016-02-23
        • 2017-12-25
        • 1970-01-01
        • 2016-10-05
        • 2022-11-10
        • 2018-04-10
        相关资源
        最近更新 更多