discord.pyを使ってDiscordのBotを作成して簡単な応答をさせてみた

なんか面倒そうで触っていなかったDiscordのBotを試してみました。案外簡単でした。
2022.01.24

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

最近のゲーム関係コミュニティでよく使われているDiscord。PS5及びPS4に近日連携されるというニュースも出ていて、マルチプレイをする上では欠かせないケースもでてきそうです。私個人もかつてはプライベートにおいてもSlackを使っていましたが、現在はDiscord一色となっています。

主に以下のタイトルでの情報収集で用いており、海外産のタイトルやMMORPGを遊び始めたり、運営がDiscordを推奨している場合に参加チャンネルが更に増える感じです。

そんなDiscordにもAPIが存在しますが、これまで触っていませんでした。始めるまでに面倒なイメージが強かったためです。が、効率を求めると避けられない点もあり、すこしづつながら触ってみることにしました。とりあえずはPython製のAPIラッパー discord.py を用います。

Discordアカウントの作成

Botの作成にはDiscordアカウントが必要です。アカウントがなければ登録しましょう。

Bot動作確認用サーバの作成

手軽く確認するためサーバを作成しておきます。Discordログイン後に画面左下からサーバを作成します。

「オリジナルの作成」にて「自分と友達のため」を選択します。サーバ名に適当な名前を入れて「新規作成」をクリックします。

Botの作成

Discordアカウント作成後、Developer Portalにアクセスします。右側の「New Application」からアプリケーションとしてBotを作成します。Bot名だけ指定が必要です。

Bot作成後、左側メニューの「Bot」から「Build A Bot」を選択して実際にBotとしてチャンネル上で機能させますが、名前が被っていると追加できません。

以下のエラーが出た場合はGeneral Informationからリネーム後に再度操作します。

追加完了できたら、左側「Bot」からコーディングに利用するTokenを取得します。「Copy」をクリックするだけです。

念の為「PUBLIC BOT」をOFFしておきます。

次に権限付与を行います。左側「OAuth2」の「URL Generator」を選択します。

「Scope」のうち「Bot」を選択し、「BOT PERMISSIONS」については「Send Messages」と「Read Messages/View Channels」にチェックを入れておきます。

最後に「Generated URL」を「Copy」してアクセスしてみましょう。Botの動作確認用チャンネルを指定します。

discord.pyのセットアップ

poetryを併用してみます。

mkdir discord
cd discord/
poetry init
poetry add discord.py

以下、実際のログ。

% mkdir discord
% cd discord/
% poetry init
This command will guide you through creating your pyproject.toml config.

Package name [discord]:
Version [0.1.0]:
Description []:
Author [xxxx <xxxxxx@example.com>, n to skip]:
License []:
Compatible Python versions [^3.9]:

Would you like to define your main dependencies interactively? (yes/no) [yes]
You can specify a package in the following forms:
  - A single name (requests)
  - A name and a constraint (requests@^2.23.0)
  - A git url (git+https://github.com/python-poetry/poetry.git)
  - A git url with a revision (git+https://github.com/python-poetry/poetry.git#develop)
  - A file path (../my-package/my-package.whl)
  - A directory (../my-package/)
  - A url (https://example.com/packages/my-package-0.1.0.tar.gz)

Search for package to add (or leave blank to continue):

Would you like to define your development dependencies interactively? (yes/no) [yes]
Search for package to add (or leave blank to continue):

Generated file

[tool.poetry]
name = "discord"
version = "0.1.0"
description = ""
authors = ["xxxx <xxxxxx@example.com>"]

[tool.poetry.dependencies]
python = "^3.9"

[tool.poetry.dev-dependencies]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"


Do you confirm generation? (yes/no) [yes]
% poetry add discord.py
Creating virtualenv discord in /path/to/discord/.venv
Using version ^1.7.3 for discord.py

Updating dependencies
Resolving dependencies... (7.2s)

Writing lock file

Package operations: 9 installs, 0 updates, 0 removals

  • Installing idna (3.3)
  • Installing multidict (5.2.0)
  • Installing async-timeout (3.0.1)
  • Installing attrs (21.4.0)
  • Installing chardet (4.0.0)
  • Installing typing-extensions (4.0.1)
  • Installing yarl (1.7.2)
  • Installing aiohttp (3.7.4.post0)
  • Installing discord.py (1.7.3)

DMにレスポンスさせてみる

まずはシンプルな動作になりますが、DMの特定文言に対してレスさせてみます。以下のコードにDeveloper Portalで取得したTokenを設定します。

import discord

client = discord.Client()
TOKEN = ''

@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

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

client.run(TOKEN)
poetry run python3 bot.py

これでBotの動作が確認できました。

あとがき

Bot起動までの手順はやってみるとシンプルですが、何もわからない状態では戸惑うかもしれません。

Botを継続運用する場合はプロセスの常駐が必須となってきます。まずはローカル環境で必要に応じて動かすところから始めてみましょう。