【问题标题】:How to know which user pressed button如何知道哪个用户按下了按钮
【发布时间】:2020-11-14 11:41:18
【问题描述】:

我正在制作 Telegram Bot,我有两个内联按钮。当用户单击按钮机器人会回答“嗨@username”时,我需要这样做。该怎么做?

【问题讨论】:

    标签: python button telegram inline telegram-bot


    【解决方案1】:

    您收到的任何消息对象都包含“from”作为用户对象的键,该对象包含“first_name”和其他属性 (https://core.telegram.org/bots/api#user)。

    使用我推荐的 aiogram 库,您可以执行以下操作:

    @dp.message_handler()
    async def get_message(message):
        await message.answer(f'Hello, @{message.user.username}')
    

    【讨论】:

    • telebot (PyTelegramApiBot) 怎么样?我是新手,所以学习起来更容易
    • 那里的工作方式相同。您可以在消息处理函数中使用 message['from']['first_name'] 来获取名字。
    • @AlexZab telebot 是一种不好的做法。
    【解决方案2】:

    我找到了一种方法来做到这一点!您需要添加username = "@" + str(message.from_user.username),然后添加bot.send_message(message.chat.id, "Hi " + username)

    【讨论】:

    • 请避免使用+作为字符串,改用f-strings
    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2011-04-11
    • 2021-10-08
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    相关资源
    最近更新 更多