discord.py でスラッシュコマンドを作る方法|引数・選択肢・権限まで
「/」を打つと候補が出てくるスラッシュコマンドは、今の Discord Bot の基本です。入力ミスが減り、Message Content Intent も不要なので、新しく作る Bot ならスラッシュコマンドがおすすめです。このページでは、discord.py 2.x での作り方を、基本から引数・選択肢・権限の制限まで説明します。
スラッシュコマンドとテキストコマンドの違い
| スラッシュコマンド | テキストコマンド(!help など) | |
| 入力の補助 | 候補・説明・引数の入力欄が出る | なし(覚えて打つ) |
|---|---|---|
| 必要なインテント | なし | Message Content(特権) |
| 返信の見え方 | 本人だけに見せる返信もできる | 全員に見える |
基本の書き方(commands.Bot の場合)
import os
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.tree.command(name="ping", description="Bot の応答速度を表示します")
async def ping(interaction: discord.Interaction):
ms = round(bot.latency * 1000)
await interaction.response.send_message(f"Pong! {ms}ms")
@bot.event
async def on_ready():
synced = await bot.tree.sync()
print(f"Logged in as {bot.user}({len(synced)} 個のコマンドを登録)")
bot.run(os.getenv("DISCORD_TOKEN"))
ポイントは2つです。@bot.tree.command でコマンドを定義することと、起動時に bot.tree.sync() で Discord に登録することです。
sync() をすべてのサーバー向けに実行すると、反映まで時間がかかることがあります。開発中は、特定のサーバーだけに登録すると即座に反映されます(下の「すぐに反映させる」を参照)。引数(オプション)を付ける
関数の引数に型を書くだけで、入力欄が自動で作られます。説明は @app_commands.describe で付けます。
@bot.tree.command(name="say", description="Bot に発言させます")
@app_commands.describe(text="発言させる内容", count="繰り返す回数")
async def say(interaction: discord.Interaction, text: str, count: int = 1):
await interaction.response.send_message("\n".join([text] * min(count, 5)))
使える型の例:str・int・float・bool・discord.Member(メンバーを選ぶ)・discord.Role・discord.TextChannel など。初期値を付けた引数は「任意」になります。
選択肢から選ばせる
@bot.tree.command(name="color", description="好きな色を選びます")
@app_commands.choices(color=[
app_commands.Choice(name="赤", value="red"),
app_commands.Choice(name="青", value="blue"),
app_commands.Choice(name="緑", value="green"),
])
async def color(interaction: discord.Interaction, color: app_commands.Choice[str]):
await interaction.response.send_message(f"{color.name} を選びました({color.value})")
本人だけに見える返信
ephemeral=True を付けると、コマンドを使った本人にだけ表示されます。設定画面やエラーの通知に便利です。
await interaction.response.send_message("設定を保存しました", ephemeral=True)
管理者だけが使えるようにする
@bot.tree.command(name="clear", description="メッセージをまとめて削除します")
@app_commands.default_permissions(manage_messages=True)
@app_commands.checks.has_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.defer(ephemeral=True)
deleted = await interaction.channel.purge(limit=min(amount, 100))
await interaction.followup.send(f"{len(deleted)} 件削除しました", ephemeral=True)
default_permissions は「最初からその権限がある人にだけ表示する」設定、checks.has_permissions は実行時の確認です。両方付けておくと安全です。
時間がかかる処理は defer する
スラッシュコマンドは 3秒以内に応答しないと失敗(「アプリケーションが応答しませんでした」)になります。外部 API の呼び出しなど時間がかかる処理は、先に defer() してから followup で返します。
await interaction.response.defer() # 「考え中…」を表示
result = await heavy_task()
await interaction.followup.send(result)
すぐに反映させる(開発用)
GUILD = discord.Object(id=123456789012345678) # テスト用サーバーの ID
@bot.event
async def on_ready():
bot.tree.copy_global_to(guild=GUILD)
await bot.tree.sync(guild=GUILD)
特定のサーバーに登録したコマンドは、すぐに使えるようになります。公開するときは、全体向けの sync() に戻します。
よくあるエラー
コマンドが表示されない
招待 URL に applications.commands スコープが付いているか、sync() を実行しているかを確認します。Discord アプリの再起動で表示されることもあります。
「アプリケーションが応答しませんでした」
3秒以内に応答できていません。defer() を使うか、エラーで止まっていないかログを確認します。
CommandSignatureMismatch
コードを変えたのに、Discord 側の登録が古いままです。sync() し直してください。
まとめ
@bot.tree.commandで定義し、tree.sync()で登録する- 引数は型を書くだけ、選択肢は
@app_commands.choices - 3秒ルールに注意し、重い処理は
defer()する
作った Bot を24時間動かすなら、StellaHost で月額 ¥180 から始められます。
Discord Bot を、月 ¥180 で24時間。
支払い後およそ2分で、日本のサーバーが自動で用意されます。 プランを見る →