python - 我想使用 discord.py 制作一个多页帮助命令

标签 python discord.py

我正在使用 discord.py 制作一个机器人,并且有更多的命令无法在一页上容纳我的自定义帮助命令。我希望机器人添加 2 个 react ,后退和前进,然后发送帮助消息的用户可以选择一个,并进入帮助命令的不同页面。我希望机器人能够编辑消息以显示第二页,如果他们返回,则编辑回原始的第一页。有人可以帮忙吗?这类似于 owobot 定义,您可以在其中在定义之间来回滚动。

最佳答案

此方法将使用 Client.wait_For() ,如果您有任何其他想法,可以轻松调整。
例子

@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 秒不事件后自行删除(即没有人对箭头使用react),但如果您希望在删除前更长时间,只需更改数字即可。
或者,您可以添加第三个表情符号,例如十字,它可以根据需要删除消息。

引用文献:
  • Message.add_reaction()
  • Message.remove_reaction()
  • Client.wait_for()
  • Message.edit()
  • Message.delete()
  • asyncio.TimeoutError - 用户没有及时 react 的异常(exception)情况
  • 关于python - 我想使用 discord.py 制作一个多页帮助命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61787520/

    相关文章:

    discord - 如何使用 aiohttp 制作 reddit discord 机器人

    python-3.x - Python为消息添加自定义 react

    python - 从 Python 列表中获取数据范围

    python - conda 安装 tensorflow 失败并出现 Python 版本异常

    python - 使用正则表达式在一段时间之前获取所有内容?

    python - 将核苷酸转换为相应的 DNA 序列

    python - "FFmpeg was not found, spotdl can' t continue”,即使它是使用 sudo apt-get install spotdl 安装的 + 如果从终端运行它也可以工作

    python - 如何检查用户是否提供了参数 discord.py

    python - 如何根据值为 Python Pandas 中的整行着色?

    discord.py - 如何使用 client.get_all_emojis() discord.py