今天要來教怎麼做簡單的播放音樂功能啦
自己研究的時候本來還覺得很困難,後來也發現其實很簡單
今日都以Cog內的寫法為主喔

準備

今天會用到神奇的下載模組pytubefix
用fix是因為原本的失效了,作者好像也沒有要更新

1
pip install pytubefix

還有discord的小小附加套件(嗎)
我也不太確定是什麼東西,反正裝就對了

1
pip install discord.py[voice]

再來就是超級常用的ffmpeg,自行下載
只要放在機器人資料夾內就可以了,推薦路徑為從bot.py出發ffmpeg/bin/ffmpeg.exe

加入和離開頻道

加入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@commands.command()
async def join(self,ctx)
# 從機器人的所有語音連線中取得本伺服器的連線
# utils是Discord附送的小功能,與機器人操作沒有任何關係
voice = discord.utils.get(self.bot.voice_clients, guild=ctx.guild)

# 如果使用者目前沒有加入語音
if ctx.author.voice == None:
await ctx.send('目前沒有加入語音')

# 如果機器人已經在伺服器內的語音
elif not voice == None:
await ctx.send('機器人已經在某一頻道內了')

else:
voiceChannel = ctx.author.voice.channel
voiceChannel.connect()

離開

1
2
3
4
5
6
7
8
@commands.command()
async def leave(self,ctx:commands.Context):
voice = discord.utils.get(self.bot.voice_clients, guild = ctx.guild)
# 如果機器人本來就沒有連線
if voice == None:
await ctx.send('機器人沒有在語音頻道裡')
else:
await voice.disconnect(force=True)

取得音樂並播放

Discord音訊物件介紹

discord.FFmpegPCMAudio是Discord專用的音訊物件,使用ffmpeg編碼後變成可以透過機器人播放的音訊
寫法為discord.FFmpegPCMAudio(source=檔案來源,executable=ffmpeg路徑)
注意此處路徑須以bot.py為出發而非cog檔案

取得音樂部分

1
2
3
4
5
6
7
8
9
10
11
from pytubefix import Youtube

@commands.command()
async def play(self,ctx,url):
# 此處省略是否連線的偵測以求簡便,若需要可使用與leave相同邏輯,可自行加上
voice = discord.utils.get(self.bot.voice_clients, guild = ctx.guild)

# 將網址內容下載為song.mp3
Youtube(url).streams.get_audio_only().download(mp3=True,filename='song')
# 播放轉化為特殊物件的音訊
voice.play(discord.FFmpegPCMAudio(source='time.mp3',executable='ffmpeg/bin/ffmpeg.exe'))

暫停、繼續和停止

此處一樣省略偵測邏輯,可參考離開相同邏輯

1
2
3
4
5
  async def pause(self,ctx):

voice = discord.utils.get(self.bot.voice_clients, guild = ctx.guild)

voice.pause()

三項操作的語法相同,將函式名稱和voice的方法替換成pause、resume和stop即可


只要使用!play接網址,就可以輕鬆讓機器人播放音樂了
至於每個指令的其他提示文字可自行變化增減