【问题标题】:How to create a clickable button under the message?如何在消息下创建一个可点击的按钮?
【发布时间】:2021-10-11 10:42:15
【问题描述】:

我正在尝试使用 Python 和 discord.py 创建一个 Discord 机器人,但目前我想创建一个“可点击按钮”:

这是一个带有按钮的 Dank Memer 机器人示例。如何实现这一点并在我的消息下添加按钮?

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    首先,这些是 Discord 中新 "Message Components" 的一部分。对于 discord.py,这称为按钮组件。此功能在 discord.py 的 PyPi 版本中不可用,仅在 master 分支上的 2.0 重写中可用。

    $ pip install git+https://github.com/Rapptz/discord.py.git@master
    

    但是由于 discord.py 不再维护,也许可以查看一个维护的分支,例如 nextcord、disnake 等。

    要在 dpy 2.0 上使用创建按钮:

    view = discord.ui.View()
    item = discord.ui.Button(style=discord.ButtonStyle.blurple, label="Click Me", url="https://google.com")
    view.add_item(item=item)
    await ctx.send("This message has a button!", view=view)
    

    或者对于更复杂的功能,您可以将discord.ui.View 子类化:

    class ViewWithButton(discord.ui.View):
        @discord.ui.button(style=discord.ButtonStyle.blurple, label='Click Me')
        async def click_me_button(self, button: discord.ui.Button, interaction: discord.Interaction):
            print("Button was clicked!")
    
    
    await ctx.send("This message has a button!", view=ViewWithButton())
    

    可在此处找到 discord.py 的按钮参考:https://discordpy.readthedocs.io/en/master/api.html#button

    【讨论】:

      【解决方案2】:

      安装 discord.py master 分支

      pip install git+https://github.com/Rapptz/discord.py.git@master
      

      如需使用 ui/interactions,请参阅 Official docs

      您可以在https://github.com/Rapptz/discord.py/tree/master/examples/views 上找到示例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-15
        • 2014-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-12
        相关资源
        最近更新 更多