musicbotを構築し、discordサーバーに追加する。

はじめに

Discord には Musicbot という VC 内で音楽を聴ける bot が複数ある。
Rythmを使ってもいいのだが、自分で構築したいと思ったのでまとめる。

目次

1.python 実行環境を準備する

python はバージョンで文法が変わったりして、メジャーアップデートで正常に動作しなくなることがある。
この musicbot では 3.7.x が推奨されているので 3.7.x を構築するのにpyenvを使った。
公式に従い進めていく。

terminal
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
cd ~/.pyenv && src/configure && make -C src
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile
exec "$SHELL"
source ~/.bash_profile

これで pyenv を準備できたので 3.7.x をインストールする。
ひとまず 3.7.0 で構築したが好きなので構築してほしい

terminal
pyenv install 3.7.0
cd ~/MusicBot
pyenv local 3.7.0

これで MusicBot 内では 3.7.0 を使うように仕向けることができた。

2.musicbot を引っ張ってくる

musicbotはここを使った。
数ある musicbot の中では若干ラグはあるがここが一番音質がいい。

terminal
cd ~/
git clone https://github.com/Just-Some-Bots/MusicBot
cd MusicBot/
git checkout release-260819

3.実行環境の準備

ドキュメントに従い進めていく。

terminal
sudo apt-get install build-essential unzip -y
sudo apt-get install software-properties-common -y
sudo apt-get update -y
sudo apt-get install git ffmpeg libopus-dev libffi-dev libsodium-dev python3-pip
sudo apt-get upgrade -y
cd ~/MusicBot

python 内のパッケージを追加していくが、github に上がっているものだとエラーが出るので、requiments.txt を次のように書き換える

requiments.txt
1
2
3
4
5
6
7
8
9
10
11
12

- pynacl==1.2.1
- discord.py[voice]==1.2.5

+ cffi == 1.4.1
+ pynacl
+ discord.py[voice]
pip
youtube_dl
colorlog
+ cffi --only-binary all; sys_platform == 'win32'

書き換えたらインストールする

terminal
sudo python3 -m pip install -U -r requirements.txt

4.discord bot の準備

バックエンドは構築できたので、フロントエンド側の discordbot を作る。
Discord developerにアクセスし、New Applacations を選択。

名前を決めろと言われるので名前を決める。

ハンバーガーメニューから Bot を選択

bot を作成するかといわれるので yes を指定

Token 項目に Token が生成されるので、そのコードをメモしておく。

ハンバーガーメニューから OAuth2 を選択

scopes 内の bot をクリックし

bot permissions 内で許可したいものを選択。恐らくSend Messeages, Manege Messeages, Connect, Speakを許可しておけばいいんじゃないかな

scopes 内にある、http:からはじまるものを開く。
そうすると追加画面が出てくるので、欲しいサーバーに追加して準備は完了だ。

5.config ファイルを編集する

config ファイルを編集し、bot を動くようにする。
私はこのように編集した。

config/options.ini
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// This is the configuration file for MusicBot. You need to edit this file
// to setup the bot. Do not edit this file using Notepad as it ruins the
// formatting - use Notepad++ or a code editor like Visual Studio Code.

// For help, see: https://just-some-bots.github.io/MusicBot/

// これは MusicBot の設定ファイルです。
// ボットを設定するには、このファイルを編集する必要があります。
// Notepad++や Visual Studio Code などのコードエディタを使用してください。
// ヘルプは以下を参照してください: https://just-some-bots.github.io/MusicBot/

// To get IDs, enable Developer Mode (Options -> Settings -> Appearance)
// on Discord and then right-click the person/channel you want to get the
// channel of, then click 'Copy ID'. You can also use the 'listids' command.
// (http://i.imgur.com/GhKpBMQ.gif)

// ID を取得するには、Discord で開発者モード(オプション → 設定 → 外観)を有効にしてから、取得したい人・チャンネルを右クリックして、「ID をコピー」をクリックします。
// また、「listids」コマンドを使うこともできます。(http://i.imgur.com/GhKpBMQ.gif)

; HOW TO GET VARIOUS IDS:
; http://i.imgur.com/GhKpBMQ.gif
; Enable developer mode (options, settings, appearance), right click the object you want the id of, and click Copy ID
; This works for basically everything you would want the id of (channels and users). For roles you have to right click a role mention.

// 様々な ID を取得する方法 http://i.imgur.com/GhKpBMQ.gif
// 開発者モードを有効にし(オプション、設定、外観)、ID を取得したいオブジェクトを右クリックして、「ID をコピー」をクリックします。
// ロールの場合は、ロールを右クリックしてください。

[Credentials]
// This is your Discord bot account token.
// Find your bot's token here: https://discordapp.com/developers/applications/me/
// Create a new application, with no redirect URI or boxes ticked.
// Then click 'Create Bot User' on the application page and copy the token here.

// これは、あなたの Discord ボットアカウントのトークンです。あなたのボットのトークンはこちらで確認してください: https://discordapp.com/developers/applications/me/
// リダイレクト URI やボックスにチェックを入れずに、新しいアプリケーションを作成します。次に、アプリケーションページで「Create Bot User」をクリックし、トークンをここにコピーします。

Token = bot_token_id

// The bot supports converting Spotify links and URIs to YouTube videos and
// playing them. To enable this feature, please fill in these two options with valid
// details, following these instructions: https://just-some-bots.github.io/MusicBot/using/spotify/

// このボットは、Spotify のリンクや URI を YouTube の動画に変換して再生する機能をサポートしています。
// この機能を有効にするには、以下の指示に従って、有効な詳細情報を以下の 2 つのオプションに入力してください: https://just-some-bots.github.io/MusicBot/using/spotify/

Spotify_ClientID =
Spotify_ClientSecret =

[Permissions]
// This option determines which user has full permissions and control of the bot.
// You can only set one owner, but you can use permissions.ini to give other
// users access to more commands.
// Setting this option to 'auto' will set the owner of the bot to the person who
// created the bot application, which is usually what you want. Else, change it
// to another user's ID.

// このオプションは、どのユーザーがボットの完全なパーミッションとコントロールを持つかを決定します。
// オーナーは 1 人しか設定できませんが、permissions.ini を使って他のユーザーにも多くのコマンドへのアクセス権を与えることができます。
// このオプションを'auto'に設定すると、ボットの所有者は、ボットアプリケーションを作成した人に設定されますが、これは通常必要なことです。
// それ以外の場合は、他のユーザーの ID に変更してください。

OwnerID = auto

// This option determines which users have access to developer-only commands.
// Developer only commands are very dangerous and may break your bot if used
// incorrectly, so it's highly recommended that you ignore this option unless you
// are familiar with Python code.

// このオプションは、どのユーザーが開発者専用のコマンドにアクセスできるかを決定します。
// 開発者専用コマンドは非常に危険で、間違った使い方をするとボットを壊してしまう可能性があるため、Python コードに精通していない限り、このオプションは無視することを強くお勧めします。

DevIDs =

// This option determines if the bot should respond to other any other bots
// put bot ID's here seperated with spaces
// Any id you put here the bot WILL respond to.

// このオプションは、ボットが他のどのようなボットに対しても応答するかどうかを決定します。

BotExceptionIDs =

[Chat]
// Determines the prefix that must be used before commands in the Discord chat.
// e.g if you set this to *, the play command would be triggered using *play.

// Discord チャットのコマンドの前に使用するプレフィックスを決定します。例えば、これを*に設定すると、play コマンドは*play で起動します。

CommandPrefix = !

// Restricts the bot to only listening to certain text channels. To use this, add
// the IDs of the text channels you would like the bot to listen to, seperated by
// a space.

// ボットが特定のテキストチャンネルのみを聞くように制限します。
// この機能を使うには、ボットに聞かせたいテキストチャンネルの ID を、スペースで区切って追加します。

- BindToChannels =

+ BindToChannels = bot-control-channel-id

// Changes the behavior of BindToChannels. Normally any messages sent to a channel not in
// BindToChannels will be ignored. This option allows servers that do not have any bound
// channels while other server have some defined to still use commands in any channel with
// the Music Bot. Setting this to yes when there are no bound channels does nothing.

// BindToChannels の動作を変更します。
// 通常、BindToChannels に含まれていないチャンネルに送信されたメッセージは無視されます。
// このオプションは、チャンネルが設定されていないサーバーと、チャンネルが設定されているサーバーの間で、どのチャンネルのコマンドでもミュージック・ボットで使えるようにします。
// バインドされたチャンネルがないときにこのオプションを yes に設定しても、何の効果もありません。

AllowUnboundServers = no

// Allows the bot to automatically join servers on startup. To use this, add the IDs
// of the voice channels you would like the bot to join on startup, seperated by a
// space. Each server can have one channel. If this option and AutoSummon are
// enabled, this option will take priority.

// 起動時にボットが自動的にサーバーに参加するようにします。
// ボットの起動時に参加させたい音声チャンネルの ID をスペースで区切って追加してください。
// 各サーバーには 1 つのチャンネルを設定できます。
// このオプションと AutoSummon が有効になっている場合、このオプションが優先されます。

AutojoinChannels = bot-join-voice-channel-id

// Send direct messages for now playing messages instead of sending them into the guild. They are
// sent to the user who added the media being played. Now playing messages for automatic entries
// are unaffected and follows NowPlayingChannels config. The bot will not delete direct messages.

// 今プレイ中のメッセージは、ギルドに送るのではなく、ダイレクトメッセージを送ってください。
// 再生されているメディアを追加したユーザーに送られます。
// 自動エントリーの再生中メッセージは影響を受けず、NowPlayingChannels 設定に従います。
// ボットはダイレクトメッセージを削除しません。

DMNowPlaying = no

// Disable now playing messages for entries automatically added by the bot, via the autoplaylist.

// ボットが自動再生リストを使って自動的に追加したエントリーの再生中メッセージを無効にしました。

DisableNowPlayingAutomatic = no

// For now playing messages that are unaffected by DMNowPlaying and DisableNowPlayingAutomatic,
// determine which channels the bot is going to output now playing messages to. If this is not
// specified for a server, now playing message for manually added entries will be sent in the same
// channel that users used the command to add that entry, and now playing messages for automatically
// added entries will be sent to the same channel that the last now playing message was sent to if
// this is not specified for a server if possible. Specifying more than one channel for a server
// forces the bot to pick only one channel from the list to send messages to.

// DMNowPlaying や DisableNowPlayingAutomatic の影響を受けない再生中のメッセージについては、ボットが再生中のメッセージをどのチャンネルに出力するかを決定します。
// サーバにこれが指定されていない場合、手動で追加されたエントリの再生メッセージは、ユーザがそのエントリを追加するためにコマンドを使用したのと同じチャネルに送信され、自動で追加されたエントリの再生メッセージは、最後の再生メッセージが送信されたのと同じチャネルに送信されます。
// サーバーに複数のチャンネルを指定すると、ボットはリストの中から 1 つのチャンネルだけを選んでメッセージを送信します。

NowPlayingChannels =

// The bot would try to delete (or edit) previously sent now playing messages by default. If you
// don't want the bot to delete them (for keeping a log of what has been played), turn this
// option off.

// ボットは、以前に送信した再生中のメッセージをデフォルトで削除(または編集)しようとします。
// ボットに削除させたくない場合は、このオプションをオフにしてください(再生されたメッセージのログを残すため)。

DeleteNowPlaying = yes

[MusicBot]
// The volume of the bot, between 0.01 and 1.0.

// 0.01 ~ 1.0 の範囲で設定します。

DefaultVolume = 0.25

// Only allows whitelisted users (in whitelist.txt) to use commands.
// WARNING: This option has been deprecated and will be removed in a future version
// of the bot. Use permissions.ini instead.

// ホワイトリスト(whitelist.txt)に登録されているユーザーにのみ、コマンドの使用を許可します。
// 警告: このオプションは非推奨であり、ボットの将来のバージョンでは削除される予定です。
// 代わりに permissions.ini を使用してください。

WhiteListCheck = no

// The number of people voting to skip in order for a song to be skipped successfully,
// whichever value is lower will be used. Ratio refers to the percentage of undefeaned, non-
// owner users in the channel.

// 曲が正常にスキップされるためにスキップに投票する人数で、値が小さい方が採用されます。
// 比率とは、チャンネルの中で、所有者ではない未定義のユーザーの割合を指します。

SkipsRequired = 4
SkipRatio = 0.5

// Determines if downloaded videos will be saved to the audio_cache folder. If this is yes,
// they will not be redownloaded if found in the folder and queued again. Else, videos will
// be downloaded to the folder temporarily to play, then deleted after to avoid filling space.

// ダウンロードしたビデオを audio_cache フォルダに保存するかどうかを指定します。
// この設定が「はい」の場合、フォルダ内にビデオが見つかり、再度キューに入れられても、再ダウンロードされません。
// そうでない場合は、ビデオは一時的にフォルダにダウンロードされて再生されますが、スペースがいっぱいにならないように、その後削除されます。

SaveVideos = yes

// Mentions the user who queued a song when it starts to play.

// 曲の再生開始時に、キューに入れたユーザーをメンションします。

NowPlayingMentions = no

// Automatically joins the owner's voice channel on startup, if possible. The bot must be on
// the same server and have permission to join the channel.

// 可能であれば、起動時に自動的にオーナーの音声チャンネルに参加します。
// ボットは同じサーバにいて、チャンネルに参加する権限を持っている必要があります。

AutoSummon = yes

// Start playing songs from the autoplaylist.txt file after joining a channel. This does not
// stop users from queueing songs, you can do that by restricting command access in permissions.ini.

// チャンネルに参加した後、autoplaylist.txt ファイルから曲の再生を開始する。
// これは、ユーザーが曲をキューに入れることを妨げるものではありません。
// これは、permissions.ini でコマンドアクセスを制限することで可能です。

UseAutoPlaylist = yes

// Sets if the autoplaylist should play through songs in a random order when enabled. If no,
// songs will be played in a sequential order instead.

// オートプレイリストを有効にしたときに、ランダムな順序で曲を再生するかどうかを設定します。
// 設定しない場合は、連続した順序で再生されます。

AutoPlaylistRandom = yes

// Pause the music when nobody is in a voice channel, until someone joins again.

// ボイスチャンネルに誰もいないとき、誰かが再び参加するまで音楽を一時停止します。

AutoPause = yes

// Automatically cleanup the bot's messages after a small period of time.

// 一定期間後にボットのメッセージを自動的にクリーンアップします。

DeleteMessages = yes

// If this and DeleteMessages is enabled, the bot will also try to delete messages from other
// users that called commands. The bot requires the 'Manage Messages' permission for this.

// この機能と DeleteMessages を有効にすると、ボットはコマンドを呼び出した他のユーザからのメッセージも削除しようとします。
// これには、「メッセージの管理」権限が必要です。

DeleteInvoking = no

// Regularly saves the queue to the disk. If the bot is then shut down, the queue will
// resume from where it left off.

// 定期的にキューをディスクに保存します。
// ボットがシャットダウンされると、キューは中断されたところから再開されます。
PersistentQueue = yes

// Determines what messages are logged to the console. The default level is INFO, which is
// everything an average user would need. Other levels include CRITICAL, ERROR, WARNING,
// DEBUG, VOICEDEBUG, FFMPEG, NOISY, and EVERYTHING. You should only change this if you
// are debugging, or you want the bot to have a quieter console output.

// コンソールにどのようなメッセージを記録するかを決定します。デフォルトのレベルは INFO で、平均的なユーザーが必要とするものです。
// その他のレベルには、CRITICAL、ERROR、WARNING、DEBUG、VOICEDEBUG、FFMPEG、NOISY、EVERYTHING があります。
// このレベルを変更するのは、デバッグをしている場合や、ボットのコンソール出力をより静かにしたい場合のみです。

- DebugLevel = INFO

+ DebugLevel = EVERYTHING

// Specify a custom message to use as the bot's status. If left empty, the bot
// will display dynamic info about music currently being played in its status instead.

// ボットのステータスとして使用するカスタムメッセージを指定します。
// 空にすると、現在再生されている音楽の動的な情報がステータスに表示されます。

StatusMessage =

// Write what the bot is currently playing to the data/<server id>/current.txt FILE.
// This can then be used with OBS and anything else that takes a dynamic input.

// ボットが現在再生している曲を data/<server id>/current.txt FILE に書き込みます。
// これは、OBS やその他の動的な入力を取るもので使用できます。

WriteCurrentSong = no

// Allows the person who queued a song to skip their OWN songs instantly, similar to the
// functionality that owners have where they can skip every song instantly.

// オーナーがすべての曲を瞬時にスキップできる機能と同様に、キューに入れた人が自分の曲を瞬時にスキップできるようにします。

AllowAuthorSkip = yes

// Enables experimental equalization code. This will cause all songs to sound similar in
// volume at the cost of higher processing consumption when the song is initially being played.

// 実験的なイコライズコードを有効にします。
// これにより、すべての曲の音量が似たようなものになりますが、曲を最初に再生するときの処理消費が大きくなります。

UseExperimentalEqualization = no

// Enables the use of embeds throughout the bot. These are messages that are formatted to
// look cleaner, however they don't appear to users who have link previews disabled in their
// Discord settings.

// ボット全体でエンベッドの使用を可能にします。
// これは、よりきれいに見えるようにフォーマットされたメッセージですが、Discord の設定でリンクのプレビューを無効にしているユーザーには表示されません。

UseEmbeds = yes

// The amount of items to show when using the queue command.

// queue コマンドを使用する際に表示するアイテムの量を指定します。

QueueLength = 10

// Remove songs from the autoplaylist if an error occurred while trying to play them.
// If enabled, unplayable songs will be moved to another file and out of the autoplaylist.
// You may want to disable this if you have internet issues or frequent issues playing songs.

// 再生しようとしてエラーが発生した曲を自動再生リストから削除します。
// この機能を有効にすると、再生できない曲は別のファイルに移動され、自動再生リストから外れます。
// インターネットの問題や、曲の再生に頻繁に問題が発生する場合は、この機能を無効にするとよいでしょう。

RemoveFromAPOnError = yes

// Whether to show the configuration for the bot in the console when it launches.

// ボットの起動時に、コンソールにボットの設定を表示するかどうか。

ShowConfigOnLaunch = no

// Whether to use leagcy skip behaviour. This will change it so that those with permission
// do not need to use "skip f" to force-skip a song, they will instead force-skip by default.

// リーグシースキップの動作を使用するかどうか。
// これにより、権限のある人が曲を強制的にスキップするために "skip f" を使う必要がなくなり、代わりにデフォルトで強制的にスキップするように変更されます。

LegacySkip = no

// Leave servers if the owner is not found in them.

// サーバーの中にオーナーがいない場合は、サーバーを残します。

LeaveServersWithoutOwner = no

// Use command alias defined in aliases.json.

// aliases.json で定義されたコマンドエイリアスを使用します。

UseAlias = yes

[Files]
// Path to your i18n file. Do not set this if you do not know what it does.

// 国際化ファイルへのパス。これが何をするものかわからない場合は、設定しないでください。

i18nFile =

5.起動する

./run.shで起動を始めるのだが、起動時に

terminal
ModuleNotFoundError: No module named 'hoge'

のようなエラーが大抵出るので、このエラーが出なくなるまで繰り返す。hoge が足りてないパッケージなので

terminal
pip install hoge

のように書いてインストールしていく。
起動が完了し、bot がオンラインになったことが確認でき、!play title で再生されたら成功だ。
使えるコマンドはここにある。

6.デーモン化する

systemd を用いて、バックグラウンドで動くようにする。

/etc/systemd/system/musicbot.service
1
2
3
4
5
6
7
8
9
10
11
12
[Unit]
Description=MusicBot
After=network.target

[Service]
Type=simple
WorkingDirectory=/home/musicbot/MusicBot
ExecStart=/home/musicbot/.pyenv/shims/python /home/musicbot/MusicBot/run.py
User=musicbot

[Install]
WantedBy=multi-user.target

python の実体の場所は which コマンドで引っ張ってこれる。

terminal
which python
/home/musicbot/.pyenv/shims/python

コメント