0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Discord Botの作り方①開発編

Posted at

はじめに

Discord Botを作成して、デプロイまでする機会があったので備忘録として残します。
今回は、開発編です。

手順

  1. 以下のURLにアクセス
    https://discord.com/developers/applications

  2. 「New Application」をクリックして、任意の名前を設定する

  3. 左メニュー → Bot で、出力されたトークンをメモしておく

  4. 左メニュー → OAuth2 → OAuth2 URL Generator で、必要な権限を設定すると、画面下部にGenerated URLが作成されるので、ブラウザから叩く
    (権限例: scopes => bot,applications.commands | Bot Permissions => Send Messages,Read Message History,Use Slash Commands)

  5. サーバーを選択すると招待されます

コーディング

必要なライブラリをインストール

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が返答してくれないかもしれません
次はデプロイ編書きます

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?