はじめに
Discord Botを作成して、デプロイまでする機会があったので備忘録として残します。
今回は、開発編です。
手順
-
以下のURLにアクセス
https://discord.com/developers/applications -
「New Application」をクリックして、任意の名前を設定する
-
左メニュー → Bot で、出力されたトークンをメモしておく
-
左メニュー → OAuth2 → OAuth2 URL Generator で、必要な権限を設定すると、画面下部にGenerated URLが作成されるので、ブラウザから叩く
(権限例: scopes => bot,applications.commands | Bot Permissions => Send Messages,Read Message History,Use Slash Commands) -
サーバーを選択すると招待されます
コーディング
必要なライブラリをインストール
pip install discord.py python-dotenv
以下サンプル
main.py
import discord
import os
from discord import app_commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.environ.get("DISCORD_TOKEN")
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
@client.event
async def on_ready():
print(f"Logged in as {client.user}")
await tree.sync()
@tree.command(name="hello", description="挨拶します")
async def start_command(interaction: discord.Interaction):
await interaction.response.send_message("こんにちは!")
client.run(TOKEN)
.envも作成
DISCORD_TOKEN=ここに先程取得したTOKEN
動作確認
ローカルで以下実行
python main.py
チャンネルで/helloと打つと、Botが挨拶を返してくれるはずです!
最後に
実行後は、少し待たないとBotが返答してくれないかもしれません
次はデプロイ編書きます