4
4

More than 1 year has passed since last update.

discord.pyのボタンでページ機能を作る

Last updated at Posted at 2022-05-09

必要なもの

discord.py(^2.0.0)

pip install git+https://github.com/Rapptz/discord.py

コード

まずはボタンの追加から

と思ったけど僕が説明するよりいいのがあるのでそちらを見てもらったほうが良い

実装

button.py

import discord
import asyncio
from discord.ext import commands
class Paginator:
    def __init__(self,title="",entries=[],prefix="",suffix="",color=discord.Colour.blue()):
        self.title=title
        self.entries=entries
        self.prefix=prefix
        self.suffix=suffix
        self.color=color
        self.pages=[]
        self.current=0
    async def start(self,ctx):
        current=self.current
        class PageButton(discord.ui.View):
            def __init__(self,title,entries,
                  prefix="",
                  suffix="",
                  color=discord.Colour.blue(),
                  disableds=[True,True,False,False,False],
                  styles=[discord.ButtonStyle.blurple,discord.ButtonStyle.blurple,discord.ButtonStyle.danger,discord.ButtonStyle.blurple,discord.ButtonStyle.blurple],
                  args=["","◀️","","▶️",""],
                  ids=["first","back","stop","next","end"]):
                super().__init__()
                if len(entries)>1:
                    for disable,style,txt,id in zip(disableds,styles,args,ids):
                        self.add_item(PaginateButton(title,entries,prefix,suffix,color,txt,disable,style,id))
                if len(entries)==1:
                    self.add_item(PaginateButton(title,entries,prefix,suffix,color,args[2],disableds[2],styles[2],ids[2]))
        class PaginateButton(discord.ui.Button):
            def __init__(self,title,entries,prefix,suffix,color,txt,disable,style,id):
                self.title=title
                self.entries=entries
                self.prefix=prefix
                self.suffix=suffix
                self.color=color
                super().__init__(label=txt,style=style,custom_id=id,disabled=disable)
            async def callback(self,interaction:discord.Interaction):
                nonlocal current,ctx
                if ctx.author==interaction.user:
                    if self.custom_id=="next":
                        current+=1
                        if current<len(self.entries)-1:
                            await interaction.response.edit_message(
                    embed=discord.Embed(title=self.title,description=f"{self.prefix}{self.entries[current]}{self.suffix}",color=self.color),
                    view=PageButton(self.title,self.entries,disableds=[False,False,False,False,False]))
                        if current==len(self.entries)-1:
                            await interaction.response.edit_message(
                    embed=discord.Embed(title=self.title,description=f"{self.prefix}{self.entries[current]}{self.suffix}",color=self.color))
                            await interaction.message.edit(
                    view=PageButton(self.title,self.entries,disableds=[False,False,False,True,True]))
                    if self.custom_id=="back":
                        current-=1
                        if current>0:
                            await interaction.response.edit_message(
                    embed=discord.Embed(title=self.title,description=f"{self.prefix}{self.entries[current]}{self.suffix}",color=self.color),
                    view=PageButton(self.title,self.entries,disableds=[False,False,False,False,False])
                            )
                        if current==0:
                            await interaction.response.edit_message(
                    embed=discord.Embed(title=self.title,description=f"{self.prefix}{self.entries[current]}{self.suffix}",color=self.color))
                            await interaction.message.edit(
                    view=PageButton(self.title,self.entries,disableds=[True,True,False,False,False]))
                    if self.custom_id=="first":
                        current=0
                        await interaction.response.edit_message(
                    embed=discord.Embed(title=self.title,description=f"{self.prefix}{self.entries[current]}{self.suffix}",color=self.color),
                    view=PageButton(self.title,self.entries,disableds=[True,True,False,False,False]))
                    if self.custom_id=="end":
                        current=len(self.entries)-1
                        await interaction.response.edit_message(
                    embed=discord.Embed(title=self.title,description=f"{self.prefix}{self.entries[current]}{self.suffix}",color=self.color),
                    view=PageButton(self.title,self.entries,disableds=[False,False,False,True,True]))
                    if self.custom_id=="stop":
                        await interaction.response.edit_message(
                    view=None)
        embed=discord.Embed(title=self.title,description=f"{self.prefix}{self.entries[0]}{self.suffix}")
        if isinstance(ctx,commands.Context):
            await ctx.send(embed=embed,view=PageButton(self.title,self.entries,self.prefix,self.suffix,self.color))
        if isinstance(ctx,discord.Interaction):
            await ctx.response.send_message(embed=embed,view=PageButton(self.title,self.entries,self.prefix,self.suffix,self.color))

ちょっと色々

nの値がいろいろ後で調整しているため気持ち悪いことに。

詰まったところ

  • どうやってスタートするか
    • 新しいクラス作ればいいことに気付いた()
  • どうやってstopボタンでボタンを消すか
    • githubにNoneを渡せば消えると書いてあった

使い方

import discord
from discord.ext import commands
from button import Paginator
client=commands.Bot(comand_prefix="!",intents=discord.Intents.default())
@client.event
async def on_ready():
    print("login")
@client.command()
async def pagetest(ctx):
    page=Paginator(entries=[i for i in range(20)])
    await page.start(ctx)
client.run(token)

こんな感じになるはず:thumbsup:
スクリーンショット 2022-05-10 002844.png

出来たらdisabledを使ってみたいがそこまでの力は僕にはない()
使うときは次のコマンド打つ前に真ん中の⏹ボタンを押してください。

修正済み

参考サイト

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4