无法为我的Discord机器人的斜杠命令添加按钮。

huangapple go评论63阅读模式
英文:

Can't add buttons to slash commands for my discord bot

问题

所以我试图使用discord.py交互和app_commands元素向斜杠命令添加按钮但是当我尝试运行这段代码时我得到了这个错误[error](https://i.stack.imgur.com/hL2Ks.png)我找不到discord.py实现的正常示例也许有人可以帮忙

代码

intents = discord.Intents.all()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@tree.command(name="hello", description="带有按钮的发送hello消息", guild=croc)
async def hello(ctx):
button1 = discord.Button(label="Hello", custom_id="hello")
button2 = discord.Button(label="World", custom_id="world")
action_row = discord.ActionRow(button1, button2)

await ctx.response.send_message("点击一个按钮!", components=[action_row])

@client.event
async def on_interaction(interaction):
if interaction.type == discord.InteractionType.component:
custom_id = interaction.data["custom_id"]

    if custom_id == "hello":
        await interaction.response.send_message("你点击了Hello按钮!", ephemeral=True)
    elif custom_id == "world":
        await interaction.response.send_message("你点击了World按钮!", ephemeral=True)

@client.event
async def on_ready():
await tree.sync(guild=croc)
print("登录为", client.user)


<details>
<summary>英文:</summary>

So I was trying to add buttons to slash commands using discord.py interactions and app_commands elements but when I try to run this code I get this error: [error](https://i.stack.imgur.com/hL2Ks.png). I can&#39;t find normal examples for discord.py implementations maybe somebody can help.

Code:

intents = discord.Intents.all()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@tree.command(name="hello", description="Sends a hello message with buttons", guild=croc)
async def hello(ctx):
button1 = discord.Button(label="Hello", custom_id="hello")
button2 = discord.Button(label="World", custom_id="world")
action_row = discord.ActionRow(button1, button2)

await ctx.response.send_message(&quot;Click a button!&quot;, components=[action_row])

@client.event
async def on_interaction(interaction):
if interaction.type == discord.InteractionType.component:
custom_id = interaction.data["custom_id"]

    if custom_id == &quot;hello&quot;:
        await interaction.response.send_message(&quot;You clicked the Hello button!&quot;, ephemeral=True)
    elif custom_id == &quot;world&quot;:
        await interaction.response.send_message(&quot;You clicked the World button!&quot;, ephemeral=True)

@client.event
async def on_ready():
await tree.sync(guild=croc)
print("Loged as ", client.user)


Maybe there is problem with library version but i don&#39;t know.

</details>


# 答案1
**得分**: 0

从[文档][1]中,可以看出,用于创建按钮的可构建和可用类型是[discord.ui.Button][2],而不是这个。

这不是创建按钮的方法。创建一个视图类:
```python
class ButtonView(discord.ui.View):
    def __init__(self):
        super().__init__()

现在,在这之后,有两种方法可以添加按钮。

class ButtonView(discord.ui.View):
    def __init__(self):
        super().__init__()
    
    @discord.ui.button(label="Hello")
    async def buttoncallback(self, interaction: discord.Interaction, button: button: discord.ui.Button):
        pass

或者你可以动态添加它们。

class ButtonView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_buttons() # 记得添加这一行来调用add_buttons()函数
    def add_buttons(self):
        mybutton = discord.ui.Button(label="Hello")
        self.add_item(mybutton)

        async def buttoncallback(interaction: discord.Interaction):
            pass

        mybutton.callback = buttoncallback

要调用你的按钮,将你的ButtonView添加到发送消息时的view参数中。

@tree.command(name="hello", description="Sends a hello message with buttons", guild=croc)
async def hello(interaction: discord.Interaction):
    view = ButtonView()
    await interaction.response.send_message("Click a button!", view=view)

注意:为了不让自己混淆,将ctx更改为interactiondiscord.ext.commands.Contextdiscord.Interaction完全不同。ctx之所以能工作,是因为你的代码认为它是interaction,并且你确实像是interaction一样使用了它。

参考文献:discord.InteractionResponse.send_messagediscord.ui.Buttondiscord.ui.View

英文:

From the docs,
> The user constructible and usable type to create a button is discord.ui.Button not this one.

This is not how you make a button. Making a view class:

class ButtonView(discord.ui.View):
    def __init__(self):
        super().__init__()

Now, after this, there are two ways to add your buttons.

class ButtonView(discord.ui.View):
    def __init__(self):
        super().__init__()
    
    @discord.ui.button(label=&quot;Hello&quot;)
    async def buttoncallback(self, interaction: discord.Interaction, button: button: discord.ui.Button):
        pass

Or you can dynamically add them

class ButtonView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_buttons() # Remember to add this line to call the add_buttons() function
    def add_buttons(self):
        mybutton = discord.ui.Button(label=&quot;Hello&quot;)
        self.add_item(mybutton)

        async def buttoncallback(interaction: discord.Interaction):
            pass

        mybutton.callback = buttoncallback

To call your button, add your ButtonView to the view parameter when sending your message.

@tree.command(name=&quot;hello&quot;, description=&quot;Sends a hello message with buttons&quot;, guild=croc)
async def hello(interaction: discord.Interaction):
    view = ButtonView()
    await interaction.response.send_message(&quot;Click a button!&quot;, view=view)

Note: As to not confuse yourself, change ctx to interaction. discord.ext.commands.Context is completely different from discord.Interaction. The only reason ctx works is because your code thinks that it is interaction and you did use it as if it was interaction

References: discord.InteractionResponse.send_message, discord.ui.Button, discord.ui.View

huangapple
  • 本文由 发表于 2023年3月31日 19:54:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定