web-dev-qa-db-ja.com

discord.pyを使用して複数ページのヘルプコマンドを作成したい

ボットを作成するためにdiscord.pyを使用していますが、カスタムヘルプコマンドの1ページに収まらないほど多くのコマンドがあります。ボットに2つのリアクションを追加および転送したいので、ヘルプメッセージを送信したユーザーは1つを選択して、ヘルプコマンドの別のページに移動できます。ボットがメッセージを編集して2ページ目を表示できるようにしたいと思います。メッセージが戻った場合は、元の最初のページに戻って編集します。誰かこれを手伝ってくれる?これはowobotの定義に似ており、定義間を前後にスクロールできます。

2
Oblique

このメソッドは 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 などのWebサイトを使用して、絵文字のUnicodeを検索できます。この場合、前方矢印は_\u25c0_であり、後方矢印は_\u25b6_でした。

それ以外に、あなたは行ってもいいはずです!メッセージは、メッセージ内で60秒間何も操作しないと(つまり、誰も矢印に反応しなくなると)削除されますが、削除するまでの期間を長くしたい場合は、番号を変更するだけです。

または、メッセージをオンデマンドで削除するクロスなどの3番目の絵文字を追加することもできます。


参照:

2
Diggy.