Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import discord
- from discord.ext import commands
- from discord.utils import get
- import youtube_dl
- import os
- import shutil
- from time import sleep
- queues = {}
- class Music(commands.Cog):
- def __init__(self, client):
- self.bot = client
- @commands.Cog.listener()
- async def on_ready(self):
- print('Music cog successfully loaded.')
- @commands.command(pass_context=True)
- async def rpgmusic(self, ctx):
- global voice
- channel = ctx.message.author.voice.channel
- voice = get(self.bot.voice_clients, guild=ctx.guild)
- if voice and voice.is_connected():
- await voice.move_to(channel)
- else:
- voice = await channel.connect()
- print(f'Bot connected to voice channel {channel}\n')
- await ctx.send(f'Playing some RPG music in {channel}.')
- sleep(3)
- voice.play(discord.FFmpegPCMAudio("./preset_music/rpgmusic.mp3"), after=lambda e: print(f'RPG music in {channel} has finished playing.'))
- voice.source = discord.PCMVolumeTransformer(voice.source)
- voice.source.volume = 0.05
- @commands.command(pass_context=True)
- async def join(self, ctx):
- global voice
- channel = ctx.message.author.voice.channel
- voice = get(self.bot.voice_clients, guild=ctx.guild)
- if voice and voice.is_connected():
- await voice.move_to(channel)
- else:
- voice = await channel.connect()
- print(f'Bot connected to voice channel {channel}\n')
- await ctx.send(f'I joined {channel}.')
- @commands.command(pass_context=True)
- async def leave(self, ctx):
- channel = ctx.message.author.voice.channel
- voice = get(self.bot.voice_clients, guild=ctx.guild)
- if voice and voice.is_connected():
- await voice.disconnect()
- print(f'Bot disconnected from channel {channel}.')
- else:
- print('Not able to disconnect to a voice channel because bot wasn\'t in one.')
- @commands.command(pass_context=True, aliases=['p', 'pla'])
- async def play(self, ctx, url: str):
- def check_queue():
- Queue_infile = os.path.isdir("./Queue")
- if Queue_infile is True:
- DIR = os.path.abspath(os.path.realpath("Queue"))
- length = len(os.listdir(DIR))
- still_q = length - 1
- try:
- first_file = os.listdir(DIR)[0]
- except:
- print("No more queued song(s).\n")
- queues.clear()
- return
- main_location = os.path.dirname(os.path.realpath(__file__))
- song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
- if length != 0:
- print("song has finished playing, continuing to next song.\n")
- print(f"Songs still in queue: {still_q}")
- song_there = os.path.isfile("song.mp3")
- if song_there:
- os.remove("song.mp3")
- shutil.move(song_path, main_location)
- for file in os.listdir("./"):
- if file.endswith(".mp3"):
- os.rename(file, 'song.mp3')
- voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
- voice.source = discord.PCMVolumeTransformer(voice.source)
- voice.source.volume = 0.07
- else:
- queues.clear()
- return
- else:
- queues.clear()
- print("No songs were queued before the ending of the last song.\n")
- song_there = os.path.isfile("song.mp3")
- try:
- if song_there:
- os.remove("song.mp3")
- queues.clear()
- print("Removed old song file.")
- except PermissionError:
- print("Error in deleting song.mp3: file still in use.")
- await ctx.send("Error in playing new song: there is still a song being played.")
- return
- Queue_infile = os.path.isdir("./Queue")
- try:
- Queue_folder = "./Queue"
- if Queue_infile is True:
- print("Removed old queue folder.")
- shutil.rmtree(Queue_folder)
- except:
- print("No queue folder to remove.")
- await ctx.send("Preparing song. Please wait.")
- voice = get(self.bot.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:
- print("Downloading audio now.\n")
- ydl.download([url])
- for file in os.listdir("./"):
- if file.endswith(".mp3"):
- name = file
- print(f"Renamed File: {file}\n")
- os.rename(file, "song.mp3")
- channel = ctx.message.author.voice.channel
- if voice and voice.is_connected():
- await voice.move_to(channel)
- else:
- voice = await channel.connect()
- print(f'Bot connected to voice channel {channel}\n')
- voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
- voice.source = discord.PCMVolumeTransformer(voice.source)
- voice.source.volume = 0.07
- nname = name.rsplit("-", 2)
- await ctx.send(f"Now playing {nname[0]}.")
- print(f"Now playing {nname[0]}.\n")
- @commands.command(pass_context=True)
- async def pause(self, ctx):
- voice = get(self.bot.voice_clients, guild=ctx.guild)
- if voice and voice.is_playing():
- print('Song paused.')
- voice.pause()
- await ctx.send('Song has been paused.')
- else:
- print('Could not pause song; no song currently playing.')
- await ctx.send('Could not pause the song as because there is no music playing.')
- @commands.command(pass_context=True)
- async def resume(self, ctx):
- voice = get(self.bot.voice_clients, guild=ctx.guild)
- if voice and voice.is_paused():
- print('Song resumed.')
- voice.resume()
- await ctx.send('Resumed song.')
- else:
- print('Could not resume music; no song has been paused.')
- await ctx.send('Could not resume song as because there is no paused music.')
- @commands.command(pass_context=True)
- async def stop(self, ctx):
- voice = get(self.bot.voice_clients, guild=ctx.guild)
- queues.clear()
- if voice and voice.is_playing():
- print('Song stopped.')
- voice.stop()
- await ctx.send('Stopped playing current song.')
- else:
- print('Could not stop song as because there is no song currently playing.')
- await ctx.send('Could not stop song as because there is no currently queued song.')
- @commands.command(pass_context=True)
- async def queue(self, ctx, url: str):
- Queue_infile = os.path.isdir("./Queue")
- if Queue_infile is False:
- os.mkdir("Queue")
- DIR = os.path.abspath(os.path.realpath("Queue"))
- q_num = len(os.listdir(DIR))
- q_num += 1
- add_queue = True
- while add_queue:
- if q_num in queues:
- q_num += 1
- else:
- add_queue = False
- queues[q_num] = q_num
- queue_path = os.path.abspath(os.path.realpath("Queue") + f"\song{q_num}.%(ext)s")
- ydl_opts = {
- 'format': 'bestaudio/best',
- 'outtmpl': queue_path,
- 'postprocessors': [{
- 'key': 'FFmpegExtractAudio',
- 'preferredcodec': 'mp3',
- 'preferredquality': '192',
- }],
- }
- with youtube_dl.YoutubeDL(ydl_opts) as ydl:
- print("Downloading audio now\n")
- ydl.download([url])
- await ctx.send("Adding song to the queue in position " + str(q_num) + ".")
- print("A new song has been added to the queue.\n")
- def setup(bot):
- bot.add_cog(Music(bot))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement