LoginSignup
5
8

More than 1 year has passed since last update.

DiscordPyでのボタンの実装方法

Posted at

はじめに

DiscordPyの情報が少ないのでまとめてみました。

目次

  1. DiscordPyのインストール
  2. DiscordPyの簡単な使い方
  3. 参考文献

DiscordPyのインストール

DiscordPyにはバージョンが何種類かあるが今回は1.7.3を使う

$ pip install discord.py

その他必要なもの

$ pip install discord-buttons-plugin
$ pip install dislash.py

DiscordPyの簡単な使い方

from discord.ext import commands
import discord
from discord_buttons_plugin import *
from discord.utils import get
from dislash import InteractionClient, SelectMenu, SelectOption

bot = commands.Bot(command_prefix = "!")
buttons = ButtonsClient(bot)
slash = InteractionClient(bot)
Token = "Token"

@bot.event
async def on_ready():
    print("起動しました")

コマンドの使い方

@bot.command()
async def test(ctx):
    await ctx.channel.send("Test!!")

コマンドに引数を用いることができる

@bot.command()
async def test(ctx, name):
    await ctx.channel.send(f"Test {name}!!")

ボタンの実装方法

@bot.command()
async def button(ctx):
    await buttons.send(
            "テストボタン",
            channel = ctx.channel.id,
            components = [
                ActionRow([
                    Button(
                        label="ボタン", 
                        style=ButtonType().Danger, 
                        custom_id="button_clicked",
                        disabled = False
                    )
                ])
            ]
        )

ボタンの色の変更方法

ButtonType().Primary #青
ButtonType().Success #緑
ButtonType().Secondary #黒
ButtonType().Danger #赤
ButtonType().Link #リンク

ボタンが押されたか検知する

@buttons.click
async def button_clicked(ctx): #関数名は上で指定したカスタムidに対応している
    await ctx.reply("ボタンが押されました", flags = MessageFlags().EPHEMERAL) #ボタンを押した人のみ見えるメッセージ 
    await ctx.channel.send("ボタンが押されました") #誰でも見れる

その他役立つ情報

#embedの作成
embed = discord.Embed(title="テスト",description="これはembedです")
await ctx.channel.send(embed=embed)

#チャンネルの作成(プライベートチャンネル)
admin_role = get(ctx.guild.roles, name="管理者")
permission = {
    ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
    ctx.member: discord.PermissionOverwrite(read_messages=True),
    admin_role: discord.PermissionOverwrite(read_messages=True)
}
channel = await category.create_text_channel(name=ch_name, overwrites=permission)

#チャンネルの削除
await ctx.channel.purge()

#セレクトメニュー
menu = [SelectOption("menu1", "1"), SelectOption("menu2", "2"),]#SelectOption("表示される文字", "対応する文字列")
msg = await ctx.channel.send(
        "セレクトメニュー",
        components=[
            SelectMenu(
                custom_id="test",
                placeholder="セレクトメニュー",
                options=menu
            )
        ]
    )
inter = await msg.wait_for_dropdown()
label = inter.select_menu.selected_options[0].value

#ボタンのリンク先を特定のチャンネルにする
await buttons.send(
            "リンク",
            channel = channel.id,
            components = [
                ActionRow([
                    Button(
                        label="ボタンリンク", 
                        style=ButtonType().Link, 
                        disabled = False,
                        url = f'https://discord.com/channels/{ctx.guild.id}/{channel_id}'#サーバーidとチャンネルid

                    )
                ])
            ]
        )
#メッセージを待つ
message: discord.Message = await bot.wait_for("message", check=lambda m: m.channel == channel) #文字列はmessage.contentで取得する

#DMでメッセージを待つ
message: discord.Message = await bot.wait_for("message", check=lambda m: m.author == ctx.member and m.guild is None) #文字列はmessage.contentで取得する

#on_messageとコマンドを両方使う
@bot.event
async def on_message(message):
    await bot.process_commands(message)

とても役立つ情報

print(vars(ctx))#ctxの中身が表示されてわかりやすい

参考文献

5
8
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
5
8