1 year ago
#354776
Bắc Xuân
Getting NameError when add song to queue discord.py music bot
I'm coding a discord.py
music bot for my server. When I use the play command, it adds a song to the queue.
But when I try to add another second song to the queue or just check the queue, I get the following errors:
Traceback (most recent call last):
File "D:\Python3.10\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\VIETTEL\Desktop\python\god-tier tool.py", line 859, in play
queue_len = len(song_queue)
NameError: name 'song_queue' is not defined
This is my code for the project. Kindly let me know if I need to make any changes:
class MusicPlayer(commands.Cog):
def __init__(self, cm):
self.cm = cm
song_queue = []
async def check_queue(ctx):
if len(song_queue) > 0:
ctx.voice_client.stop()
await play_song(ctx, song_queue[0])
song_queue.pop(0)
async def search_song(amount, song, get_url=False):
info = await cm.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({'format': 'bestaudio', 'quiet': True}).extract_info(f'ytsearch{amount}:{song}', download=False, ie_key="YoutubeSearch"))
if len(info['entries']) == 0: return None
return [entry['webpage_url'] for entry in info['entries']] if get_url else info
async def play_song(ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url, execu)), after=lambda error:cm.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
@cm.command()
async def join(ctx):
if ctx.author.voice is None:
return await ctx.send("Bạn không ở trong 1 voice channel")
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.author.voice.channel.connect()
@cm.command()
async def leave(ctx):
if ctx.voice_client is not None:
return await ctx.voice_client.disconnect()
await ctx.send("U cant kick a stupid bot that even not in a voice channel")
@cm.command()
async def play(ctx, *, song=None):
async def play_song(ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url, executable="C:\\ffmpeg-5.0-essentials_build\\bin\\ffmpeg.exe")), after=lambda error:cm.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
async def search_song(amount, song, get_url=False):
info = await cm.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({'format': 'bestaudio', 'quiet': True}).extract_info(f'ytsearch{amount}:{song}', download=False, ie_key="YoutubeSearch"))
if len(info['entries']) == 0: return None
return [entry['webpage_url'] for entry in info['entries']] if get_url else info
if song is None:
return await ctx.send("Bạn phải chọn 1 bài để phát")
if ctx.voice_client is None:
return await ctx.send("Bot chưa trong 1 voice channel")
if not ("youtube.com/watch" in song or "youtu.be" in song):
await ctx.send("Đang seach, vui lòng đợi")
result = await search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Không thể phát bài hát này")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(song_queue)
song_queue.append(song)
return await ctx.send(f"Bài hát đã được thêm vào queue ở vị trí: {queue_len+1}.")
await play_song(ctx, song)
await ctx.send(f"Đang phát: {song}")
@cm.command()
async def search(ctx, *, song=None):
async def search_song(amount, song, get_url=False):
info = await cm.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({'format': 'bestaudio', 'quiet': True}).extract_info(f'ytsearch{amount}:{song}', download=False, ie_key="YoutubeSearch"))
if len(info['entries']) == 0: return None
return [entry['webpage_url'] for entry in info['entries']] if get_url else info
if song is None: return await ctx.send("Nhập từ khóa cần tím kiếm pls")
await ctx.send("Đang tìm kiếm...")
info = await search_song(10, song)
embed = discord.Embed(title=f"Kết quả time kiếm cho '{song}':", description="*Copy và dùng URL để .play chính xác hơn*\n", colour=discord.Colour.blue())
amount = 0
for entry in info["entries"]:
embed.description += f"[{entry['title']}]({entry['webpage_url']})\n"
amount += 1
embed.set_footer(text=f"Đang hiển thị {amount} kết quả đầu tiên.")
await ctx.send(embed=embed)
@cm.command()
async def queue(ctx): # display the current guilds queue
if len(song_queue) == 0:
return await ctx.send("Không có bài hát nào trong queue")
embed = discord.Embed(title="Quê-ue", description="", colour=discord.Colour.blue())
i = 1
for url in song_queue:
embed.description += f"{i}) {url}\n"
i += 1
embed.set_footer(text="Bot thuong dank ehe")
await ctx.send(embed=embed)
@cm.command()
async def skip(ctx):
if ctx.voice_client is None:
return await ctx.send("Không có bài hát nào đang được phát")
if ctx.author.voice is None:
return await ctx.send("Bot không ở trong 1 voice channel")
if ctx.author.voice.channel.id != ctx.voice_client.channel.id:
return await ctx.send("Anou nhầm bot rồi bạn ơi")
poll = discord.Embed(title=f"Vote skip bởi {ctx.author.name}#{ctx.author.discriminator}", description="**50+% vote để skip**", colour=discord.Colour.blue())
poll.add_field(name="Skip", value=":white_check_mark:")
poll.add_field(name="Nghe tiếp", value=":no_entry_sign:")
poll.set_footer(text="End vote sau 15s")
poll_msg = await ctx.send(embed=poll) # only returns temporary message, we need to get the cached message to get the reactions
poll_id = poll_msg.id
await poll_msg.add_reaction(u"\u2705") # yes
await poll_msg.add_reaction(u"\U0001F6AB") # no
await asyncio.sleep(15) # 15 seconds to vote
poll_msg = await ctx.channel.fetch_message(poll_id)
votes = {u"\u2705": 0, u"\U0001F6AB": 0}
reacted = []
for reaction in poll_msg.reactions:
if reaction.emoji in [u"\u2705", u"\U0001F6AB"]:
async for user in reaction.users():
if user.voice.channel.id == ctx.voice_client.channel.id and user.id not in reacted and not user.bot:
votes[reaction.emoji] += 1
reacted.append(user.id)
skip = False
if votes[u"\u2705"] > 0:
if votes[u"\U0001F6AB"] == 0 or votes[u"\u2705"] / (votes[u"\u2705"] + votes[u"\U0001F6AB"]) > 0.50: # 80% or higher
skip = True
embed = discord.Embed(title="Đã skip!", description="***Đã skip thành công, chuyển tiếp sang bài hát tiếp theo***", colour=discord.Colour.green())
if not skip:
embed = discord.Embed(title="No skip 4u", description="*No skip, return to wjbu*", colour=discord.Colour.red())
embed.set_footer(text="Voting has ended.")
await poll_msg.clear_reactions()
await poll_msg.edit(embed=embed)
if skip:
ctx.voice_client.stop()
@cm.command()
async def pause(ctx):
if ctx.voice_client.is_paused():
return await ctx.send("Bot đang pause-ed")
ctx.voice_client.pause()
await ctx.send("Đã dừng player")
@cm.command()
async def resume(ctx):
if ctx.voice_client is None:
return await ctx.send("Bot không ở trong 1 voice channel")
if not ctx.voice_client.is_paused():
return await ctx.send("Bot không bị pause-ed ehe")
ctx.voice_client.resume()
await ctx.send("Player đã được tiếp tục")
Is there any way to solve this error?
python
discord.py
nameerror
0 Answers
Your Answer