Adding all slash command to music cog

This commit is contained in:
Mylloon 2021-08-16 16:21:30 +02:00
parent 40e06be550
commit d4ed846cb5
2 changed files with 166 additions and 68 deletions

View file

@ -29,6 +29,9 @@ import wavelink
from discord.ext import commands, menus from discord.ext import commands, menus
from time import sleep from time import sleep
import socket import socket
from discord_slash import cog_ext
from utils.core import isSlash, multipleArgsToTuple, mySendHidden
from sys import _getframe
# Genius API # Genius API
from lyricsgenius import Genius from lyricsgenius import Genius
@ -151,7 +154,7 @@ class Player(wavelink.Player):
channel = self.bot.get_channel(int(self.channel_id)) channel = self.bot.get_channel(int(self.channel_id))
qsize = self.queue.qsize() qsize = self.queue.qsize()
embed = discord.Embed(title=f'Contrôleur musical dans {channel.name}', colour=0xebb145) embed = discord.Embed(title=f"Musique dans {channel.name}", colour=0xebb145)
embed.description = f"En cours :\n**`{track.title}`**\n\n" embed.description = f"En cours :\n**`{track.title}`**\n\n"
embed.set_thumbnail(url=track.thumb) embed.set_thumbnail(url=track.thumb)
@ -221,7 +224,7 @@ class InteractiveController(menus.Menu):
return payload.emoji in self.buttons return payload.emoji in self.buttons
async def send_initial_message(self, ctx: commands.Context, channel: discord.TextChannel) -> discord.Message: async def send_initial_message(self, _: commands.Context, channel: discord.TextChannel) -> discord.Message:
return await channel.send(embed=self.embed) return await channel.send(embed=self.embed)
@menus.button(emoji='\u25B6') @menus.button(emoji='\u25B6')
@ -311,7 +314,7 @@ class PaginatorSource(menus.ListPageSource):
def __init__(self, entries, *, per_page=8): def __init__(self, entries, *, per_page=8):
super().__init__(entries, per_page=per_page) super().__init__(entries, per_page=per_page)
async def format_page(self, menu: menus.Menu, page): async def format_page(self, _: menus.Menu, page):
embed = discord.Embed(title='À suivre...', colour=0x4f0321) embed = discord.Embed(title='À suivre...', colour=0x4f0321)
embed.description = '\n'.join(f'`{index}. {title}`' for index, title in enumerate(page, 1)) embed.description = '\n'.join(f'`{index}. {title}`' for index, title in enumerate(page, 1))
@ -371,16 +374,16 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
@wavelink.WavelinkMixin.listener() @wavelink.WavelinkMixin.listener()
async def on_node_ready(self, node: wavelink.Node): async def on_node_ready(self, node: wavelink.Node):
print(f'Node Lavalink \"{node.identifier}\" est prête !') print(f'Node Lavalink \"{node.identifier}\" prête !')
@wavelink.WavelinkMixin.listener('on_track_stuck') @wavelink.WavelinkMixin.listener('on_track_stuck')
@wavelink.WavelinkMixin.listener('on_track_end') @wavelink.WavelinkMixin.listener('on_track_end')
@wavelink.WavelinkMixin.listener('on_track_exception') @wavelink.WavelinkMixin.listener('on_track_exception')
async def on_player_stop(self, node: wavelink.Node, payload): async def on_player_stop(self, _: wavelink.Node, payload):
await payload.player.do_next() await payload.player.do_next()
@commands.Cog.listener() @commands.Cog.listener()
async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState): async def on_voice_state_update(self, member: discord.Member, _: discord.VoiceState, after: discord.VoiceState):
if member.bot: if member.bot:
return return
@ -466,11 +469,14 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
return player.dj == ctx.author or ctx.author.guild_permissions.kick_members return player.dj == ctx.author or ctx.author.guild_permissions.kick_members
@commands.command(aliases=["join", "j"]) @commands.command(aliases=["join", "j"])
async def connect(self, ctx: commands.Context, *, channel: typing.Union[discord.VoiceChannel, discord.StageChannel] = None): async def connect(self, ctx: commands.Context, *, channel: typing.Union[discord.VoiceChannel, discord.StageChannel] = None, fromSlash = None):
"""Connexion à un channel vocal.\n ➡ Syntaxe: {PREFIX}connect/join/j""" """Se connecte au salon vocal.\n ➡ Syntaxe: {PREFIX}connect/join/j [salon]"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if player.is_connected: if player.is_connected:
if fromSlash:
await ctx.send("Déjà connecté.", hidden = True)
return return
channel = getattr(ctx.author.voice, 'channel', channel) channel = getattr(ctx.author.voice, 'channel', channel)
@ -478,14 +484,26 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
raise NoChannelProvided raise NoChannelProvided
await player.connect(channel.id) await player.connect(channel.id)
await ctx.send(f":thumbsup: **Connecté à __{channel.name}__**")
@cog_ext.cog_slash(name="join", description = "Se connecte au salon vocal.")
async def _connect(self, ctx, channel = None):
return await self.connect(ctx = ctx, channel = channel, fromSlash = True)
@commands.command(aliases=["p"]) @commands.command(aliases=["p"])
async def play(self, ctx: commands.Context, *, query: str): async def play(self, ctx: commands.Context, *, query: str = None, fromSlash = None):
"""Joue ou met dans la file d'attente un son avec la requête donnée.\n ➡ Syntaxe: {PREFIX}play/p""" """Joue ou met dans la file d'attente le son demandé.\n ➡ Syntaxe: {PREFIX}play/p <nom du son>"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
noSoundFound = "Aucun son n'a été trouvée avec cette requête."
if query == None:
return await mySendHidden(ctx, fromSlash, noSoundFound, delete_after=15)
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
await ctx.invoke(self.connect) channel = getattr(ctx.author.voice, 'channel')
if channel is None:
raise NoChannelProvided
await self.connect(ctx = ctx, channel = channel, fromSlash = True)
query = query.strip('<>') query = query.strip('<>')
if not URL_REG.match(query): if not URL_REG.match(query):
@ -493,7 +511,7 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
tracks = await self.bot.wavelink.get_tracks(query) tracks = await self.bot.wavelink.get_tracks(query)
if not tracks: if not tracks:
return await ctx.send("Aucun son n'a été trouvée avec cette requête. Veuillez réessayer.", delete_after=15) return await mySendHidden(ctx, fromSlash, noSoundFound, delete_after=15)
if isinstance(tracks, wavelink.TrackPlaylist): if isinstance(tracks, wavelink.TrackPlaylist):
for track in tracks.tracks: for track in tracks.tracks:
@ -510,17 +528,23 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
if not player.is_playing: if not player.is_playing:
await player.do_next() await player.do_next()
@cog_ext.cog_slash(name="play", description = "Joue ou met dans la file d'attente le son demandé.")
async def _play(self, ctx, son):
return await self.play(ctx = ctx, query = son, fromSlash = True)
@commands.command() @commands.command()
async def pause(self, ctx: commands.Context): async def pause(self, ctx: commands.Context, *, fromSlash = None):
"""Met en pause du son en cours.""" """Met en pause du son en cours."""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if player.is_paused or not player.is_connected: if player.is_paused or not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if self.is_privileged(ctx): if self.is_privileged(ctx):
await ctx.send("Un admin ou un DJ a mis la musique en pause.", delete_after=10) await ctx.send(f"{ctx.author.mention} a mis la musique en pause.", delete_after=10)
player.pause_votes.clear() player.pause_votes.clear()
return await player.set_pause(True) return await player.set_pause(True)
@ -529,22 +553,28 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
player.pause_votes.add(ctx.author) player.pause_votes.add(ctx.author)
if len(player.pause_votes) >= required: if len(player.pause_votes) >= required:
await ctx.send("Mise en pause votée. Musique mis en pause.", delete_after=10) await ctx.send("Mise en pause votée.", delete_after=10)
player.pause_votes.clear() player.pause_votes.clear()
await player.set_pause(True) await player.set_pause(True)
else: else:
await ctx.send(f"{ctx.author.mention} a voté pour mettre la musique en pause.", delete_after=15) await mySendHidden(ctx, fromSlash, "Tu as voté pour mettre la musique en pause.", delete_after=15)
@cog_ext.cog_slash(name="pause", description = "Met en pause du son en cours.")
async def _pause(self, ctx):
return await self.pause(ctx = ctx, fromSlash = True)
@commands.command() @commands.command()
async def resume(self, ctx: commands.Context): async def resume(self, ctx: commands.Context, *, fromSlash = None):
"""Reprend la musique en pause.""" """Reprend la musique en pause."""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_paused or not player.is_connected: if not player.is_paused or not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique en pause n'est en cours.", hidden = True)
return return
if self.is_privileged(ctx): if self.is_privileged(ctx):
await ctx.send("Un admin ou un DJ a mis la musique en pause.", delete_after=10) await ctx.send(f"{ctx.author.mention} a relancé la musique.", delete_after=10)
player.resume_votes.clear() player.resume_votes.clear()
return await player.set_pause(False) return await player.set_pause(False)
@ -553,28 +583,28 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
player.resume_votes.add(ctx.author) player.resume_votes.add(ctx.author)
if len(player.resume_votes) >= required: if len(player.resume_votes) >= required:
await ctx.send("Mise en pause votée. Musique relancée.", delete_after=10) await ctx.send("Relance de la musique votée.", delete_after=10)
player.resume_votes.clear() player.resume_votes.clear()
await player.set_pause(False) await player.set_pause(False)
else: else:
await ctx.send(f'{ctx.author.mention} a voté pour relancer la musique.', delete_after=15) await mySendHidden(ctx, fromSlash, "Tu as voté pour relancer la musique.", delete_after=15)
@cog_ext.cog_slash(name="resume", description = "Reprend la musique en pause.")
async def _resume(self, ctx):
return await self.resume(ctx = ctx, fromSlash = True)
@commands.command(aliases=["s"]) @commands.command(aliases=["s"])
async def skip(self, ctx: commands.Context): async def skip(self, ctx: commands.Context, *, fromSlash = None):
"""Skip le son en cours.\n ➡ Syntaxe: {PREFIX}skip/s""" """Passe le son en cours.\n ➡ Syntaxe: {PREFIX}skip/s"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if self.is_privileged(ctx): if self.is_privileged(ctx) or ctx.author == player.current.requester:
await ctx.send("Un admin ou un DJ a skip le son.", delete_after=10) await ctx.send(f"{ctx.author.mention} passe le son.", delete_after=10)
player.skip_votes.clear()
return await player.stop()
if ctx.author == player.current.requester:
await ctx.send("La personne qui avait mit le son l'a skip.", delete_after=10)
player.skip_votes.clear() player.skip_votes.clear()
return await player.stop() return await player.stop()
@ -583,63 +613,85 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
player.skip_votes.add(ctx.author) player.skip_votes.add(ctx.author)
if len(player.skip_votes) >= required: if len(player.skip_votes) >= required:
await ctx.send("Vote pour skip le son adoptée, skip de le son.", delete_after=10) await ctx.send("Vote pour passer le son adoptée.", delete_after=10)
player.skip_votes.clear() player.skip_votes.clear()
await player.stop() await player.stop()
else: else:
await ctx.send(f"{ctx.author.mention} a voté pour skip le son.", delete_after=15) await mySendHidden(ctx, fromSlash, f"Tu as voté pour passer le son ({len(player.skip_votes)}/{required}).", delete_after=15)
@cog_ext.cog_slash(name="skip", description = "Passe le son en cours.")
async def _skip(self, ctx):
return await self.skip(ctx = ctx, fromSlash = True)
@commands.command(aliases=["disconnect", "discon"]) @commands.command(aliases=["disconnect", "dc"])
async def stop(self, ctx: commands.Context): async def stop(self, ctx: commands.Context, *, fromSlash = None):
"""Stop le son et supprime la file d'attente.\n ➡ Syntaxe: {PREFIX}stop/disconnect/discon""" """Stop le son en cours de lecture, supprime la file d'attente et quitte le vocal.\n ➡ Syntaxe: {PREFIX}stop/disconnect/dc"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if self.is_privileged(ctx): if self.is_privileged(ctx):
await ctx.send("Un admin ou un DJ arrêter le son et supprimer la file d'attente.", delete_after=10) await ctx.send(f"{ctx.author.mention} a déconnecter le bot et supprimer la file d'attente.", delete_after=10)
print("x")
return await player.teardown() return await player.teardown()
required = self.required(ctx) required = self.required(ctx)
player.stop_votes.add(ctx.author) player.stop_votes.add(ctx.author)
if len(player.stop_votes) >= required: if len(player.stop_votes) >= required:
await ctx.send("Arrêt voté. Arrêt du son et suppression de la file d'attente.", delete_after=10) await ctx.send("Arrêt et suppression de la file d'attente voté.", delete_after=10)
await player.teardown() await player.teardown()
else: else:
await ctx.send(f"{ctx.author.mention} a voté pour arrêter d'écouter de la musique.", delete_after=15) await mySendHidden(ctx, fromSlash, "Tu as voté pour arrêter d'écouter de la musique.", delete_after=15)
@cog_ext.cog_slash(name="stop", description = "Stop le son en cours de lecture, supprime la file d'attente et quitte le vocal.")
async def _stop(self, ctx):
return await self.stop(ctx = ctx, fromSlash = True)
@commands.command(aliases=['v', 'vol']) @commands.command(aliases=['v', 'vol'])
async def volume(self, ctx: commands.Context, *, vol: int): async def volume(self, ctx: commands.Context, *, vol: int = None, fromSlash = None):
"""Modifiez le volume du lecteur.\n ➡ Syntaxe: {PREFIX}volume/vol/v (1-100)""" """Modifie le volume du bot.\n ➡ Syntaxe: {PREFIX}volume/vol/v (1-100)"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not vol:
return await mySendHidden(ctx, fromSlash, f"Le volume est actuellement réglé à **{player.volume}%**.")
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if not self.is_privileged(ctx): if not self.is_privileged(ctx):
return await ctx.send("Seuls le DJ ou les admins peuvent modifier le volume.") return await mySendHidden(ctx, fromSlash, "Seuls le DJ ou les admins peuvent modifier le volume.")
if not 0 < vol < 101: if not 0 < vol < 101:
return await ctx.send("Veuillez saisir une valeur comprise entre 1 et 100.") return await mySendHidden(ctx, fromSlash, "Veuillez saisir une valeur comprise entre 1 et 100.")
await player.set_volume(vol) await player.set_volume(vol)
await ctx.send(f"Volume réglé à **{vol}**%.", delete_after=7) await ctx.send(f"Volume réglé sur **{vol}%** par {ctx.author.mention}", delete_after=7)
@cog_ext.cog_slash(name="volume", description = "Modifie le volume du bot.")
async def _volume(self, ctx, vol: int = None):
return await self.volume(ctx = ctx, vol = vol, fromSlash = True)
@commands.command(aliases=['mix']) @commands.command(aliases=['mix'])
async def shuffle(self, ctx: commands.Context): async def shuffle(self, ctx: commands.Context, *, fromSlash = None):
"""Mélange les sons en file d'attente. (mini 3 sons en file d'attente)\n ➡ Syntaxe: {PREFIX}shuffle/mix""" """Mélange les sons en file d'attente. (mini 3 sons en file d'attente)\n ➡ Syntaxe: {PREFIX}shuffle/mix"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if player.queue.qsize() < 3: if player.queue.qsize() < 3:
return await ctx.send("Ajoutez d'autres sons à la file d'attente avant de les mélanger.", delete_after=15) return await mySendHidden(ctx, fromSlash, "Ajoutez d'autres sons à la file d'attente avant de les mélanger (3 minimum).", delete_after=15)
if self.is_privileged(ctx): if self.is_privileged(ctx):
await ctx.send("Un admin ou un DJ a mélangé la liste de lecture.", delete_after=10) await ctx.send(f"{ctx.author.mention} a mélangé la liste de lecture.", delete_after=10)
player.shuffle_votes.clear() player.shuffle_votes.clear()
return random.shuffle(player.queue._queue) return random.shuffle(player.queue._queue)
@ -647,11 +699,14 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
player.shuffle_votes.add(ctx.author) player.shuffle_votes.add(ctx.author)
if len(player.shuffle_votes) >= required: if len(player.shuffle_votes) >= required:
await ctx.send("Le vote pour la lecture aléatoire a été adopté. Mélange de la liste de lecture.", delete_after=10) await ctx.send("Le vote pour la lecture aléatoire a été voté.", delete_after=10)
player.shuffle_votes.clear() player.shuffle_votes.clear()
random.shuffle(player.queue._queue) random.shuffle(player.queue._queue)
else: else:
await ctx.send(f"{ctx.author.mention} a voté pour mélanger la liste de lecture.", delete_after=15) await mySendHidden(ctx, fromSlash, "Tu as voté pour mélanger la liste de lecture.", delete_after=15)
@cog_ext.cog_slash(name="shuffle", description = "Mélange les sons en file d'attente. (mini 3 sons en file d'attente)")
async def _shuffle(self, ctx):
return await self.shuffle(ctx = ctx, fromSlash = True)
@commands.command(hidden=True) @commands.command(hidden=True)
async def vol_up(self, ctx: commands.Context): async def vol_up(self, ctx: commands.Context):
@ -686,15 +741,18 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
await player.set_volume(vol) await player.set_volume(vol)
@commands.command(aliases=['eq']) @commands.command(aliases=['eq'])
async def equalizer(self, ctx: commands.Context, *, equalizer: str): async def equalizer(self, ctx: commands.Context, *, equalizer: str, fromSlash = None):
"""Change l'égaliseur de musique.\n ➡ Syntaxe: {PREFIX}equalizer/eq (flat/boost/metal/piano)""" """Change l'égaliseur de musique.\n ➡ Syntaxe: {PREFIX}equalizer/eq (flat/boost/metal/piano)"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if not self.is_privileged(ctx): if not self.is_privileged(ctx):
return await ctx.send("Seul le DJ ou les admins peuvent modifier l'égaliseur.") return await mySendHidden(ctx, fromSlash, "Seul le DJ ou les admins peuvent modifier l'égaliseur.")
eqs = {'flat': wavelink.Equalizer.flat(), eqs = {'flat': wavelink.Equalizer.flat(),
'boost': wavelink.Equalizer.boost(), 'boost': wavelink.Equalizer.boost(),
@ -704,59 +762,80 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
eq = eqs.get(equalizer.lower(), None) eq = eqs.get(equalizer.lower(), None)
if not eq: if not eq:
return await ctx.send(f"EQ non valide fourni. EQs valides :\n{', '.join(eqs.keys())}") return await mySendHidden(ctx, fromSlash, f"EQ non valide fourni.\nEQs valides : {', '.join(eqs.keys())}")
await ctx.send(f"Changement d'état de l'égaliseur en `{equalizer}`.", delete_after=15) await ctx.send(f"Changement d'état de l'égaliseur en `{equalizer}` par {ctx.author.mention}.", delete_after=15)
await player.set_eq(eq) await player.set_eq(eq)
@cog_ext.cog_slash(name="equalizer", description = "Change l'égaliseur de musique. (flat/boost/metal/piano)")
async def _equalizer(self, ctx, equalizer: str):
return await self.equalizer(ctx = ctx, equalizer = equalizer, fromSlash = True)
@commands.command(aliases=['q', 'que']) @commands.command(aliases=['q', 'que'])
async def queue(self, ctx: commands.Context): async def queue(self, ctx: commands.Context, *, fromSlash = None):
"""Afficher les sons en attente.\n ➡ Syntaxe: {PREFIX}queue/que/q""" """Affiche les sons en attente.\n ➡ Syntaxe: {PREFIX}queue/que/q"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if player.queue.qsize() == 0: if player.queue.qsize() == 0:
return await ctx.send("Il n'y a plus de sons dans la file d'attente.", delete_after=15) return await mySendHidden(ctx, fromSlash, "Il n'y a plus de sons dans la file d'attente.", delete_after=15)
entries = [track.title for track in player.queue._queue] entries = [track.title for track in player.queue._queue]
pages = PaginatorSource(entries=entries) pages = PaginatorSource(entries=entries)
paginator = menus.MenuPages(source=pages, timeout=None, delete_message_after=True) paginator = menus.MenuPages(source=pages, timeout=None, delete_message_after=True)
await ctx.send("Affichage de la liste ci-dessous.", hidden = True)
await paginator.start(ctx) await paginator.start(ctx)
@cog_ext.cog_slash(name="queue", description = "Affiche les sons en attente.")
async def _queue(self, ctx,):
return await self.queue(ctx = ctx, fromSlash = True)
@commands.command(aliases=['np', 'now_playing', 'current']) @commands.command(aliases=['np', 'now_playing', 'current'])
async def nowplaying(self, ctx: commands.Context): async def nowplaying(self, ctx: commands.Context, *, fromSlash = None):
"""Met à jour l'embed qui affiche les informations sur la chanson en cours.\n ➡ Syntaxe: {PREFIX}nowplaying/now_playing/current/np""" """Met à jour l'embed qui affiche les informations sur la chanson en cours.\n ➡ Syntaxe: {PREFIX}nowplaying/now_playing/current/np"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
await player.invoke_controller() await player.invoke_controller()
if fromSlash:
await mySendHidden(ctx, fromSlash, "Mise à jour effectuée.")
@cog_ext.cog_slash(name="nowplaying", description = "Met à jour l'embed qui affiche les informations sur la chanson en cours.")
async def _nowplaying(self, ctx,):
return await self.nowplaying(ctx = ctx, fromSlash = True)
@commands.command(aliases=['swap']) @commands.command(aliases=['swap'])
async def swap_dj(self, ctx: commands.Context, *, member: discord.Member = None): async def swap_dj(self, ctx: commands.Context, *, member: discord.Member = None, fromSlash = None):
"""Change le DJ actuel à un autre membre dans le channel vocal.\n ➡ Syntaxe: {PREFIX}swap_dj/swap (membre)""" """Donne le rôle de DJ à un autre membre dans le salon vocal.\n ➡ Syntaxe: {PREFIX}swap_dj/swap (membre)"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if not player.is_connected: if not player.is_connected:
if fromSlash:
await ctx.send("Aucune musique n'est en cours.", hidden = True)
return return
if not self.is_privileged(ctx): if not self.is_privileged(ctx):
return await ctx.send("Seuls les admins et le DJ peuvent utiliser cette commande.", delete_after=15) return await mySendHidden(ctx, fromSlash, "Seuls les admins et le DJ peuvent utiliser cette commande.", delete_after=15)
members = self.bot.get_channel(int(player.channel_id)).members members = self.bot.get_channel(int(player.channel_id)).members
if member and member not in members: if member and member not in members:
return await ctx.send(f"{member} n'est pas actuellement dans le salon, et ne peut donc pas être un DJ.", delete_after=15) return await mySendHidden(ctx, fromSlash, f"{member} n'est pas actuellement dans le salon, et ne peut donc pas être un DJ.", delete_after=15)
if member and member == player.dj: if member and member == player.dj:
return await ctx.send("Cette personne est déjà le DJ.", delete_after=15) return await mySendHidden(ctx, fromSlash, "Cette personne est déjà DJ.", delete_after=15)
if len(members) <= 2: if len(members) <= 2:
return await ctx.send("Aucun autre membre à qui donner le rôle de DJ.", delete_after=15) return await mySendHidden(ctx, fromSlash, "Aucun autre membre à qui donner le rôle de DJ.", delete_after=15)
if member: if member:
player.dj = member player.dj = member
@ -768,10 +847,14 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
else: else:
player.dj = m player.dj = m
return await ctx.send(f"{member.mention} est maintenant le DJ.") return await ctx.send(f"{member.mention} est maintenant le DJ.")
@cog_ext.cog_slash(name="swap_dj", description = "Donne le rôle de DJ à un autre membre dans le salon vocal.")
async def _swap_dj(self, ctx, member: discord.Member = None):
return await self.swap_dj(ctx = ctx, member = member, fromSlash = True)
@commands.command(name='lyrics', aliases = ['l', 'lyric']) @commands.command(name='lyrics', aliases = ['l', 'lyric'])
async def _lyrics(self, ctx, *, song: str = None): async def _lyrics(self, ctx, *, song: str = None, fromSlash = None):
"""Affiche les paroles de la musique en cours, ou de la chanson spécifiée.\n ➡ Syntaxe: {PREFIX}lyrics/lyric/l (musique)""" """Affiche les paroles de la musique en cours, ou de la chanson spécifiée.\n ➡ Syntaxe: {PREFIX}lyrics/lyric/l (musique)"""
_, fromSlash, _ = isSlash(multipleArgsToTuple(_getframe(0)))
player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx) player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, context=ctx)
if song or player.is_playing: if song or player.is_playing:
if not song: if not song:
@ -828,7 +911,10 @@ class Music(commands.Cog, wavelink.WavelinkMixin):
return await ctx.send(embed = embed) return await ctx.send(embed = embed)
else: else:
await ctx.message.add_reaction(emoji = '') await ctx.message.add_reaction(emoji = '')
await ctx.send(f"Aucune musique demandé... `{ctx.prefix}lyrics/l/lyrics <song>`.") await mySendHidden(ctx, fromSlash, f"Aucune musique demandé... `{ctx.prefix}lyrics/l/lyrics <song>`.")
@cog_ext.cog_slash(name="lyrics", description = "Affiche les paroles de la musique en cours, ou de la chanson spécifiée.")
async def __lyrics(self, ctx, song: str):
return await self._lyrics(ctx = ctx, song = song, fromSlash = True)
@commands.command(name='lyricsromanized', aliases = ['lr', 'lyricromanized'], hidden = True) @commands.command(name='lyricsromanized', aliases = ['lr', 'lyricromanized'], hidden = True)
async def _lyricsromanized(self, ctx, *, song: str = None): async def _lyricsromanized(self, ctx, *, song: str = None):

View file

@ -4,6 +4,7 @@ from re import findall
from time import time from time import time
from os import environ, path from os import environ, path
from dotenv import load_dotenv from dotenv import load_dotenv
from inspect import getargvalues
def map_list_among_us(map): def map_list_among_us(map):
"""Sélecteur de map pour la commande amongus""" """Sélecteur de map pour la commande amongus"""
@ -131,10 +132,12 @@ def getChangelogs(version = 'actual'):
return [code, changements["_links"]["self"], changements["tag_name"][1:], changements["description"]] return [code, changements["_links"]["self"], changements["tag_name"][1:], changements["description"]]
def getActualVersion(): def getActualVersion():
"""Récupère la version actuellement utilisé par le Bot grâce au README"""
with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file:
return findall(r'https:\/\/img.shields.io\/badge\/version-(\d+\.\d+)-green\?style=for-the-badge\)', file.readlines()[2])[0] return findall(r'https:\/\/img.shields.io\/badge\/version-(\d+\.\d+)-green\?style=for-the-badge\)', file.readlines()[2])[0]
def devOrStableChannel(): def devOrStableChannel():
"""Check si le bot tourne sur une version stable ou une version de développement grâce au README"""
with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file: with open(path.join(path.dirname(path.dirname(path.dirname(__file__))), "README.md"), "r") as file:
return findall(r'https:\/\/img.shields.io\/gitlab\/pipeline\/ConfrerieDuKassoulait\/KassouBot\/([a-z]+)\?style=for-the-badge\)]', file.readlines()[3])[0] return findall(r'https:\/\/img.shields.io\/gitlab\/pipeline\/ConfrerieDuKassoulait\/KassouBot\/([a-z]+)\?style=for-the-badge\)]', file.readlines()[3])[0]
@ -153,9 +156,9 @@ def isSlash(arg):
return (arg, fromSlash, fullarg) return (arg, fromSlash, fullarg)
async def mySendHidden( async def mySendHidden(ctx, fromSlash, message = None, tts = False, embed = None, file = None, files = None,
ctx, fromSlash, message = None, tts = False, embed = None, file = None, files = None, delete_after = None, allowed_mentions = None):
delete_after = None, allowed_mentions = None): """Envoie d'un message uniquement visible par l'utilisateur"""
if fromSlash == True: # can't delete hidden message if fromSlash == True: # can't delete hidden message
await ctx.send( # sending hidden message await ctx.send( # sending hidden message
content = message, tts = tts, embed = embed, file = file, files = files, content = message, tts = tts, embed = embed, file = file, files = files,
@ -193,6 +196,7 @@ def load(variables):
return keys return keys
def getLavalinkVersion(): def getLavalinkVersion():
"""Récupère la version actuellement utilisé dans le fichier README du repo dédié à Lavalink"""
try: try:
with open(path.join(path.dirname(path.dirname(__file__)), "lavalink/README.md"), "r") as file: with open(path.join(path.dirname(path.dirname(__file__)), "lavalink/README.md"), "r") as file:
ver = findall(r'Version \*\*(\d+.+)\*\*', file.readlines()[2]) ver = findall(r'Version \*\*(\d+.+)\*\*', file.readlines()[2])
@ -202,3 +206,11 @@ def getLavalinkVersion():
return ver[0] return ver[0]
else: else:
return None return None
def multipleArgsToTuple(frame):
"""Convertis les arguments reçus en une liste"""
args = []
for arg in list((getargvalues(frame).locals.values()))[2:]:
if arg:
args.append(arg)
return tuple(args)