在 discord.py 音乐机器人中添加搜索功能



这是我使用 discord 机器人播放音乐的代码,但我必须手动输入 url,而且我找不到添加搜索功能的方法。

要播放音乐,我正在 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 queuedn")
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 songn")

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 nown")
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("playingn")

忽略以下文本: Erviervwuivvbutrjbbrgbiuoj24piofi;kdl,vv4j48v02i4oi;哗啦啦;vdklcvefvijnvkwfjv,mwri3efjkdvdfvhbvuvriurfuivfubvjfvlkjdfvfjvkflvkjdfvvdfljvwrjkgvlgrvhjwrvkjwrgvkrjhbhjrvhiurvrvjkfjv

使用 YoutubeAPI 的搜索功能在 Youtube 上进行搜索。它还返回视频ID,然后您可以将其转换为链接。不过,为此制作另一个 python 文件。 希望这有帮助

最新更新