How to use nexwave.ext spotify on discord musicbot? - spotify

I have a Discord musicbot and it works with YT but not with spotify.
I tried using the inbuilt spotify module of nextwave.ext, but it's not working, it just gives me an error (400, 'Bad Request')
Here's my code:
import ...
is_spotify = False
#bot.slash_command(guild_ids=serverID,name="play",description="Mach lustige Musik an :D")
async def play(interaction: Interaction,
search: str = SlashOption(description="Titel/URL")):
global is_spotify
if validators.url(search):
if search.startswith(tuple(yt_urls)):
print("YT-URL erkannt!")
info_dict = ydl.extract_info(search, download=False)
search = info_dict.get('title', None)
elif search.startswith(tuple(spotify_urls)):
print("Spotify-URL erkannt!")
is_spotify = True
else:
await interaction.send("Ungültige URL",ephemeral=True)
if not interaction.user.voice:
return await interaction.send("Du musst in einem Channel sein!",
ephemeral=True)
if not is_spotify:
track = await nextwave.YouTubeTrack.search(query=search,
return_first=True)
if is_spotify:
try:
track = await spotify.SpotifyTrack.search(query=search,return_first=True)
print(track)
except Exception as e:
await interaction.send("Bitte benutze eine korrekte Spotify URL",
ephemeral=True)
return print(e)
if not interaction.guild.voice_client:
vc: nextwave.Player = await interaction.user.voice.channel.connect(cls=nextwave.Player)
else:
vc: nextwave.Player = interaction.guild.voice_client
await vc.move_to(interaction.user.voice.channel)
if vc.queue.is_empty and not vc.is_playing():
await vc.play(track)
await interaction.send(f"Spielt jetzt: `{track.title}`",
ephemeral=True)
else:
await vc.queue.put_wait(search)
await interaction.send(f"`{track.title}` zur Warteschlange hinzugefügt.",
ephemeral=True)
global vc_interaction
vc_interaction = interaction
if vc.loop:
return
setattr(vc,
"loop",
False)
Output I got:
Spotify-URL erkannt!
(400, 'Bad Request')
And it's not playing.
How do I fix this?

Related

Discord Bot not playing audio when visually it is

I am making a Discord Bot that plays music when I give it the name of a song.
Whenever I give it the ".play" command, the Discord app shows that the bot is in fact playing audio, I just don't hear any.
I tried multiple times with different music, however I recieved the same problem.
Here is my code:
import discord
from discord.ext import commands
import wavelink
client = commands.Bot(command_prefix = ".", intents = discord.Intents.all())
class CustomPlayer (wavelink.Player):
def __init__(self):
super().__init__()
self.queue = wavelink.Queue()
#client.event
async def on_ready():
client.loop.create_task(connect_nodes()) #HTTPS and Websocket operations
async def connect_nodes(): #Helper function
await client.wait_until_ready()
await wavelink.NodePool.create_node(
bot = client ,
host = "127.0.0.1" ,
port = 2333 ,
password = "youshallnotpass"
)
#client.event
async def on_wavelink_node_ready(node = wavelink.Node):
print(f"Node: <{node.identifier}> is ready!")
#client.command()
async def connect(ctx):
vc = ctx.voice_client
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send("Please join a channel to connect.")
if not vc:
await ctx.author.voice.channel.connect(cls = CustomPlayer())
else:
await ctx.send("The bot is already connected to a voice channel.")
#client.command()
async def disconnect(ctx):
vc = ctx.voice_client
if vc:
await vc.disconnect()
else:
await ctx.send("Bot is not connected to a voice channel.")
#client.command()
async def play(ctx, *, search: wavelink.YouTubeTrack):
vc = ctx.voice_client #represents a discord voice connection
if not vc:
custom_player = CustomPlayer()
vc: CustomPlayer = await ctx.author.voice.channel.connect(cls = custom_player)
if vc.is_playing():
vc.queue.put(item = search)
await ctx.send(embed = discord.Embed(
title = search.title,
url = search.uri,
description = f"Queued {search.title} in {vc.channel}"
))
else:
await vc.play(search)
await ctx.send(embed = discord.Embed(
title = search.title,
url = search.uri,
description = f"Playing {vc.source.title} in {vc.channel}"))

How do I stream and queue up songs in a discord bot?

What I want to do?
Search a music by its name
Stream the music instead of downloading and playing it
Queue up songs if one song is already playing
Output to the author "Playing [url]"
My code:
async def play(ctx, url : str):
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
except PermissionError:
await ctx.send("Wait for the current playing music to end or use the 'stop' command")
return
channel = ctx.author.voice.channel
'''voiceChannel = discord.utils.get(ctx.guild.voice_channels, name=channel.name)'''
voice_client = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice_client == None:
await channel.connect()
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"))
This code is very basic. It uses yt-dl and works only if you paste a url of the YouTube video.
It downloads the song and plays it which takes time for the bot to play the music
It cannot queue up songs.
It is my first time making a bot and I'm not really experienced in reading and understanding the docs as I'm just getting started in making python projects.
this is how here at Rage bots we make our music commands and its very usefull
import discord
from discord.ext import commands
from random import choice
import string
from discord.ext.commands.cooldowns import BucketType
import asyncio
import youtube_dl
import pafy
import datetime
from discord_slash import cog_ext, SlashContext
x = datetime.datetime.now()
from ult import *
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.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(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
#commands.command()
async def pause(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
ctx.voice_client.pause()
await ctx.send("*Paused -* ⏸️")
#commands.command()
async def resume(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
ctx.voice_client.resume()
await ctx.send("*Resuming -* ▶️")
#commands.command()
#commands.is_owner()
#commands.cooldown(1, 5, commands.BucketType.user)
async def oskip(self, ctx):
commandd = "oskip"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
await ctx.send("skipping")
ctx.voice_client.stop()
await self.check_queue(ctx)
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def join(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "join"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel, please connect to the channel you want the bot to join.")
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.author.voice.channel.connect()
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def leave(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "leave"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if ctx.voice_client is not None:
return await ctx.voice_client.disconnect()
await ctx.send("I am not connected to a voice channel.")
#commands.command()
async def play(self, ctx, *, song=None):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "play"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def search(self, ctx, *, song=None):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "search"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if song is None: return await ctx.send("You forgot to include a song to search for.")
await ctx.send("Searching for song, this may take a few seconds.")
info = await self.search_song(5, song)
embed = discord.Embed(title=f"Results for '{song}':", description="*You can use these URL's to play an exact song if the one you want isn't the first result.*\n", colour=discord.Color.green())
amount = 0
for entry in info["entries"]:
embed.description += f"[{entry['title']}]({entry['webpage_url']})\n"
amount += 1
embed.set_footer(text=f"Displaying the first {amount} results.")
await ctx.send(embed=embed)
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def queue(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else: # display the current guilds queue
commandd = "queue"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if len(self.song_queue[ctx.guild.id]) == 0:
return await ctx.send("There are currently no songs in the queue.")
embed = discord.Embed(title="Song Queue", description="", colour=discord.Color.green().dark_gold())
i = 1
for url in self.song_queue[ctx.guild.id]:
embed.description += f"{i}) {url}\n"
i += 1
embed.set_footer(text="Thanks for using me!")
await ctx.send(embed=embed)
#commands.command()
#commands.has_permissions(administrator=True)
#commands.cooldown(1, 5, commands.BucketType.user)
async def adskip(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "adskip"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
await ctx.send("skipping")
ctx.voice_client.stop()
await self.check_queue(ctx)
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def skip(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "skip"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if ctx.voice_client is None:
return await ctx.send("I am not playing any song.")
if ctx.author.voice is None:
return await ctx.send("You are not connected to any voice channel.")
if ctx.author.voice.channel.id != ctx.voice_client.channel.id:
return await ctx.send("I am not currently playing any songs for you.")
poll = discord.Embed(title=f"Vote to Skip Song by - {ctx.author.name}#{ctx.author.discriminator}", description="**80% of the voice channel must vote to skip for it to pass.**", colour=discord.Color.blue())
poll.add_field(name="Skip", value=":white_check_mark:")
poll.add_field(name="Stay", value=":no_entry_sign:")
poll.set_footer(text="Voting ends in 15 seconds.")
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.79: # 80% or higher
skip = True
embed = discord.Embed(title="Skip Successful", description="***Voting to skip the current song was succesful, skipping now.***", colour=discord.Color.green())
if not skip:
embed = discord.Embed(title="Skip Failed", description="*Voting to skip the current song has failed.*\n\n**Voting failed, the vote requires at least 80% of the members to skip.**", colour=discord.Color.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()
await self.check_queue(ctx)
def setup(bot):
bot.add_cog(music(bot))
just make sure to get rid of the blacklist part
this has some fun stuff to that you didnt ask for but might be use full
if you need help setting it up add me on discord
RageWire#0001
-from Rage bot head dev and support team

Why is discord.Client.wait_for is asking for event when it has one?

The problem i'm having is the code never getting through "0004" since it gets stuck on wait_for which wants additional positional argument: 'event', which should be the 'message' in bracket right next to it from what I've seen on examples from discord.py site & inside the code itself.
'''
class Test(commands.Cog):
def __init__(self, spreadsheeter):
self.spreadsheeter = spreadsheeter
#commands.command()
async def apply(self, ctx):
a_list = []
submit_channel = spreadsheeter.get_channel(718698172293316608)
channel = await ctx.author.create_dm()
def check(m):
return m.content is not None and m.channel == channel
for question in q_list:
print("0001")
sleep(.5)
print("0002")
await channel.send(question)
print("0003")
msg = await Client.wait_for('message', timeout=60, check=check)
print("0004")
a_list.append(msg.content)
print("0005")
submit_wait = True
print("0006")
while submit_wait:
print("0007")
await channel.send("End of questions 'submit' to finish.")
print("0008")
msg = await Client.wait_for("message", check=check)
print("0009")
if "submit" in msg.content.lower():
print("0010")
submit_wait =False
print("0011")
answers = "\n".join(f"{a}. {b}" for a, b in enumerate(a_list, 1))
print("0012")
submit_msg = f"Apllication from {msg.author} \nThe answers are:\n{answers}"
print("0013")
await submit_channel.send(submit_msg)
print("0014")
Error:
What I've unsuccessfully tried:
discord.client.wait_for('message', check=check)
Error: discord.client has no attribute 'wait_for'
Same for discord.member, ctx.member, ctx.client
Replacing "message" to 'message' (doesn't change anything)
Moving around the position of 'message'
Raises ton of other errors...
Giving the line bracket at start (self, "message", check=check)
Error: 'Test' object has no attribute 'loop'
#client.event instead of cog style commands.command
Error: Unresolved reference 'client'
Intent of the code:
Be called from DM as a command, then start a series of questions from q_list in that DM and then store them into a_list. Then after its done it should submit the a_list into as submit_msg into discord channel.
What it does so far?:
Asks first question from q_list
q_list = [
"Question one",
"Question two ha-ha-haaa",
"Question three ha-ha-haaa"
]
"""
After that it immediately after trying to await answer gives error.
2 Things at the beginning, you should only make a dm channel if there isn't any yet.
ctx.author.chreate_dm() doesn't return a channel, so instead of assigning the dm channel to channel you can check it's in the right channel by using ctx.author.dm_channel
#commands.command()
async def apply(self, ctx):
a_list = []
submit_channel = self.spreadsheeter.get_channel(718698172293316608)
if not ctx.author.dm_channel:
await ctx.author.create_dm()
def check(m):
return m.content is not None and m.channel == ctx.author.dm_channel
Instead of Client use spreadsheeter as that is your client
msg = await self.spreadsheeter.wait_for('message', timeout=60, check=check)
Figured it out, the thing being is it might work in cogs, but I think it won't or something is just missing...
The way i made it to work is to use it in
#Client.event (in my case #spreadsheeter.event)
Instead of ctx. I used payload.
"""
#spreadsheeter.event
async def on_raw_reaction_add(payload):
print("Hell-Yeah")
message_id = payload.message_id
if message_id == 739153263907176480:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, spreadsheeter.guilds)
print (payload.emoji.name)
if payload.emoji.name == "No1":
role = discord.utils.find(lambda r: r.name == 'RAIDERS', guild.roles)
print(role)
if role in payload.member.roles:
print("You really want to leave?")
else:
print("Kick")
await payload.member.kick()
elif payload.emoji.name == "Yes1":
print("Yo, we got a potential raider over here..")
channel = await payload.member.create_dm()
await channel.send("This is still Work/Bot is under Development (Not actuall application yet).")
await channel.send("Whenever you are ready, please start replaying to the questions.")
print("0000")
submit_channel = spreadsheeter.get_channel(718698172293316608)
if not payload.member.dm_channel:
await payload.member.create_dm()
channel = payload.member.dm_channel
print(channel)
def check(m):
return m.content is not None and m.channel == channel
for question in q_list:
print("0001")
sleep(.5)
print("0002")
await channel.send(question)
print("0003")
msg = await spreadsheeter.wait_for(event='message', timeout=60, check=check)
print("0004")
a_list.append(msg.content)
print("0005")
submit_wait = True
print("0006")
while submit_wait:
print("0007")
await channel.send("End of questions 'submit' to finish.")
print("0008")
msg = await spreadsheeter.wait_for("message", timeout=60, check=check)
print("0009")
if "submit" in msg.content.lower():
print("0010")
submit_wait = False
print("0011")
answers = "\n".join(f"{a}. {b}" for a, b in enumerate(a_list, 1))
print("0012")
submit_msg = f"Apllication from {msg.author} \nThe answers are:\n{answers}"
print("0013")
await submit_channel.send(submit_msg)
print("0014")
elif payload.emoji.name == "Need_more_info":
print("Yo, we got a potential diplomat over here..")
channel = await payload.member.create_dm()
await channel.send("This is still Work/Bot is under Development (Not actuall application yet).")
await channel.send("Whenever you are ready, please start with \n_apply")
"""
It still doesn't have the handling for multiple users, but works fine with one at a time at this moment, which solves the original problem of wait_for not waiting for anything else then timeout to run out.

discord.py stop command work but doesn't clear the queue

-----Play Section this works well-----
async def play(self, ctx, *, arg):
await ctx.channel.purge(limit=1)
try: channel = ctx.author.voice.channel
except: await ctx.send("❌ You're not connected to any channel!", delete_after = 5.0)
else:
channel = ctx.author.voice.channel
voice = get(self.bot.voice_clients, guild=ctx.guild)
song = Music.search(ctx.author.mention, arg)
------queue section------
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
if not voice.is_playing():
self.song_queue[ctx.guild] = [song]
self.message[ctx.guild] = await ctx.send(embed=song['embed'])
voice.play(discord.FFmpegPCMAudio(song['source'], **Music.FFMPEG_OPTIONS), after=lambda e: self.play_next(ctx))
voice.is_playing()
else:
self.song_queue[ctx.guild].append(song)
await self.edit_message(ctx)
----stop section----
only skips music and don't clear queue
i don't know what is wrong here
#commands.command(brief='$stop')
async def stop(self, ctx):
voice = get(self.bot.voice_clients, guild=ctx.guild)
channel = ctx.message.author.voice.channel
await ctx.channel.purge(limit=1)
if voice and voice.is_playing():
await ctx.send('⛔ Music Stopped', delete_after = 5.0)
voice.stop(ctx.guild)
else:
await ctx.send("❌ I'm not playing any songs!", delete_after = 5.0)

Issue skipping song by requester

Hi I'm currently working on a music cog for my bot and I'm trying to figure out how to allow the song requester to skip the song without having to use the vote.
The music cog uses reactions to skip, stop, pause songs ect. The requester is the user who requested the song.
Here is what I'm trying to do:
if control == 'skip':
requester = self.requester
if requester:
vc.stop()
await channel.send('Requester skipped the song,')
else:
await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8)
if react.count >= 5: # bot counts as 1 reaction.
vc.stop()
await channel.send(':track_next: **Skipping...**', delete_after=5)
I'm having an issue mainly with defining the song requester requester = self.requester
Here's snippet of the part of the code that defines requester:
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, requester):
super().__init__(source)
self.requester = requester
self.title = data.get('title')
if self.title is None:
self.title = "No title available"
self.web_url = data.get('webpage_url')
self.thumbnail = data.get('thumbnail')
if self.thumbnail is None:
self.thumbnail = "http://ppc.tools/wp-content/themes/ppctools/img/no-thumbnail.jpg"
self.duration = data.get('duration')
if self.duration is None:
self.duration = 0
self.uploader = data.get('uploader')
if self.uploader is None:
self.uploader = "Unkown"
# YTDL info dicts (data) have other useful information you might want
# https://github.com/rg3/youtube-dl/blob/master/README.md
def __getitem__(self, item: str):
"""Allows us to access attributes similar to a dict.
This is only useful when you are NOT downloading.
"""
return self.__getattribute__(item)
#classmethod
async def create_source(cls, ctx, search: str, *, loop, download=False):
loop = loop or asyncio.get_event_loop()
to_run = partial(ytdl.extract_info, url=search, download=download)
data = await loop.run_in_executor(None, to_run)
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
await ctx.send(f':notes: **{data["title"]} added to the queue.**')
if download:
source = ytdl.prepare_filename(data)
else:
return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}
return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
#classmethod
async def regather_stream(cls, data, *, loop):
"""Used for preparing a stream, instead of downloading.
Since Youtube Streaming links expire."""
loop = loop or asyncio.get_event_loop()
requester = data['requester']
to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
data = await loop.run_in_executor(None, to_run)
return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)
class MusicPlayer:
"""A class which is assigned to each guild using the bot for Music.
This class implements a queue and loop, which allows for different guilds to listen to different playlists
simultaneously.
When the bot disconnects from the Voice it's instance will be destroyed.
"""
__slots__ = ('bot', '_guild', '_ctxs', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume', 'buttons', 'music', 'music_controller', 'restmode')
def __init__(self, ctx):
self.buttons = {'⏯': 'rp',
'⏭': 'skip',
'➕': 'vol_up',
'➖': 'vol_down',
'🖼': 'thumbnail',
'⏹': 'stop',
'ℹ': 'queue',
'❔': 'tutorial'}
self.bot = ctx.bot
self._guild = ctx.guild
self._ctxs = ctx
self._channel = ctx.channel
self._cog = ctx.cog
self.queue = asyncio.Queue()
self.next = asyncio.Event()
self.np = None
self.volume = .5
self.current = None
self.music_controller = None
ctx.bot.loop.create_task(self.player_loop())
async def buttons_controller(self, guild, current, source, channel, context):
vc = guild.voice_client
vctwo = context.voice_client
for react in self.buttons:
await current.add_reaction(str(react))
def check(r, u):
if not current:
return False
elif str(r) not in self.buttons.keys():
return False
elif u.id == self.bot.user.id or r.message.id != current.id:
return False
elif u not in vc.channel.members:
return False
elif u.bot:
return False
return True
while current:
if vc is None:
return False
react, user = await self.bot.wait_for('reaction_add', check=check)
control = self.buttons.get(str(react))
if control == 'rp':
if vc.is_paused():
vc.resume()
else:
vc.pause()
await current.remove_reaction(react, user)
if control == 'skip':
requester = self.requester
if requester:
vc.stop()
await channel.send('Requester skipped the song,')
else:
await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8)
if react.count >= 5: # bot counts as 1 reaction.
vc.stop()
await channel.send(':track_next: **Skipping...**', delete_after=5)
if control == 'stop':
mods = get(guild.roles, name="Mods")
for member in list(guild.members):
if mods in member.roles:
await context.invoke(self.bot.get_command("stop"))
return
else:
await channel.send(':raised_hand: **Only a mod can stop and clear the queue. Try skipping the song instead.**', delete_after=5)
await current.remove_reaction(react, user)
if control == 'vol_up':
player = self._cog.get_player(context)
vctwo.source.volume += 2.5
await current.remove_reaction(react, user)
if control == 'vol_down':
player = self._cog.get_player(context)
vctwo.source.volume -= 2.5
await current.remove_reaction(react, user)
if control == 'thumbnail':
await channel.send(embed=discord.Embed(color=0x17FD6E).set_image(url=source.thumbnail).set_footer(text=f"Requested By: {source.requester} | Video Thumbnail: {source.title}", icon_url=source.requester.avatar_url), delete_after=10)
await current.remove_reaction(react, user)
if control == 'tutorial':
await channel.send(embed=discord.Embed(color=0x17FD6E).add_field(name="How to use the music controller?", value="⏯ - Pause\n⏭ - Skip\n➕ - Increase Volume\n➖ - Increase Volume\n🖼 - Get Thumbnail\n⏹ - Stop & Leave\nℹ - Queue\n❔ - Display help for music controls"), delete_after=10)
await current.remove_reaction(react, user)
if control == 'queue':
await self._cog.queue_info(context)
await current.remove_reaction(react, user)
If anyone could help me an example of what I'm doing wrong would be awesome! Thanks.
You should be checking requester against the user that reacted to the message.
if control == 'skip':
if self.requester == user:
...
else:
...
With your current code, I would expect the song to always be skipped, as any User or Member object it truthy. You should double-check what is actually being assigned to self.requester.
#Patrick Here is how I'm doing it with your answer, however when the skip '⏭': 'skip', reaction is used it doesn't skip the requester song and causes all the reactions to not function.
Here is the full code:
import discord
from discord.ext import commands
import asyncio
import itertools, datetime
import sys
import traceback
from async_timeout import timeout
from functools import partial
from youtube_dl import YoutubeDL
from discord.ext.commands.cooldowns import BucketType
from cogs.utils.opus_loader import load_opus_lib
from .utils import checks
from discord.utils import get
import asyncio
if not discord.opus.is_loaded():
load_opus_lib()
ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpegopts = {
'before_options': '-nostdin -preset ultrafast',
'options': '-vn -threads 1'
}
ytdl = YoutubeDL(ytdlopts)
class VoiceConnectionError(commands.CommandError):
"""Custom Exception class for connection errors."""
class InvalidVoiceChannel(VoiceConnectionError):
"""Exception for cases of invalid Voice Channels."""
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, requester):
super().__init__(source)
self.requester = requester
self.title = data.get('title')
if self.title is None:
self.title = "No title available"
self.web_url = data.get('webpage_url')
self.thumbnail = data.get('thumbnail')
if self.thumbnail is None:
self.thumbnail = "http://ppc.tools/wp-content/themes/ppctools/img/no-thumbnail.jpg"
self.duration = data.get('duration')
if self.duration is None:
self.duration = 0
self.uploader = data.get('uploader')
if self.uploader is None:
self.uploader = "Unkown"
# YTDL info dicts (data) have other useful information you might want
# https://github.com/rg3/youtube-dl/blob/master/README.md
def __getitem__(self, item: str):
"""Allows us to access attributes similar to a dict.
This is only useful when you are NOT downloading.
"""
return self.__getattribute__(item)
#classmethod
async def create_source(cls, ctx, search: str, *, loop, download=False):
loop = loop or asyncio.get_event_loop()
to_run = partial(ytdl.extract_info, url=search, download=download)
data = await loop.run_in_executor(None, to_run)
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
await ctx.send(f':notes: **{data["title"]} added to the queue.**')
if download:
source = ytdl.prepare_filename(data)
else:
return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}
return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
#classmethod
async def regather_stream(cls, data, *, loop):
"""Used for preparing a stream, instead of downloading.
Since Youtube Streaming links expire."""
loop = loop or asyncio.get_event_loop()
requester = data['requester']
to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
data = await loop.run_in_executor(None, to_run)
return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)
class MusicPlayer:
"""A class which is assigned to each guild using the bot for Music.
This class implements a queue and loop, which allows for different guilds to listen to different playlists
simultaneously.
When the bot disconnects from the Voice it's instance will be destroyed.
"""
__slots__ = ('bot', '_guild', '_ctxs', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume', 'buttons', 'music', 'music_controller', 'restmode')
def __init__(self, ctx):
self.buttons = {'⏯': 'rp',
'⏭': 'skip',
'➕': 'vol_up',
'➖': 'vol_down',
'🖼': 'thumbnail',
'⏹': 'stop',
'ℹ': 'queue',
'❔': 'tutorial'}
self.bot = ctx.bot
self._guild = ctx.guild
self._ctxs = ctx
self._channel = ctx.channel
self._cog = ctx.cog
self.queue = asyncio.Queue()
self.next = asyncio.Event()
self.np = None
self.volume = .5
self.current = None
self.music_controller = None
ctx.bot.loop.create_task(self.player_loop())
async def buttons_controller(self, guild, current, source, channel, context):
vc = guild.voice_client
vctwo = context.voice_client
for react in self.buttons:
await current.add_reaction(str(react))
def check(r, u):
if not current:
return False
elif str(r) not in self.buttons.keys():
return False
elif u.id == self.bot.user.id or r.message.id != current.id:
return False
elif u not in vc.channel.members:
return False
elif u.bot:
return False
return True
while current:
if vc is None:
return False
react, user = await self.bot.wait_for('reaction_add', check=check)
control = self.buttons.get(str(react))
if control == 'rp':
if vc.is_paused():
vc.resume()
else:
vc.pause()
await current.remove_reaction(react, user)
if control == 'skip':
if self.requester == user:
await channel.send('Requester skipped.')
vc.stop()
else:
await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8)
if react.count >= 5: # bot counts as 1 reaction.
vc.stop()
await channel.send(':track_next: **Skipping...**', delete_after=5)
if control == 'stop':
mods = get(guild.roles, name="Mods")
for member in list(guild.members):
if mods in member.roles:
await context.invoke(self.bot.get_command("stop"))
return
else:
await channel.send(':raised_hand: **Only a mod can stop and clear the queue. Try skipping the song instead.**', delete_after=5)
await current.remove_reaction(react, user)
if control == 'vol_up':
player = self._cog.get_player(context)
vctwo.source.volume += 2.5
await current.remove_reaction(react, user)
if control == 'vol_down':
player = self._cog.get_player(context)
vctwo.source.volume -= 2.5
await current.remove_reaction(react, user)
if control == 'thumbnail':
await channel.send(embed=discord.Embed(color=0x17FD6E).set_image(url=source.thumbnail).set_footer(text=f"Requested By: {source.requester} | Video Thumbnail: {source.title}", icon_url=source.requester.avatar_url), delete_after=10)
await current.remove_reaction(react, user)
if control == 'tutorial':
await channel.send(embed=discord.Embed(color=0x17FD6E).add_field(name="How to use the music controller?", value="⏯ - Pause\n⏭ - Skip\n➕ - Increase Volume\n➖ - Increase Volume\n🖼 - Get Thumbnail\n⏹ - Stop & Leave\nℹ - Queue\n❔ - Display help for music controls"), delete_after=10)
await current.remove_reaction(react, user)
if control == 'queue':
await self._cog.queue_info(context)
await current.remove_reaction(react, user)
async def player_loop(self):
"""Our main player loop."""
await self.bot.wait_until_ready()
while not self.bot.is_closed():
self.next.clear()
try:
async with timeout(3500):
source = await self.queue.get()
except asyncio.TimeoutError:
return self.destroy(self._guild)
if not isinstance(source, YTDLSource):
# Source was probably a stream (not downloaded)
# So we should regather to prevent stream expiration
try:
source = await YTDLSource.regather_stream(source, loop=self.bot.loop)
except Exception as e:
await self._channel.send(f'An error occured!.\n'
f'```css\n[{e}]\n```')
continue
source.volume = self.volume
self.current = source
try:
self._guild.voice_client.play(source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set))
except Exception:
continue
embednps = discord.Embed(color=0x17FD6E)
embednps.add_field(name="Currently Playing:", value=f"```fix\n{source.title}```", inline=False)
embednps.add_field(name="Requested By:", value=f"**{source.requester}**", inline=True)
embednps.add_field(name="Source:", value=f"**[URL]({source.web_url})**", inline=True)
embednps.add_field(name="Uploader:", value=f"**{source.uploader}**", inline=True)
embednps.add_field(name="Duration:", value=f"**{datetime.timedelta(seconds=source.duration)}**", inline=True)
embednps.set_thumbnail(url=source.thumbnail)
self.np = await self._channel.send(embed=embednps)
self.music_controller = self.bot.loop.create_task(self.buttons_controller(self._guild, self.np, source, self._channel, self._ctxs))
await self.next.wait()
# Make sure the FFmpeg process is cleaned up.
source.cleanup()
self.current = None
try:
# We are no longer playing this song...
await self.np.delete()
self.music_controller.cancel()
except Exception:
pass
def destroy(self, guild):
"""Disconnect and cleanup the player."""
return self.bot.loop.create_task(self._cog.cleanup(guild))
class Music:
"""Music cog for UKGBot."""
__slots__ = ('bot', 'players', 'musictwo', 'music_controller')
def __init__(self, bot):
self.bot = bot
self.players = {}
async def cleanup(self, guild):
try:
await guild.voice_client.disconnect()
except AttributeError:
pass
try:
del self.players[guild.id]
except KeyError:
pass
async def __local_check(self, ctx):
"""A local check which applies to all commands in this cog."""
if not ctx.guild:
raise commands.NoPrivateMessage
return True
async def cleanup(self, guild):
try:
await guild.voice_client.disconnect()
except AttributeError:
pass
try:
del self.players[guild.id]
except KeyError:
pass
async def __error(self, ctx, error):
"""A local error handler for all errors arising from commands in this cog."""
if isinstance(error, commands.NoPrivateMessage):
try:
return await ctx.send(':notes: Command cannot be used in DM.')
except discord.HTTPException:
pass
elif isinstance(error, InvalidVoiceChannel):
await ctx.send("Connect to a voice channel first!")
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
def get_player(self, ctx):
"""Retrieve the guild player, or generate one."""
try:
player = self.players[ctx.guild.id]
except KeyError:
player = MusicPlayer(ctx)
self.players[ctx.guild.id] = player
return player
#commands.command(name='stop', aliases=[ 'l', 'disconnect'])
#checks.is_channel_mod()
async def disconnect_(self, ctx):
"""Stops and leaves the voice channel."""
try:
channel = ctx.author.voice.channel
except AttributeError:
await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
if not ctx.guild.voice_client:
return await ctx.send(':notes: I\'m not connected to the voice channel.', delete_after=20)
await ctx.guild.voice_client.disconnect()
await ctx.send(':wave: Stopped and left the channel.', delete_after=20)
#commands.command(name='reconnect', aliases=['rc'])
async def reconnect_(self, ctx):
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
if ctx.guild.voice_client:
await ctx.guild.voice_client.disconnect()
await channel.connect()
#commands.command(name='connect', aliases=['join','summon'])
async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
"""connectss to a voice channel."""
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
await channel.connect()
#commands.command(name='skip', aliases=['sk'])
#checks.is_channel_mod()
async def skip_(self, ctx, *, channel: discord.VoiceChannel=None):
"""Skips a song (Mods)."""
try:
channel = ctx.author.voice.channel
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
ctx.guild.voice_client.stop()
await ctx.send(':track_next: **Skipping...**', delete_after=5)
#commands.command(name='play', aliases=['sing', 'p'])
async def play_(self, ctx, *, search: str):
"""searches for and plays a song."""
await ctx.trigger_typing()
vc = ctx.voice_client
try:
channel = ctx.author.voice.channel
if not vc:
await ctx.invoke(self.connect_)
except AttributeError:
return await ctx.send(":notes: You are not connected to a voice channel.", delete_after=20)
player = self.get_player(ctx)
# If download is False, source will be a dict which will be used later to regather the stream.
# If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)
await player.queue.put(source)
#commands.command(name='playing', aliases=['np', 'current', 'currentsong', 'now_playing'])
async def now_playing_(self, ctx):
"""Shows the current song playing."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
return await ctx.send("I'm not connected to a voice channel..", delete_after=20)
elif ctx.author not in ctx.guild.voice_client.channel.members:
return await ctx.send("You need to be in the voice channel first!", delete_after=20)
player = self.get_player(ctx)
if not player.current:
return await ctx.send("There's nothing currently playing.", delete_after=20)
try:
# Remove our previous now_playing message.
await player.np.delete()
except discord.HTTPException:
pass
embednp = discord.Embed(color=0x17FD6E)
embednp.add_field(name="Currently Playing:", value=f"```fix\n{vc.source.title}```", inline=False)
embednp.add_field(name="Requested By:", value=f"**{vc.source.requester}**", inline=True)
embednp.add_field(name="Source:", value=f"**[URL]({vc.source.web_url})**", inline=True)
embednp.add_field(name="Uploader:", value=f"**{vc.source.uploader}**", inline=True)
embednp.add_field(name="Duration:", value=f"**{datetime.timedelta(seconds=vc.source.duration)}**", inline=True)
embednp.set_thumbnail(url=f"{vc.source.thumbnail}")
player.np = await ctx.send(embed=embednp)
self.music_controller = self.bot.loop.create_task(MusicPlayer(ctx).buttons_controller(ctx.guild, player.np, vc.source, ctx.channel, ctx))
async def queue_info(self, ctx):
player = self.get_player(ctx)
if player.queue.empty():
return await ctx.send('**:notes: No songs currently queued.**', delete_after=5)
upcoming = list(itertools.islice(player.queue._queue, 0, 5))
fmt = '\n'.join(f'**`{_["title"]}`**' for _ in upcoming)
embed = discord.Embed(title=f'{len(upcoming)} songs queued.', description=fmt, color=0x17FD6E)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Music(bot))
Look at your signature, async def buttons_controller(self, guild, current, source, channel, context): What you are looking for is source as source = song "the song you have requested".
Therefore you would need to add source in front of requester as requester = the member and after this you need to define user as we are looking the specific requester on reaction add.
So you have this:
if control == 'skip':
if source.requester == user:
vc.stop()

Resources