Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- This is an example cog that shows how you would make use of Lavalink.py.
- This example cog requires that you have python 3.6 or higher due to the f-strings.
- """
- import math
- import re
- import discord
- import lavalink
- from discord.ext import commands
- url_rx = re.compile('https?:\\/\\/(?:www\\.)?.+') # noqa: W605
- class musica(commands.Cog):
- def __init__(self, client):
- self.client = client
- if not hasattr(client, 'lavalink'): # This ensures the client isn't overwritten during cog reloads.
- client.lavalink = lavalink.Client(client.user.id)
- client.lavalink.add_node('luiz13lavalink.glitch.me', 80, 'youshallnotpass', 'us', 'default-node') # Host, Port, Password, Region, Name
- client.add_listener(client.lavalink.voice_update_handler, 'on_socket_response')
- client.lavalink.add_event_hook(self.track_hook)
- def cog_unload(self):
- self.client.lavalink._event_hooks.clear()
- async def cog_before_invoke(self, ctx):
- guild_check = ctx.guild is not None
- # This is essentially the same as `@commands.guild_only()`
- # except it saves us repeating ourselves (and also a few lines).
- if guild_check:
- await self.ensure_voice(ctx)
- # Ensure that the bot and command author share a mutual voicechannel.
- return guild_check
- async def cog_command_error(self, ctx, error):
- if isinstance(error, commands.CommandInvokeError):
- await ctx.send(error.original)
- # The above handles errors thrown in this cog and shows them to the user.
- # This shouldn't be a problem as the only errors thrown in this cog are from `ensure_voice`
- # which contain a reason string, such as "Join a voicechannel" etc. You can modify the above
- # if you want to do things differently.
- async def track_hook(self, event):
- if isinstance(event, lavalink.events.QueueEndEvent):
- guild_id = int(event.player.guild_id)
- await self.connect_to(guild_id, None)
- # Disconnect from the channel -- there's nothing else to play.
- async def connect_to(self, guild_id: int, channel_id: str):
- """ Connects to the given voicechannel ID. A channel_id of `None` means disconnect. """
- ws = self.client._connection._get_websocket(guild_id)
- await ws.voice_state(str(guild_id), channel_id)
- # The above looks dirty, we could alternatively use `bot.shards[shard_id].ws` but that assumes
- # the bot instance is an AutoShardedBot.
- @commands.command(aliases=['p'])
- async def play(self, ctx, *, query: str):
- """ Searches and plays a song from a given query. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- query = query.strip('<>')
- if not url_rx.match(query):
- query = f'ytsearch:{query}'
- results = await player.node.get_tracks(query)
- if not results or not results['tracks']:
- return await ctx.send('Nada encontrado!')
- embed = discord.Embed(color=discord.Color.blurple())
- if results['loadType'] == 'PLAYLIST_LOADED':
- tracks = results['tracks']
- for track in tracks:
- player.add(requester=ctx.author.id, track=track)
- embed.title = 'Lista de reprodução adicionada!'
- embed.description = f'{results["playlistInfo"]["name"]} - {len(tracks)} tracks'
- else:
- track = results['tracks'][0]
- embed.title = 'Música adicionada'
- embed.description = f'[{track["info"]["title"]}]({track["info"]["uri"]})'
- player.add(requester=ctx.author.id, track=track)
- await ctx.send(embed=embed)
- if not player.is_playing:
- await player.play()
- @commands.command()
- async def seek(self, ctx, *, seconds: int):
- """ Seeks to a given position in a track. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- track_time = player.position + (seconds * 1000)
- await player.seek(track_time)
- await ctx.send(f'Faixa movida para **{lavalink.utils.format_time(track_time)}**')
- @commands.command(aliases=['forceskip'])
- async def skip(self, ctx):
- """ Skips the current track. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.is_playing:
- return await ctx.send('Nada esta tocando no momento.')
- await player.skip()
- await ctx.send('⏭ | Música pulada.')
- @commands.command()
- async def stop(self, ctx):
- """ Stops the player and clears its queue. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.is_playing:
- return await ctx.send('Nada esta tocando no momento.')
- player.queue.clear()
- await player.stop()
- await ctx.send('⏹ | Parei todas as músicas.')
- @commands.command(aliases=['np', 'n', 'playing'])
- async def now(self, ctx):
- """ Shows some stats about the currently playing song. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.current:
- return await ctx.send('Nada está tocando no momento.')
- position = lavalink.utils.format_time(player.position)
- if player.current.stream:
- duration = '🔴 LIVE'
- else:
- duration = lavalink.utils.format_time(player.current.duration)
- song = f'**[{player.current.title}]({player.current.uri})**\n({position}/{duration})'
- embed = discord.Embed(color=discord.Color.blurple(),
- title='Agora tocando', description=song)
- await ctx.send(embed=embed)
- @commands.command(aliases=['q'])
- async def queue(self, ctx, page: int = 1):
- """ Shows the player's queue. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.queue:
- return await ctx.send('Não a mais músicas na lista.')
- items_per_page = 10
- pages = math.ceil(len(player.queue) / items_per_page)
- start = (page - 1) * items_per_page
- end = start + items_per_page
- queue_list = ''
- for index, track in enumerate(player.queue[start:end], start=start):
- queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\n'
- embed = discord.Embed(colour=discord.Color.blurple(),
- description=f'**{len(player.queue)} tracks**\n\n{queue_list}')
- embed.set_footer(text=f'Olhando página {page}/{pages}')
- await ctx.send(embed=embed)
- @commands.command(aliases=['resume'])
- async def pause(self, ctx):
- """ Pauses/Resumes the current track. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.is_playing:
- return await ctx.send('Nada está tocando no momento.')
- if player.paused:
- await player.set_pause(False)
- await ctx.send('⏯ | Música resumida')
- else:
- await player.set_pause(True)
- await ctx.send('⏯ | Música pausada')
- @commands.command(aliases=['vol'])
- async def volume(self, ctx, volume: int = None):
- """ Changes the player's volume (0-1000). """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not volume:
- return await ctx.send(f'🔈 | {player.volume}%')
- await player.set_volume(volume) # Lavalink will automatically cap values between, or equal to 0-1000.
- await ctx.send(f'🔈 | Volume setado para {player.volume}%')
- @commands.command()
- async def shuffle(self, ctx):
- """ Shuffles the player's queue. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.is_playing:
- return await ctx.send('Nada está tocando no momento.')
- player.shuffle = not player.shuffle
- await ctx.send('🔀 | Modo aleatório' + ('enabled' if player.shuffle else 'disabled'))
- @commands.command(aliases=['loop'])
- async def repeat(self, ctx):
- """ Repeats the current song until the command is invoked again. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.is_playing:
- return await ctx.send('Nada está tocando no momento.')
- player.repeat = not player.repeat
- await ctx.send('🔁 | Modo de repetição' + ('enabled' if player.repeat else 'disabled'))
- @commands.command()
- async def remove(self, ctx, index: int):
- """ Removes an item from the player's queue with the given index. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.queue:
- return await ctx.send('Nada está tocando no momento.')
- if index > len(player.queue) or index < 1:
- return await ctx.send(f'Index has to be **between** 1 and {len(player.queue)}')
- removed = player.queue.pop(index - 1) # Account for 0-index.
- await ctx.send(f'Removido**{removed.title}** da lista.')
- @commands.command()
- async def find(self, ctx, *, query):
- """ Lists the first 10 search results from a given query. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not query.startswith('ytsearch:') and not query.startswith('scsearch:'):
- query = 'ytsearch:' + query
- results = await player.node.get_tracks(query)
- if not results or not results['tracks']:
- return await ctx.send('Nada foi encontrado')
- tracks = results['tracks'][:10] # First 10 results
- o = ''
- for index, track in enumerate(tracks, start=1):
- track_title = track['info']['title']
- track_uri = track['info']['uri']
- o += f'`{index}.` [{track_title}]({track_uri})\n'
- embed = discord.Embed(color=discord.Color.blurple(), description=o)
- await ctx.send(embed=embed)
- @commands.command(aliases=['dc'])
- async def disconnect(self, ctx):
- """ Disconnects the player from the voice channel and clears its queue. """
- player = self.client.lavalink.players.get(ctx.guild.id)
- if not player.is_connected:
- return await ctx.send('Não estou conectado a nenhum canal de voz.')
- if not ctx.author.voice or (player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)):
- return await ctx.send('Você não esta em meu canal de voz!')
- player.queue.clear()
- await player.stop()
- await self.connect_to(ctx.guild.id, None)
- await ctx.send('*⃣ | Desconectei do canal de voz.')
- async def ensure_voice(self, ctx):
- """ This check ensures that the bot and command author are in the same voicechannel. """
- player = self.client.lavalink.players.create(ctx.guild.id, endpoint=str(ctx.guild.region))
- # Create returns a player if one exists, otherwise creates.
- should_connect = ctx.command.name in ('play') # Add commands that require joining voice to work.
- if not ctx.author.voice or not ctx.author.voice.channel:
- raise commands.CommandInvokeError('Entre em um canal de voz primeiro.')
- if not player.is_connected:
- if not should_connect:
- raise commands.CommandInvokeError('Você não esta em um canal de voz.')
- permissions = ctx.author.voice.channel.permissions_for(ctx.me)
- if not permissions.connect or not permissions.speak: # Check user limit too?
- raise commands.CommandInvokeError('Eu preciso da permissão`CONNECT` é `SPEAK` permissões.')
- player.store('channel', ctx.channel.id)
- await self.connect_to(ctx.guild.id, str(ctx.author.voice.channel.id))
- else:
- if int(player.channel_id) != ctx.author.voice.channel.id:
- raise commands.CommandInvokeError('Você precisa estar no mesmo canal de voz que eu.')
- def setup(client):
- client.add_cog(musica(client))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement