Advertisement
AgentLoneStar007

Discord Bot music_cog.py

Jun 8th, 2020 (edited)
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.43 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3. from discord.utils import get
  4. import youtube_dl
  5. import os
  6. import shutil
  7. from time import sleep
  8.  
  9. queues = {}
  10.  
  11. class Music(commands.Cog):
  12.     def __init__(self, client):
  13.         self.bot = client
  14.  
  15.     @commands.Cog.listener()
  16.     async def on_ready(self):
  17.         print('Music cog successfully loaded.')
  18.        
  19.     @commands.command(pass_context=True)
  20.     async def rpgmusic(self, ctx):
  21.         global voice
  22.         channel = ctx.message.author.voice.channel
  23.         voice = get(self.bot.voice_clients, guild=ctx.guild)
  24.  
  25.         if voice and voice.is_connected():
  26.             await voice.move_to(channel)
  27.         else:
  28.             voice = await channel.connect()
  29.             print(f'Bot connected to voice channel {channel}\n')
  30.    
  31.         await ctx.send(f'Playing some RPG music in {channel}.')
  32.         sleep(3)
  33.         voice.play(discord.FFmpegPCMAudio("./preset_music/rpgmusic.mp3"), after=lambda e: print(f'RPG music in {channel} has finished playing.'))
  34.         voice.source = discord.PCMVolumeTransformer(voice.source)
  35.         voice.source.volume = 0.05
  36.  
  37.    
  38.     @commands.command(pass_context=True)
  39.     async def join(self, ctx):
  40.         global voice
  41.         channel = ctx.message.author.voice.channel
  42.         voice = get(self.bot.voice_clients, guild=ctx.guild)
  43.  
  44.         if voice and voice.is_connected():
  45.             await voice.move_to(channel)
  46.  
  47.         else:
  48.             voice = await channel.connect()
  49.             print(f'Bot connected to voice channel {channel}\n')
  50.  
  51.         await ctx.send(f'I joined {channel}.')
  52.    
  53.  
  54.     @commands.command(pass_context=True)
  55.     async def leave(self, ctx):
  56.         channel = ctx.message.author.voice.channel
  57.         voice = get(self.bot.voice_clients, guild=ctx.guild)
  58.    
  59.         if voice and voice.is_connected():
  60.             await voice.disconnect()
  61.             print(f'Bot disconnected from channel {channel}.')
  62.        
  63.         else:
  64.             print('Not able to disconnect to a voice channel because bot wasn\'t in one.')
  65.  
  66.     @commands.command(pass_context=True, aliases=['p', 'pla'])
  67.     async def play(self, ctx, url: str):
  68.  
  69.         def check_queue():
  70.             Queue_infile = os.path.isdir("./Queue")
  71.             if Queue_infile is True:
  72.                 DIR = os.path.abspath(os.path.realpath("Queue"))
  73.                 length = len(os.listdir(DIR))
  74.                 still_q = length - 1
  75.                 try:
  76.                     first_file = os.listdir(DIR)[0]
  77.                 except:
  78.                     print("No more queued song(s).\n")
  79.                     queues.clear()
  80.                     return
  81.                 main_location = os.path.dirname(os.path.realpath(__file__))
  82.                 song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
  83.                 if length != 0:
  84.                     print("song has finished playing, continuing to next song.\n")
  85.                     print(f"Songs still in queue: {still_q}")
  86.                     song_there = os.path.isfile("song.mp3")
  87.                     if song_there:
  88.                         os.remove("song.mp3")
  89.                         shutil.move(song_path, main_location)
  90.                     for file in os.listdir("./"):
  91.                         if file.endswith(".mp3"):
  92.                             os.rename(file, 'song.mp3')
  93.  
  94.                     voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
  95.                     voice.source = discord.PCMVolumeTransformer(voice.source)
  96.                     voice.source.volume = 0.07
  97.  
  98.                 else:
  99.                     queues.clear()
  100.                     return
  101.             else:
  102.                 queues.clear()
  103.                 print("No songs were queued before the ending of the last song.\n")
  104.  
  105.         song_there = os.path.isfile("song.mp3")
  106.         try:
  107.             if song_there:
  108.                 os.remove("song.mp3")
  109.                 queues.clear()
  110.                 print("Removed old song file.")
  111.         except PermissionError:
  112.             print("Error in deleting song.mp3: file still in use.")
  113.             await ctx.send("Error in playing new song: there is still a song being played.")
  114.             return
  115.  
  116.         Queue_infile = os.path.isdir("./Queue")
  117.         try:
  118.             Queue_folder = "./Queue"
  119.             if Queue_infile is True:
  120.                 print("Removed old queue folder.")
  121.                 shutil.rmtree(Queue_folder)
  122.         except:
  123.             print("No queue folder to remove.")
  124.  
  125.         await ctx.send("Preparing song. Please wait.")
  126.  
  127.         voice = get(self.bot.voice_clients, guild=ctx.guild)
  128.  
  129.         ydl_opts = {
  130.             'format': 'bestaudio/best',
  131.             'postprocessors': [{
  132.                 'key': 'FFmpegExtractAudio',
  133.                 'preferredcodec': 'mp3',
  134.                 'preferredquality': '192',
  135.             }],
  136.         }
  137.  
  138.         with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  139.             print("Downloading audio now.\n")
  140.             ydl.download([url])
  141.  
  142.         for file in os.listdir("./"):
  143.             if file.endswith(".mp3"):
  144.                 name = file
  145.                 print(f"Renamed File: {file}\n")
  146.                 os.rename(file, "song.mp3")
  147.  
  148.         channel = ctx.message.author.voice.channel
  149.  
  150.         if voice and voice.is_connected():
  151.             await voice.move_to(channel)
  152.  
  153.         else:
  154.             voice = await channel.connect()
  155.             print(f'Bot connected to voice channel {channel}\n')
  156.  
  157.         voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
  158.         voice.source = discord.PCMVolumeTransformer(voice.source)
  159.         voice.source.volume = 0.07
  160.  
  161.         nname = name.rsplit("-", 2)
  162.         await ctx.send(f"Now playing {nname[0]}.")
  163.         print(f"Now playing {nname[0]}.\n")
  164.  
  165.  
  166.     @commands.command(pass_context=True)
  167.     async def pause(self, ctx):
  168.         voice = get(self.bot.voice_clients, guild=ctx.guild)
  169.  
  170.         if voice and voice.is_playing():
  171.             print('Song paused.')
  172.             voice.pause()
  173.             await ctx.send('Song has been paused.')
  174.         else:
  175.             print('Could not pause song; no song currently playing.')
  176.             await ctx.send('Could not pause the song as because there is no music playing.')
  177.  
  178.     @commands.command(pass_context=True)
  179.     async def resume(self, ctx):
  180.         voice = get(self.bot.voice_clients, guild=ctx.guild)
  181.  
  182.         if voice and voice.is_paused():
  183.             print('Song resumed.')
  184.             voice.resume()
  185.             await ctx.send('Resumed song.')
  186.         else:
  187.             print('Could not resume music; no song has been paused.')
  188.             await ctx.send('Could not resume song as because there is no paused music.')
  189.  
  190.     @commands.command(pass_context=True)
  191.     async def stop(self, ctx):
  192.         voice = get(self.bot.voice_clients, guild=ctx.guild)
  193.  
  194.         queues.clear()
  195.  
  196.         if voice and voice.is_playing():
  197.             print('Song stopped.')
  198.             voice.stop()
  199.             await ctx.send('Stopped playing current song.')
  200.         else:
  201.             print('Could not stop song as because there is no song currently playing.')
  202.             await ctx.send('Could not stop song as because there is no currently queued song.')
  203.  
  204.     @commands.command(pass_context=True)
  205.     async def queue(self, ctx, url: str):
  206.         Queue_infile = os.path.isdir("./Queue")
  207.         if Queue_infile is False:
  208.             os.mkdir("Queue")
  209.         DIR = os.path.abspath(os.path.realpath("Queue"))
  210.         q_num = len(os.listdir(DIR))
  211.         q_num += 1
  212.         add_queue = True
  213.         while add_queue:
  214.             if q_num in queues:
  215.                 q_num += 1
  216.             else:
  217.                 add_queue = False
  218.                 queues[q_num] = q_num
  219.  
  220.         queue_path = os.path.abspath(os.path.realpath("Queue") + f"\song{q_num}.%(ext)s")
  221.  
  222.         ydl_opts = {
  223.             'format': 'bestaudio/best',
  224.             'outtmpl': queue_path,
  225.             'postprocessors': [{
  226.                 'key': 'FFmpegExtractAudio',
  227.                 'preferredcodec': 'mp3',
  228.                 'preferredquality': '192',
  229.             }],
  230.         }
  231.  
  232.         with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  233.             print("Downloading audio now\n")
  234.             ydl.download([url])
  235.         await ctx.send("Adding song to the queue in position " + str(q_num) + ".")
  236.  
  237.         print("A new song has been added to the queue.\n")
  238.  
  239.  
  240. def setup(bot):
  241.     bot.add_cog(Music(bot))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement