我想使用discord.py生成多页帮助命令

2024-09-29 00:20:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用discord.py创建一个bot,并且在一个页面上可以容纳的自定义帮助命令太多了。我希望机器人添加2个反应,前后,然后发送帮助消息的用户可以选择一个,并转到帮助命令的不同页面。我希望机器人能够编辑消息以显示第二页,如果返回,则编辑回原始的第一页。有人能帮忙吗?这类似于owobot定义,您可以在定义之间来回滚动


Tags: 用户py命令消息编辑定义bot机器人
2条回答

此方法将使用^{},如果您有任何其他想法,可以很容易地进行调整

范例

@bot.command()
async def pages(ctx):
    contents = ["This is page 1!", "This is page 2!", "This is page 3!", "This is page 4!"]
    pages = 4
    cur_page = 1
    message = await ctx.send(f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
    # getting the message object for editing and reacting

    await message.add_reaction("◀️")
    await message.add_reaction("▶️")

    def check(reaction, user):
        return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]
        # This makes sure nobody except the command sender can interact with the "menu"

    while True:
        try:
            reaction, user = await bot.wait_for("reaction_add", timeout=60, check=check)
            # waiting for a reaction to be added - times out after x seconds, 60 in this
            # example

            if str(reaction.emoji) == "▶️" and cur_page != pages:
                cur_page += 1
                await message.edit(content=f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
                await message.remove_reaction(reaction, user)

            elif str(reaction.emoji) == "◀️" and cur_page > 1:
                cur_page -= 1
                await message.edit(content=f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
                await message.remove_reaction(reaction, user)

            else:
                await message.remove_reaction(reaction, user)
                # removes reactions if the user tries to go forward on the last page or
                # backwards on the first page
        except asyncio.TimeoutError:
            await message.delete()
            break
            # ending the loop if user doesn't react after x seconds

如果您的编辑器不支持直接粘贴到表情符号中,您可以使用this one之类的网站来查找表情符号的unicodes。在本例中,向前箭头为\u25c0,向后箭头为\u25b6

除此之外,你应该可以走了!该消息在60秒不活动后(即,没有人对箭头作出反应)将自动删除,但如果您希望删除前的时间更长,只需更改数字即可

或者,您可以添加第三个表情符号,例如十字架,它可以根据需要删除消息


参考文献:

如果使用client.command()而不是bot.command(),请将两个变量bot替换为client

相关问题 更多 >