![見出し画像](https://assets.st-note.com/production/uploads/images/94044024/rectangle_large_type_2_d9363b8c723aa31428bdc4fa5bf9438f.png?width=800)
discord.py による簡易Botの作成
「discord.py」による簡易Botの作成を試したので、まとめました。
1. discord.py
「discord.py」は、モダンで使いやすく、機能が豊富で、非同期対応のdiscord APIラッパーです。
特徴は、次のとおりです。
・async/await 構文を使用した最新のPythonic API
・429を防止する正常なレート制限処理
・Botの作成を支援するコマンド拡張
・使いやすいオブジェクト指向設計
・速度とメモリの両方を最適化
2. Botアカウントの作成
Discord Developer Portal で、Botアカウントを作成します。
(1) Discord Developer Portal の Applications を開く。
(2) 「New Applications」ボタンを押し、アプリケーションを作成。
![](https://assets.st-note.com/img/1671956520609-5atpblqo1T.png?width=800)
(3) 「Bot」タブで「Add Bot」をクリックし、「Reset Token」と「Copy」をクリックし、トークン (Discord Bot Token) を取得。
このトークンはBotのパスワードになります。
![](https://assets.st-note.com/img/1671956643324-vCSBqFiHLv.png?width=800)
![](https://assets.st-note.com/img/1671958208870-DJWLq2huwd.png?width=800)
(4) 「Public Bot」を無効化。
自分だけがこのBotをサーバーに参加できるようになります。
![](https://assets.st-note.com/img/1671956864847-LXYMzt865h.png?width=800)
(5) 「Message Content Intent」を有効化。
メッセージを受信するために必要です。
![](https://assets.st-note.com/img/1671956912186-4itRFdsptG.png?width=800)
3. Botをサーバーに招待
(1) 「OAuth2」タブの「URL Generator」の「Scopes」で「bot」をチェック。
![](https://assets.st-note.com/img/1671957298801-9g0eCe5CCJ.png?width=800)
(2) 「Bot Permissions」で「Send Messages」と「Read Message History」をチェック。
![](https://assets.st-note.com/img/1671957306719-HauaufEmN3.png?width=800)
(3) 下端のURLをコピーして、ブラウザで開き、招待するサーバーを設定。
![](https://assets.st-note.com/img/1671957374422-Qmxox6mz3u.png?width=800)
4. Botの作成
特定のメッセージに応答するBotを作成します。
(1) Pyton 3.8以降の仮想環境の準備。
(2) パッケージのインストール。
$ python -m pip install -U discord.py
(3) コードの作成。
「discord.py」の処理は、イベントドリブンです。各種イベントに対応する応答を、コードで記述します。また、以下のコードの <DISCORD_BOT_TOKENをここに記述> には、自分のトークンを記述してください。
・example_bot.py
import discord
# インテントの生成
intents = discord.Intents.default()
intents.message_content = True
# クライアントの生成
client = discord.Client(intents=intents)
# discordと接続した時に呼ばれる
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
# メッセージを受信した時に呼ばれる
@client.event
async def on_message(message):
# 自分のメッセージを無効
if message.author == client.user:
return
# メッセージが"$hello"で始まっていたら"Hello!"と応答
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
# クライアントの実行
client.run('<DISCORD_BOT_TOKENをここに記述>')
(4) Botの実行
$ python example_bot.py
(5) discordアプリで「$hello」とメッセージ送信。
「Hello!」の応答してくれます。
![](https://assets.st-note.com/img/1671957485976-5DGh4dtVVI.png?width=800)
5. Extensions
Extensions は、次のとおりです。
・discord.ext.commands - Bot commands framework
・discord.ext.tasks - asyncio.Task helpers
6. APIリファレンス
APIリファレンスは、次のとおりです。
・API リファレンス
・Interactions API リファレンス
・discord.ext.commands API リファレンス
・discord.ext.tasks API リファレンス
この記事が気に入ったらサポートをしてみませんか?