Advertisement
Guest User

music.py

a guest
May 12th, 2019
1,228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.98 KB | None | 0 0
  1. """
  2. Made by That Guy#5275
  3. """
  4. import discord
  5. from discord.ext import commands
  6.  
  7. import asyncio
  8. import itertools
  9. import sys
  10. import traceback
  11. from async_timeout import timeout
  12. from functools import partial
  13. from youtube_dl import YoutubeDL
  14.  
  15.  
  16. ytdlopts = {
  17.     'format': 'bestaudio/best',
  18.     'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
  19.     'restrictfilenames': True,
  20.     'noplaylist': True,
  21.     'nocheckcertificate': True,
  22.     'ignoreerrors': False,
  23.     'logtostderr': False,
  24.     'quiet': True,
  25.     'no_warnings': True,
  26.     'default_search': 'auto',
  27.     'source_address': '0.0.0.0'  # ipv6 addresses cause issues sometimes
  28. }
  29.  
  30. ffmpegopts = {
  31.     'before_options': '-nostdin -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
  32.     'options': '-vn'
  33. }
  34.  
  35. ytdl = YoutubeDL(ytdlopts)
  36.  
  37.  
  38. class VoiceConnectionError(commands.CommandError):
  39.     """Custom Exception class for connection errors."""
  40.  
  41.  
  42. class InvalidVoiceChannel(VoiceConnectionError):
  43.     """Exception for cases of invalid Voice Channels."""
  44.  
  45.  
  46. class YTDLSource(discord.PCMVolumeTransformer):
  47.  
  48.     def __init__(self, source, *, data, requester):
  49.         super().__init__(source)
  50.         self.requester = requester
  51.  
  52.         self.title = data.get('title')
  53.         self.web_url = data.get('webpage_url')
  54.  
  55.         # YTDL info dicts (data) have other useful information you might want
  56.         # https://github.com/rg3/youtube-dl/blob/master/README.md
  57.  
  58.     def __getitem__(self, item: str):
  59.         """Allows us to access attributes similar to a dict.
  60.        This is only useful when you are NOT downloading.
  61.        """
  62.         return self.__getattribute__(item)
  63.  
  64.     @classmethod
  65.     async def create_source(cls, ctx, search: str, *, loop, download=False):
  66.         loop = loop or asyncio.get_event_loop()
  67.  
  68.         to_run = partial(ytdl.extract_info, url=search, download=download)
  69.         data = await loop.run_in_executor(None, to_run)
  70.  
  71.         if 'entries' in data:
  72.             # take first item from a playlist
  73.             data = data['entries'][0]
  74.  
  75.         await ctx.send(f'```ini\n[Added {data["title"]} to the Queue.]\n```', delete_after=15)
  76.  
  77.         if download:
  78.             source = ytdl.prepare_filename(data)
  79.         else:
  80.             return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}
  81.  
  82.         return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
  83.  
  84.     @classmethod
  85.     async def regather_stream(cls, data, *, loop):
  86.         """Used for preparing a stream, instead of downloading.
  87.        Since Youtube Streaming links expire."""
  88.         loop = loop or asyncio.get_event_loop()
  89.         requester = data['requester']
  90.  
  91.         to_run = partial(ytdl.extract_info,
  92.                          url=data['webpage_url'], download=False)
  93.         data = await loop.run_in_executor(None, to_run)
  94.  
  95.         return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)
  96.  
  97.  
  98. class MusicPlayer:
  99.     """A class which is assigned to each guild using the bot for Music.
  100.    This class implements a queue and loop, which allows for different guilds to listen to different playlists
  101.    simultaneously.
  102.    When the bot disconnects from the Voice it's instance will be destroyed.
  103.    """
  104.  
  105.     __slots__ = ('bot', '_guild', '_channel', '_cog',
  106.                  'queue', 'next', 'current', 'np', 'volume')
  107.  
  108.     def __init__(self, ctx):
  109.         self.bot = ctx.bot
  110.         self._guild = ctx.guild
  111.         self._channel = ctx.channel
  112.         self._cog = ctx.cog
  113.  
  114.         self.queue = asyncio.Queue()
  115.         self.next = asyncio.Event()
  116.  
  117.         self.np = None  # Now playing message
  118.         self.volume = .5
  119.         self.current = None
  120.  
  121.         ctx.bot.loop.create_task(self.player_loop())
  122.  
  123.     async def player_loop(self):
  124.         """Our main player loop."""
  125.         await self.bot.wait_until_ready()
  126.  
  127.         while not self.bot.is_closed():
  128.             self.next.clear()
  129.  
  130.             try:
  131.                 # Wait for the next song. If we timeout cancel the player and disconnect...
  132.                 async with timeout(300):  # 5 minutes...
  133.                     source = await self.queue.get()
  134.             except asyncio.TimeoutError:
  135.                 return self.destroy(self._guild)
  136.  
  137.             if not isinstance(source, YTDLSource):
  138.                 # Source was probably a stream (not downloaded)
  139.                 # So we should regather to prevent stream expiration
  140.                 try:
  141.                     source = await YTDLSource.regather_stream(source, loop=self.bot.loop)
  142.                 except Exception as e:
  143.                     await self._channel.send(f'There was an error processing your song.\n'
  144.                                              f'```css\n[{e}]\n```')
  145.                     continue
  146.  
  147.             source.volume = self.volume
  148.             self.current = source
  149.  
  150.             self._guild.voice_client.play(
  151.                 source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set))
  152.             self.np = await self._channel.send(f'**Now Playing:** `{source.title}` requested by '
  153.                                                f'`{source.requester}`')
  154.             await self.next.wait()
  155.  
  156.             # Make sure the FFmpeg process is cleaned up.
  157.             source.cleanup()
  158.             self.current = None
  159.  
  160.             try:
  161.                 # We are no longer playing this song...
  162.                 await self.np.delete()
  163.             except discord.HTTPException:
  164.                 pass
  165.  
  166.     def destroy(self, guild):
  167.         """Disconnect and cleanup the player."""
  168.         return self.bot.loop.create_task(self._cog.cleanup(guild))
  169.  
  170.  
  171. class Music(commands.Cog):
  172.     """Music related commands."""
  173.  
  174.     __slots__ = ('bot', 'players')
  175.  
  176.     def __init__(self, bot):
  177.         self.bot = bot
  178.         self.players = {}
  179.  
  180.     async def cleanup(self, guild):
  181.         try:
  182.             await guild.voice_client.disconnect()
  183.         except AttributeError:
  184.             pass
  185.  
  186.         try:
  187.             del self.players[guild.id]
  188.         except KeyError:
  189.             pass
  190.  
  191.     async def __local_check(self, ctx):
  192.         """A local check which applies to all commands in this cog."""
  193.         if not ctx.guild:
  194.             raise commands.NoPrivateMessage
  195.         return True
  196.  
  197.     async def __error(self, ctx, error):
  198.         """A local error handler for all errors arising from commands in this cog."""
  199.         if isinstance(error, commands.NoPrivateMessage):
  200.             try:
  201.                 return await ctx.send('This command can not be used in Private Messages.')
  202.             except discord.HTTPException:
  203.                 pass
  204.         elif isinstance(error, InvalidVoiceChannel):
  205.             await ctx.send('Error connecting to Voice Channel. '
  206.                            'Please make sure you are in a valid channel or provide me with one')
  207.  
  208.         print('Ignoring exception in command {}:'.format(
  209.             ctx.command), file=sys.stderr)
  210.         traceback.print_exception(
  211.             type(error), error, error.__traceback__, file=sys.stderr)
  212.  
  213.     def get_player(self, ctx):
  214.         """Retrieve the guild player, or generate one."""
  215.         try:
  216.             player = self.players[ctx.guild.id]
  217.         except KeyError:
  218.             player = MusicPlayer(ctx)
  219.             self.players[ctx.guild.id] = player
  220.  
  221.         return player
  222.  
  223.     @commands.command(name='connect', aliases=['join'])
  224.     async def connect_(self, ctx, *, channel: discord.VoiceChannel = None):
  225.         """Connect to voice.
  226.        Parameters
  227.        ------------
  228.        channel: discord.VoiceChannel [Optional]
  229.            The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in
  230.            will be made.
  231.        This command also handles moving the bot to different channels.
  232.        """
  233.         if not channel:
  234.             try:
  235.                 channel = ctx.author.voice.channel
  236.             except AttributeError:
  237.                 raise InvalidVoiceChannel(
  238.                     'No channel to join. Please either specify a valid channel or join one.')
  239.  
  240.         vc = ctx.voice_client
  241.  
  242.         if vc:
  243.             if vc.channel.id == channel.id:
  244.                 return
  245.             try:
  246.                 await vc.move_to(channel)
  247.             except asyncio.TimeoutError:
  248.                 raise VoiceConnectionError(
  249.                     f'Moving to channel: <{channel}> timed out.')
  250.         else:
  251.             try:
  252.                 await channel.connect()
  253.             except asyncio.TimeoutError:
  254.                 raise VoiceConnectionError(
  255.                     f'Connecting to channel: <{channel}> timed out.')
  256.  
  257.         await ctx.send(f'Connected to: **{channel}**', delete_after=20)
  258.  
  259.     @commands.command(name='play', aliases=['sing'])
  260.     async def play_(self, ctx, *, search: str):
  261.         """Request a song and add it to the queue.
  262.        This command attempts to join a valid voice channel if the bot is not already in one.
  263.        Uses YTDL to automatically search and retrieve a song.
  264.        Parameters
  265.        ------------
  266.        search: str [Required]
  267.            The song to search and retrieve using YTDL. This could be a simple search, an ID or URL.
  268.        """
  269.         await ctx.trigger_typing()
  270.  
  271.         vc = ctx.voice_client
  272.  
  273.         if not vc:
  274.             await ctx.invoke(self.connect_)
  275.  
  276.         player = self.get_player(ctx)
  277.  
  278.         # If download is False, source will be a dict which will be used later to regather the stream.
  279.         # If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
  280.         source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)
  281.  
  282.         await player.queue.put(source)
  283.  
  284.     @commands.command(name='pause')
  285.     async def pause_(self, ctx):
  286.         """Pause the currently playing song."""
  287.         vc = ctx.voice_client
  288.  
  289.         if not vc or not vc.is_playing():
  290.             return await ctx.send('I am not currently playing anything!', delete_after=20)
  291.         elif vc.is_paused():
  292.             return
  293.  
  294.         vc.pause()
  295.         await ctx.send(f'**`{ctx.author}`**: Paused the song!')
  296.  
  297.     @commands.command(name='resume')
  298.     async def resume_(self, ctx):
  299.         """Resume the currently paused song."""
  300.         vc = ctx.voice_client
  301.  
  302.         if not vc or not vc.is_connected():
  303.             return await ctx.send('I am not currently playing anything!', delete_after=20)
  304.         elif not vc.is_paused():
  305.             return
  306.  
  307.         vc.resume()
  308.         await ctx.send(f'**`{ctx.author}`**: Resumed the song!')
  309.  
  310.     @commands.command(name='skip')
  311.     async def skip_(self, ctx):
  312.         """Skip the song."""
  313.         vc = ctx.voice_client
  314.  
  315.         if not vc or not vc.is_connected():
  316.             return await ctx.send('I am not currently playing anything!', delete_after=20)
  317.  
  318.         if vc.is_paused():
  319.             pass
  320.         elif not vc.is_playing():
  321.             return
  322.  
  323.         vc.stop()
  324.         await ctx.send(f'**`{ctx.author}`**: Skipped the song!')
  325.  
  326.     @commands.command(name='queue', aliases=['q', 'playlist'])
  327.     async def queue_info(self, ctx):
  328.         """Retrieve a basic queue of upcoming songs."""
  329.         vc = ctx.voice_client
  330.  
  331.         if not vc or not vc.is_connected():
  332.             return await ctx.send('I am not currently connected to voice!', delete_after=20)
  333.  
  334.         player = self.get_player(ctx)
  335.         if player.queue.empty():
  336.             return await ctx.send('There are currently no more queued songs.')
  337.  
  338.         # Grab up to 5 entries from the queue...
  339.         upcoming = list(itertools.islice(player.queue._queue, 0, 5))
  340.  
  341.         fmt = '\n'.join(f'**`{_["title"]}`**' for _ in upcoming)
  342.         embed = discord.Embed(
  343.             title=f'Upcoming - Next {len(upcoming)}', description=fmt)
  344.  
  345.         await ctx.send(embed=embed)
  346.  
  347.     @commands.command(name='now_playing', aliases=['np', 'current', 'currentsong', 'playing'])
  348.     async def now_playing_(self, ctx):
  349.         """Display information about the currently playing song."""
  350.         vc = ctx.voice_client
  351.  
  352.         if not vc or not vc.is_connected():
  353.             return await ctx.send('I am not currently connected to voice!', delete_after=20)
  354.  
  355.         player = self.get_player(ctx)
  356.         if not player.current:
  357.             return await ctx.send('I am not currently playing anything!')
  358.  
  359.         try:
  360.             # Remove our previous now_playing message.
  361.             await player.np.delete()
  362.         except discord.HTTPException:
  363.             pass
  364.  
  365.         player.np = await ctx.send(f'**Now Playing:** `{vc.source.title}` '
  366.                                    f'requested by `{vc.source.requester}`')
  367.  
  368.     @commands.command(name='volume', aliases=['vol'])
  369.     async def change_volume(self, ctx, *, vol: float):
  370.         """Change the player volume.
  371.        Parameters
  372.        ------------
  373.        volume: float or int [Required]
  374.            The volume to set the player to in percentage. This must be between 1 and 100.
  375.        """
  376.         vc = ctx.voice_client
  377.  
  378.         if not vc or not vc.is_connected():
  379.             return await ctx.send('I am not currently connected to voice!', delete_after=20)
  380.  
  381.         if not 0 < vol < 101:
  382.             return await ctx.send('Please enter a value between 1 and 100.')
  383.  
  384.         player = self.get_player(ctx)
  385.  
  386.         if vc.source:
  387.             vc.source.volume = vol / 100
  388.  
  389.         player.volume = vol / 100
  390.         await ctx.send(f'**`{ctx.author}`**: Set the volume to **{vol}%**')
  391.  
  392.     @commands.command(name='stop')
  393.     async def stop_(self, ctx):
  394.         """Stop the currently playing song and destroy the player.
  395.        !Warning!
  396.            This will destroy the player assigned to your guild, also deleting any queued songs and settings.
  397.        """
  398.         vc = ctx.voice_client
  399.  
  400.         if not vc or not vc.is_connected():
  401.             return await ctx.send('I am not currently playing anything!', delete_after=20)
  402.  
  403.         await self.cleanup(ctx.guild)
  404.  
  405.  
  406. def setup(bot):
  407.     bot.add_cog(Music(bot))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement