👋

discord.pyでスラッシュコマンドを実装する方法

2023/09/26に公開

Discordボットとは

Discordは、ゲーマーやコミュニティのメンバーに利用されるコミュニケーションツールです。この記事では、Discordボットを作成し、Pythonライブラリであるdiscord.pyを使用してスラッシュコマンドを実装する方法を説明します。

開発環境のセットアップ

Discordボットを開発するには、Pythonとdiscord.pyのセットアップが必要です。以下は、開発環境をセットアップする手順です。

Pythonをインストールします。

discord.pyライブラリをインストールします。

Discord Botを作成します。

ボットの基本設定

ボットをサーバーに導入するための手順と、基本的な設定について説明します。Discordサーバーでボットを使用するために必要な情報を提供します。

スラッシュコマンドの作成
スラッシュコマンドの基本的な構造と作成方法について詳しく解説します。Discord Botにスラッシュコマンドを追加するためのステップを説明します。

コマンドの処理

インポートとクライアントの初期化
この部分では、必要なライブラリをインポートし、Discordボットのクライアントを初期化します。

import discord 
from discord import app_commands 
intents = discord.Intents.default() 
client = discord.Client(intents=intents) 
tree = app_commands.CommandTree(client)

discord ライブラリはDiscordのAPIとの対話を可能にします。

app_commands モジュールはスラッシュコマンドを扱うために使用します。

intents はDiscordボットがどの種類のイベントに反応するかを設定します。

client はDiscordボットのクライアントです。コードの中核となる部分です。

tree はスラッシュコマンドを管理するためのオブジェクトです。

ボットのログインと同期

この部分では、ボットがDiscordにログインし、スラッシュコマンドを同期させます。

@client.event
  async def on_ready():
  print('ログインしました') 
  # アクティビティを設定 
  new_activity = f"テスト" 
  await client.change_presence(activity=discord.Game(new_activity)) 
  # スラッシュコマンドを同期 
  await tree.sync()

@client.event デコレータは、on_ready 関数がボットがログインしたときに実行されるイベントハンドラであることを示します。

await client.change_presence() は、ボットのステータス(アクティビティ)を設定します。

await tree.sync() は、スラッシュコマンドをDiscordに同期させ、利用可能にします。

スラッシュコマンドの定義

この部分では、スラッシュコマンド hello を定義します。

@tree.command(name='hello', description='Say hello to the world!') 
async def test(interaction: discord.Interaction): 
  await interaction.response.send_message('Hello, World!')

@tree.command デコレータは、hello というスラッシュコマンドを定義します。

description はコマンドの説明を設定します。

async def test(interaction: discord.Interaction): は hello コマンドが実行されたときに呼び出される関数を定義します。

await interaction.response.send_message('Hello, World!') は、コマンドが実行された際に "Hello, World!" というメッセージをユーザーに返します。

ボットの実行

最後に、ボットを実行します。

client.run("TOKEN")

client.run("TOKEN") は、ボットを指定したトークンで起動します。このトークンを実際のボットのトークンに置き換える必要があります。

このように、コードは複数の部分から構成され、各部分が特定の役割を果たしています。インポート、クライアントの初期化、イベントハンドラの定義、スラッシュコマンドの定義、ボットの実行など、それぞれの部分が全体の機能を実現するために重要な役割を果たしています。

ボットのテスト

/helloコマンドを実行すると"hello, world!"と返事できていますね

おわりに

この記事では、discord.pyを使用してスラッシュコマンドを実装する方法を包括的に説明しました。スラッシュコマンドはDiscordボットの強力なツールであり、ユーザーとのインタラクションを向上させるのに役立ちます。これからもさらに多くの機能を追加して、ボットをカスタマイズしていきましょう。

使用したコード

import discord
from discord import app_commands

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@client.event
async def on_ready():
    print('ログインしました')

    # アクティビティを設定
    new_activity = f"テスト"
    await client.change_presence(activity=discord.Game(new_activity))

    # スラッシュコマンドを同期
    await tree.sync()

@tree.command(name='hello', description='Say hello to the world!')
async def test(interaction: discord.Interaction):
    await interaction.response.send_message('Hello, World!')


client.run("TOKEN")

Discussion