我最近用默认的kick和ban命令以及其他一些东西创建了一个机器人。但是,我真正想添加的一件事是音乐命令。例如,.play <song name>
将是一首选定的歌曲。 .pause
和.stop
将暂停并停止音乐播放。视频的任何提示或链接将不胜感激。预先谢谢你。
答案 0 :(得分:0)
您在这里。不幸的是,我不知道如何使歌曲停止或暂停,但是如果我想知道如何去做,我会编辑这个答案。
import discord
import os
import youtube_dl
import asyncio
from discord.ext import commands
TOKEN = 1234567890 #change this to your token
client = commands.Bot(command_prefix = ".") #Here you can change prefix for commands
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
def endSong(guild, path):
os.remove(path)
@client.command(pass_context=True)
async def play(ctx, url):
if not ctx.message.author.voice:
await ctx.send('You are not connected to a voice channel') #message when you are not connected to any voice channel
return
else:
channel = ctx.message.author.voice.channel
voice_client = await channel.connect()
guild = ctx.message.guild
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
file = ydl.extract_info(url, download=True)
path = str(file['title']) + "-" + str(file['id'] + ".mp3")
voice_client.play(discord.FFmpegPCMAudio(path), after=lambda x: endSong(guild, path))
voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)
await ctx.send(f'**Music: **{url}') #sends info about song playing right now
client.run(TOKEN)
如果您愿意,可以在歌曲/音乐停止播放后使机器人离开语音通道。在代码末尾,但在 client.run(TOKEN) !
之前添加此代码!while voice_client.is_playing():
await asyncio.sleep(1)
else:
await voice_client.disconnect()
print("Disconnected")
.play url -播放url中的歌曲(示例 .play https://www.youtube.com/watch?v=dQw4w9WgXcQ)