LoginSignup
3
3

More than 1 year has passed since last update.

[Python]Discord Botのつくりかた

Last updated at Posted at 2023-03-25

前書き

Discord Botコトハジメ。趣味記事です。
メンションするとあらかじめ設定された数パターンの中からランダムに返信を返すDiscord Botを実装します。

下準備

Python実行環境の構築

Discord側の準備

Botアカウントの作成

DEVELOPER PORTALにアクセス、ログインします。

右上の[New Application]をクリック
image.png

モーダルウィンドウが開くのでbot名を入力し、[Create]ボタンをクリックします。
image.png

[Bot]タブを開き、[Add Bot]をクリック。その後、[Yes, do it!]をクリックして続行します。
image.png

今回は個人用のデモBotのため、[PUBLIC BOT]はオフに設定します。
image.png

Privileged Gateway Intentsにもチェックを入れておきます。
image.png

tokenの取得

[Copy]ボタンをクリックするとクリップボードにtokenがコピーされます。tokenはこの画面から何度でもリセット可能です。

Discrodサーバへの招待

この時点ではbotはどのサーバにも参加していない状態です。自分が管理権限を持っているサーバへの招待を行います。

[OAuth2]タブの[URLGenerator]に移動し、[SCOPES]の[bot]にチェックを入れます。
image.png

[BOT PERMISSIONS]が表示されるので、必要な権限にチェックを入れます。
image.png

設定した権限に対応した招待用URLが生成されるので、URLをコピーして別タブで開き、任意のサーバに招待します。

実装

環境変数の設定

python-dotenvを使います。
解説・導入方法は↓

.env
DISCORD_TOKEN=コピーしたtoken
config.py
from dotenv import load_dotenv
load_dotenv()

import os
DISCORD_TOKEN = os.getenv('DISCORD_TOKEN')

discord.pyパッケージをインストール

$ pip install discord.py

実装

discordbot.py
import discord
import config
import random

intents = discord.Intents.all()
client = discord.Client(intents=intents)

# Bot起動時に呼び出される関数
@client.event
async def on_ready():
    print("Ready!")

# メッセージの検知
@client.event
async def on_message(message):
    # 自身が送信したメッセージには反応しない
    if message.author == client.user:
        return

    # ユーザーからのメンションを受け取った場合、あらかじめ用意された配列からランダムに返信を返す
    if client.user in message.mentions:

        ansewr_list = ["さすがですね!","知らなかったです!","すごいですね!","センスが違いますね!","そうなんですか?"]
        answer = random.choice(ansewr_list)
        print(answer)
        await message.channel.send(answer)

# Bot起動
client.run(config.DISCORD_TOKEN)

Botをオンラインにする

この時点ではBotはオフラインです。
image.png

実装したdiscordbot.pyを実行すると…

$ python discordbot.py

無事オンラインになりました。
image.png

動作確認

image.png

動きました!!!!

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