当我点击按钮时出现“此交互失败”错误

问题描述 投票:0回答:1

所以我有一个代码,运行后,当我单击 Discord 时,我收到此问题“此交互”失败

import discord
from discord.ext import commands



class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(discord.ui.Button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button"))
        
    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
        user = interaction.user
        await user.send("You clicked the button!")
        
        
class InteractiveCog(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.channel_id = 1226612165453021244

    @commands.command()
    async def message(self, ctx):
        channel = self.client.get_channel(self.channel_id)
        if channel:
            embed = discord.Embed(title="Interactive Message", description="Click the button below!")
            await channel.send(embed=embed, view=MyView())
        
async def setup(client):
    await client.add_cog(InteractiveCog(client))



我试图从按钮获得简单的响应,然后,我将更改我的机器人验证。

python discord discord.py discord-buttons
1个回答
0
投票

按钮本身需要回调。在您的代码片段中:

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(discord.ui.Button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button"))

on_button_click 实际上不会执行任何操作,因为它与按钮本身无关。

discord.py 文档中,您会看到

discord.ui.Button
需要回调。

这个函数是一个协程。 与此 UI 项目关联的回调。

因此要添加回调,我们可以这样做:

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()
        button = discord.ui.Button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button")
        button.callback = self.on_button_click  # Add callback to the button
        self.add_item(button)
        
    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
        user = interaction.user
        await user.send("You clicked the button!")
© www.soinside.com 2019 - 2024. All rights reserved.