【Python】Discord BOT を作る

Uncategorized
638 words

思ってたより簡単に作れそう。

Discord BOT アカウント作成

Discord API を使うため、Discord BOT アカウントを作成します。

developer portal の Applications ページ を開き、右上の「New Application」をクリック。

アプリケーションの名前を入力し「Create」をクリック。

「Bot」タブに移動し「Reset Token」をクリック。

「Yes, do it!」をクリック。

トークンが発行されるので、コピペしておきます。

サーバーに BOT 追加

今作った BOT をサーバーに追加するため、BOTの招待用URL を作成します。

「OAuth2」タブの「URL Generator」カテゴリーに移動し、

「SCOPES」セクションの「bot」を選択。

「BOT PERMISSIONS」セクションの「Administrator」を選択。

今回はお試しのため、Administrator を選択したが、実際の運用時は最低限の権限を選択する。

「GENERATED URL」セクションに 招待用URL が表示される。

招待用URL をブラウザーで開き、サーバーに BOT を追加します。

対話型BOT

Python の discord.py ライブラリー を使って、対話型BOT を作成します。

discord.py ライブラリー

1
pip install -U discord.py

ソース

適当なフォルダー内に「main.py」を作成して、次のソースをコピペします。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import discord

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

@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('$hello'):
await message.channel.send('Hello!')

client.run(token='*****')

「token=’*****’」の部分は、自分の トークンに差し替えてください。

確認

これを実行して BOT にメッセージ「$hello」を送ると、BOT が反応してくれます。

定期的に実行するBOT

前回のは 対話型BOT でしたが、今回は定期的に実行されるBOTを紹介します。

ソース

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import discord
from discord.ext import tasks, commands

intents = discord.Intents.default()
intents.members = True # membersを受け取る
bot = commands.Bot(command_prefix='!', intents=intents)

@tasks.loop(minutes=1)
async def fetch_members():
for guild in bot.guilds:
members = []
async for member in guild.fetch_members():
print(f"Fetched Member {member}")
members.append(member)
# 続きの処理...
print(f"Fetched {len(members)} members.")
print("Members fetching job done.")

@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
fetch_members.start() # Start the task

bot.run(token='*****')

確認

これを実行すると、1分ごとにサーバーのメンバーリストを取得してコンソールに表示してくれます。

例外エラー

BOT が「サーバーのメンバーリストを扱う」ということを宣言していないため。

1
2
3
4
5
6
例外が発生しました: PrivilegedIntentsRequired
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
discord.gateway.WebSocketClosure:
During handling of the above exception, another exception occurred:
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 4014
During handling of the above exception, another exception occurred:

「Bot」セクションの「SERVER MEMBERS INTENT」を有効にする。

参考

https://www.freecodecamp.org/japanese/news/create-a-discord-bot-with-python/