Discord.py 如何制作将运行具有多个随机响应的命令的按钮

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

我正在尝试制作一个Python不和谐机器人。我有一个命令,最终会给出一个随机回复,我发现的代码非常适合它,但我想添加一个按钮,该按钮会与回复一起出现,可以单击该按钮来再次运行该命令,而不必不断地重新输入命令。另外,如果可能的话,我希望它只能由特定角色访问

@bot.command()
async def button(ctx):
    items = [
    discord.Embed(title = "this is for a test"),
    discord.Embed(title = "this is the second test"),
    discord.Embed(title = "this is the third test"),
    discord.Embed(title = "this is the fourth test"),
    discord.Embed(title = "this is the fifth test"),
    discord.Embed(title = "this is the sixth test"),
    discord.Embed(title = "this is the seventh test"),
    discord.Embed(title = "this is the eighth test")]
    randomitem = random.choice(items)
    await ctx.reply(embed=randomitem) # embed= - for send discord.Embed]
    view = discord.ui.View()
    button = discord.ui.Button(label="Click me")
    view.add_item(button)
    await ctx.send(view=view)
python discord discord.py
1个回答
0
投票

不是最有效的方法,但这样做可以:

randomitem = None
@bot.command()
async def button(ctx):
    global randomitem
    items = [
        discord.Embed(title="this is for a test"),
        discord.Embed(title="this is the second test"),
        discord.Embed(title="this is the third test"),
        discord.Embed(title="this is the fourth test"),
        discord.Embed(title="this is the fifth test"),
        discord.Embed(title="this is the sixth test"),
        discord.Embed(title="this is the seventh test"),
        discord.Embed(title="this is the eighth test")
    ]
    
    randomitem = random.choice(items)
    msg = await ctx.reply(embed=randomitem)
    
    async def change_embed(interaction):
        global randomitem
        next_embed = random.choice(items)
        while next_embed == randomitem:
            next_embed = random.choice(items)
        randomitem = next_embed
        await msg.edit(embed=next_embed)
        
    view = discord.ui.View()
    button = discord.ui.Button(label="Click me", custom_id="click_me")
    button.callback = change_embed
    view.add_item(button)
    
    await ctx.send(view=view)

工作原理:

  • randomitem 作为全局变量(默认设置为 None)

  • 功能

    change_embed
    用于更改按钮单击时的嵌入

  • button.callback
    检查按钮点击

  • 回调调用函数

  • while loop
    检查随机项目是否与下一个项目相同

  • msg.edit
    编辑嵌入

注意:点击会在discord中返回“交互失败”错误,因为你没有响应交互

© www.soinside.com 2019 - 2024. All rights reserved.