【问题标题】:Embed pages using buttons discord.py使用按钮嵌入页面 discord.py
【发布时间】:2022-11-16 08:44:44
【问题描述】:

我一直在努力开店。我有一些产品的数据库。我需要在一页上显示 5 个产品的地方嵌入,嵌入有按钮(上一个/下一个),使用这个按钮你可以翻页。 我怎样才能用按钮翻页?

class Buttons(discord.ui.View):
    @discord.ui.button(label='Previous', style=discord.ButtonStyle.gray)
    async def previous(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.edit_message(view=self)

    @discord.ui.button(label='Next', style=discord.ButtonStyle.gray)
    async def next(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.edit_message(view=self)
class roleShop(commands.Cog):
    def __init__(self, client):
        self.client = client

    @app_commands.command(name='shop', description='Roles shop')
    async def roleShop(self,interaction: discord.Interaction):
        count = 0
        pageCount = 0
        roleList = []
        for i in dbConnect.sql.execute("SELECT * FROM shop"):
            count+=1
            roleList.append(i)
        pageCount = count/5
        if pageCount % 2 != 0:
            pageCount=str(pageCount).split('.')
            pageCount=int(pageCount[0])
            pageCount+=1

        embed=discord.Embed(
            title='Roles shop',
            color=discord.Colour.dark_green()
            )
        roleList=[]
        for i in dbConnect.sql.execute("SELECT * FROM shop"):
            roleList.append(i)
        embed.description = f'Roles to sell: **{len(roleList)}**'
        c=0
        for j in roleList[:5]:
            c+=1
            embed.add_field(name='\u200b',value=f'**{c}**)Role:<@&{j[0]}>\nSeller: <@{j[4]}>\nCost: **{j[2]}**\nPurchases: **{j[3]}**', inline=False)
        embed.set_footer(text=f'Page 1/{pageCount}')
        await interaction.response.send_message(embed=embed, view=Buttons())

【问题讨论】:

  • 您好,Stack Overflow 不是人们为您编写代码的网站。你能用你目前拥有的代码编辑你的问题吗?

标签: python discord.py


【解决方案1】:

要使按钮真正起作用,您需要定义与它们交互时会发生什么。这是互动的callback

一种方法是创建一个名为callback 的异步函数,并让它接受参数interaction。然后您可以在函数中编辑消息,使其“翻页”

这是选择菜单的回调示例代码(对按钮的工作方式相同)

select = Select(
    placeholder="Click an option!",
    options=[
        discord.SelectOption(label="Red"),
        discord.SelectOption(label="Blue"),
        discord.SelectOption(label="Green")
    ]
)

async def my_callback(interaction):
    embed_replacement = discord.Embed(
        title = "New title!",
        description = "New description!"
        )
    await interaction.response.edit_message(embed=embed_replacement)

select.callback = my_callback # Setting callback for the select menu
print(f"You've selected {select.values[0]}!") # Element 0 is what the user has selected

本质上,当单击一个选项时(在您单击按钮的情况下),它会自动调用 callback 函数并运行其中的任何内容。您不必为整组按钮设置回调,如果您愿意,可以为每个按钮设置一个回调。在类中定义异步

【讨论】:

    猜你喜欢
    • 2021-11-29
    • 2021-01-01
    • 2021-12-27
    • 2021-08-16
    • 2021-03-21
    • 2022-01-11
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多