这是我使用Discord机器人播放音乐的代码,但是我必须手动输入网址,但我想不出添加搜索功能的方法。
要播放音乐,我要在url中下载音频,然后使用ffmpeg播放音频。 如果您听不懂我会很乐意回答。
@client.command(pass_context=True)
async def play(ctx, url: str):
def check_queue():
Queue_infile = os.path.isdir("./Queue")
if Queue_infile is True:
DIR = os.path.abspath(os.path.realpath("Queue"))
length = len(os.listdir(DIR))
still_q = length - 1
try:
first_file = os.listdir(DIR)[0]
except:
print("No more queued song(s)\n")
queues.clear()
return
main_location = os.path.dirname(os.path.realpath(__file__))
song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
if length != 0:
print("Song done, playing next queued\n")
print(f"Songs still in queue: {still_q}")
song_there = os.path.isfile("song.mp3")
if song_there:
os.remove("song.mp3")
shutil.move(song_path, main_location)
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, 'song.mp3')
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.2
else:
queues.clear()
return
else:
queues.clear()
print("No songs were queued before the ending of the last song\n")
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
queues.clear()
print("Removed old song file")
except PermissionError:
print("Trying to delete song file, but it's being played")
return
Queue_infile = os.path.isdir("./Queue")
try:
Queue_folder = "./Queue"
if Queue_infile is True:
print("Removed old Queue Folder")
shutil.rmtree(Queue_folder)
except:
print("No old Queue folder")
voice = get(client.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'quiet': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("Downloading audio now\n")
ydl.download([url])
except:
c_path = os.path.dirname(os.path.realpath(__file__))
system("spotdl -f " + '"' + c_path + '"' + " -s " + url)
for file in os.listdir("./"):
if file.endswith(".mp3"):
name = file
print(f"Renamed File: {file}\n")
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
voice.source = discord.PCMVolumeTransformer(voice.source)
voice.source.volume = 0.07
nname = name.rsplit("-", 2)
await ctx.send(f"Playing: {nname[0]}")
print("playing\n")
忽略以下文本: erviervwuivvbutrjbbrgbiuoj24piofi; kdl,vv4j48v02i4oi; blk;'vdklcvefvijnvkwfjv,mwri3efjkdvdfvfhhv
答案 0 :(得分:1)
使用Youtube API的搜索功能在YouTube上进行搜索。它还会返回视频ID,然后您可以将其转换为链接。但是,为此创建另一个python文件。 希望这对您有帮助