discord.py でボタン・セレクトメニューを作る方法|再起動後も動く永続ボタンまで
メッセージにボタンや選択メニューを付けると、ロールの付け外し、認証パネル、アンケートなど、使いやすい Bot を作れます。discord.py 2.x では discord.ui を使います。このページでは、基本のボタンから、Bot を再起動しても押せる「永続ボタン」、入力フォーム(モーダル)までを説明します。
基本のボタン
import discord
from discord import ui
class HelloView(ui.View):
@ui.button(label="あいさつ", style=discord.ButtonStyle.green)
async def hello(self, interaction: discord.Interaction, button: ui.Button):
await interaction.response.send_message(f"こんにちは、{interaction.user.mention} さん!", ephemeral=True)
@bot.tree.command(name="button", description="ボタンを表示します")
async def button_cmd(interaction: discord.Interaction):
await interaction.response.send_message("ボタンを押してください", view=HelloView())
ui.View を継承したクラスにボタンを並べ、メッセージに view= で付けます。
ボタンの色(スタイル)
| スタイル | 色 | 使いどころ |
primary | 青紫 | メインの操作 |
|---|---|---|
secondary | グレー | サブの操作 |
success / green | 緑 | 確定・参加 |
danger / red | 赤 | 削除・取り消し |
link | グレー+リンク | Web ページを開く(url= を指定) |
セレクトメニュー(選択肢)
class RoleSelect(ui.View):
@ui.select(
placeholder="通知を受け取るジャンルを選んでください",
min_values=0, max_values=3,
options=[
discord.SelectOption(label="ゲーム", value="game", emoji="🎮"),
discord.SelectOption(label="音楽", value="music", emoji="🎵"),
discord.SelectOption(label="イベント", value="event", emoji="🎉"),
],
)
async def select(self, interaction: discord.Interaction, select: ui.Select):
await interaction.response.send_message(f"選択:{', '.join(select.values) or 'なし'}", ephemeral=True)
再起動しても押せる「永続ボタン」
普通のボタンは、Bot を再起動すると押しても反応しなくなります(「インタラクションに失敗しました」)。認証パネルのように長く置いておくボタンは、次の3つを満たす「永続ボタン」にします。
ui.View(timeout=None)にする- ボタンに固定の
custom_idを付ける - 起動時に
bot.add_view()で登録し直す
class VerifyView(ui.View):
def __init__(self):
super().__init__(timeout=None)
@ui.button(label="認証する", style=discord.ButtonStyle.green, custom_id="verify:button")
async def verify(self, interaction: discord.Interaction, button: ui.Button):
role = discord.utils.get(interaction.guild.roles, name="メンバー")
await interaction.user.add_roles(role)
await interaction.response.send_message("認証しました!", ephemeral=True)
class MyBot(commands.Bot):
async def setup_hook(self):
self.add_view(VerifyView()) # 再起動後もボタンを受け付ける
Bot が24時間動いていないと、そもそもボタンは反応しません。認証パネルなどを置くなら、止まらないサーバーで動かすのが前提です。
入力フォーム(モーダル)
ボタンを押したときに、文字を入力する小さな画面を出せます。お問い合わせや申請フォームに便利です。
class ContactModal(ui.Modal, title="お問い合わせ"):
subject = ui.TextInput(label="件名", max_length=100)
body = ui.TextInput(label="内容", style=discord.TextStyle.paragraph, max_length=1000)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f"受け付けました:{self.subject.value}", ephemeral=True)
class ContactView(ui.View):
@ui.button(label="お問い合わせ", style=discord.ButtonStyle.primary)
async def open(self, interaction: discord.Interaction, button: ui.Button):
await interaction.response.send_modal(ContactModal())
よくあるつまずき
「インタラクションに失敗しました」と出る
- 3秒以内に応答していない → 重い処理の前に
await interaction.response.defer() - Bot を再起動した → 永続ボタンにする
- 処理中にエラーが起きた → コンソールのログを確認
ボタンは5個×5行まで
1つのメッセージに付けられるのは、1行5個まで・最大5行(合計25個)です。セレクトメニューは1つで1行を使います。
まとめ
ui.Viewにボタンやセレクトを並べ、view=で付ける- 長く置くボタンは
timeout=None・custom_id・add_viewで永続化 - 入力が必要なら
ui.Modalで入力フォームを出す
Discord Bot を、月 ¥180 で24時間。
支払い後およそ2分で、日本のサーバーが自動で用意されます。 プランを見る →ほかのガイド
Discord Bot で参加時の歓迎メッセージ・ロール自動付与を作る方法discord.py でメンバーの参加・退出を検知し、歓迎メッセージ・ロールの自動付与・DM 送信を作る方法と、動かないときの確認ポイントを解説します。読む →
Discord Bot のレート制限(429 Too Many Requests)の原因と対処法Bot のログに出る 429・We are being rate limited の意味と、ループでの連続送信や短すぎる定期処理などの原因、待ち時間を入れるなどの対処法を解説します。読む →
discord.py のよくあるエラー一覧と解決方法【まとめ】LoginFailure・PrivilegedIntentsRequired・ModuleNotFoundError・Missing Permissions・インタラクションに失敗しました など、discord.py でよく出るエラーの意味と直し方を一覧にまとめました。読む →
requirements.txt の書き方|Bot に必要なライブラリをサーバーに入れる方法サーバーで ModuleNotFoundError が出る原因と、requirements.txt の書き方・自動で作る方法・バージョン指定・import 名とインストール名が違うライブラリの一覧を解説します。読む →
discord.py の Cog でコマンドをファイルごとに分ける方法discord.py 2.x の Cog を使って、コマンドやイベントを機能ごとのファイルに分ける方法を解説。setup・load_extension・再読み込み・よくあるエラーまで紹介します。読む →
discord.py で定期実行する方法|tasks.loop で毎日・毎時の自動投稿discord.py の tasks.loop で、一定間隔・毎日決まった時刻(日本時間)に処理を実行する方法と、開始・停止、エラー時の対処、よくある失敗を解説します。読む →