async def voice(self, ctx, voice: str): """Set Speech API voice type""" global voice_type voice_dict = { 'IN_F': 'en-IN-Wavenet-A', 'IN_M': 'en-IN-Wavenet-C', 'US_F': 'en-US-Wavenet-G', 'US_M': 'en-US-Wavenet-B', 'GB_F': 'en-GB-Wavenet-A', 'GB_M': 'en-GB-Wavenet-B', 'AU_F': 'en-AU-Wavenet-C', 'AU_M': 'en-AU-Wavenet-B' } if voice in voice_dict: voice_type = voice_dict[voice] else: voice_type = voice await ctx.send("New voice set to: " + voice_type) audioClip = TTSSource(voice_type, "New voice set.") while not audioClip.done: await asyncio.sleep(1) source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(audioClip.filename, **ffmpeg_options)) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
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 done, playing next queued\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.4 else: queues.clear() return else: queues.clear() print("No songs were queued before the ending of the last song\n")
def after_play(self, error, gs: GuildState): """ Called when a song is finished. The bot either plays the next song if there is one, or disconnect. """ if not gs.voice_client or\ not gs.voice_client.is_connected(): return # Nothing to do if gs.playlist == []: # Nothing to play next coro = gs.voice_client.disconnect() gs.voice_client = None gs.currently_playing = None asyncio.run_coroutine_threadsafe(coro, self.bot.loop) return # Plays the next song gs.currently_playing = gs.playlist.pop(0) song_audiosource = discord.FFmpegPCMAudio(gs.currently_playing) song_audiosource = discord.PCMVolumeTransformer(song_audiosource, 0.4) gs.voice_client.play(song_audiosource, after=lambda e: self.after_play(e, gs))
async def _clip(self, ctx, query=None): clips = [ f for f in os.listdir('./audio_clips') if f.endswith(('.m4a', '.mp3', '.webm')) ] if not query: return await ctx.send( "```Available clips:\n\t" + '\n\t'.join([f"{i+1}. {f}" for i, f in enumerate(clips)]) + "```") # Choose query for clip in clips: if clip.lower().startswith(query.lower()): query = './audio_clips/' + clip break source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query)) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send(f"Now playing: {query.split('/')[-1]}")
def on_off(ctx): global t_f, stopped, voice t_f = True song_there = os.path.isfile('song.mp3') try: if song_there: os.remove('song.mp3') except PermissionError: pass print('Закон.') stopped.remove(stopped[0]) if len(stopped) != 0: try: t_f = False url = stopped[0] voice = get(ibio.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: ydl.download([url]) for file in os.listdir('./'): if file.endswith('.mp3'): os.rename(file, 'song.mp3') voice.play(discord.FFmpegPCMAudio('song.mp3'), after=lambda e: on_off(ctx)) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 1 except Exception: on_off(ctx)
async def play(ctx): voice = get(bot.voice_clients, guild=ctx.guild) files = [] for r, d, f in os.walk(path): for file in f: if '.mp3' in file: files.append(os.path.join(r, file)) i = 0 while i < len(files): num.append(i) i = i + 1 random.shuffle(num) reactions = ['⏭️'] message = await ctx.send(":musical_note:Playing music:sparkles: ") for name in reactions: emoji = get(ctx.guild.emojis, name=name) await message.add_reaction(emoji or name) playNow(ctx, files, 0) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.5
async def play(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 done, playing next queued\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("Trying to delete song file, but it's being played") await ctx.send("ERROR: Music playing") 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 old Queue folder") await ctx.send("Getting everything ready now") voice = get(bot.voice_clients, guild=ctx.guild) ydl_opts = { 'format': 'bestaudio/best', 'quiet': False, 'outtmpl': "./song.mp3", 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } song_search = " ".join(url) try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") ydl.download([f"ytsearch1:{song_search}"]) except: print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)") c_path = os.path.dirname(os.path.realpath(__file__)) system("spotdl -ff song -f " + '"' + c_path + '"' + " -s " + song_search) voice.play(discord.FFmpegPCMAudio("./song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07
async def channel_play_song(self, ctx: commands.Context, query: str): channel = ctx.author.voice.channel await self.channel_connect(channel) try: pytube.extract.video_id(query) except pytube.exceptions.RegexMatchError: try: search_result = await self.bot.youtube_client.search(query) except (AttributeError, HTTPError): video_url = None else: video_url = search_result.url if search_result is not None else None else: video_url = query if video_url is not None: video_id = pytube.extract.video_id(video_url) try: video = await self.bot.loop.run_in_executor(None, pytube.YouTube, video_url) except: embed = self.bot.generate_embed('⚠️', 'Nie można zagrać tego utworu') await self.bot.send(ctx, embed=embed) else: embed = self.generate_embed(channel, video, 'Pobieranie', '⏳') message = await self.bot.send(ctx, embed=embed) streams = video.streams.filter(only_audio=True).order_by('abr').desc() stream = streams[0] i = 0 while stream.filesize > configuration['disco_max_file_size_in_mib'] * 1_048_576: i += 1 try: stream = streams[i] except IndexError: embed = self.generate_embed(channel, video, 'Plik zbyt duży', '⚠️') break else: path = os.path.join(self.cache_dir_path, f'{video_id} - {stream.default_filename}') if not os.path.isfile(path): await self.bot.loop.run_in_executor( None, functools.partial( stream.download, output_path=self.cache_dir_path, filename_prefix=f'{video_id} - ' ), ) if channel.guild.voice_client is not None: channel.guild.voice_client.stop() song_audio = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(path), self.servers[channel.guild.id]['volume'] ) self.servers[channel.guild.id]['song_audio'] = song_audio self.servers[channel.guild.id]['song_url'] = video_url async def try_edit(embed: discord.Embed): try: await message.edit(embed=embed) except (discord.Forbidden, discord.NotFound): pass def after(error): song_audio.cleanup() embed = self.generate_embed(channel, video, 'Zakończono', '⏹') self.bot.loop.create_task(try_edit(embed)) embed = self.generate_embed(channel, video, 'Odtwarzanie', '▶️') await self.channel_connect(channel) channel.guild.voice_client.play(self.servers[channel.guild.id]['song_audio'], after=after) await message.edit(embed=embed) else: embed = self.bot.generate_embed('🙁', f'Brak wyników dla zapytania "{query}"') await self.bot.send(ctx, embed=embed)
async def on_message(message): general_channel = client.get_channel(message.channel.category_id) ids = [member.id for member in message.guild.members] print(ids) auth_avatar = message.author.avatar_url_as(format='jpeg') print(auth_avatar) print(message.content) cmd = (message.content)[:1] if cmd[0] == PREFIX: mess = breakMess((message.content).lower()) print("Received Command : ", mess) #print(mess) if mess[1] == "help": my_embed = discord.Embed( title="All About Me", description= "Lorenzo Von Matterhorn Is An Awesome Bot coded by the even more awesome @whokilleddb.\nHe likes to be called Bro.", color=0x00ff00) my_embed.add_field(name="Version:", value=VERSION, inline=False) my_embed.set_footer(text="Suit Up !") my_embed.set_author(name="WhoKilledDB") await message.channel.send(embed=my_embed) if mess[1] == "makemesad": await message.channel.send("Remember , You asked for this !") await message.channel.send(random.choice(himym)) if mess[1] == "gay": if int(mess[0]) == 2: if mess[2][2] != '!': userid = int(mess[2][2:len(mess[2]) - 1]) if mess[2][2] == '!': userid = int(mess[2][3:len(mess[2]) - 1]) print(f"User Tag : {userid}") user = client.get_user(userid) if not user: print("User Not Found") else: gayThis(user.avatar_url_as(format='jpeg', size=256)) await message.channel.send( file=discord.File("./gayed.jpeg")) os.remove('./gayed.jpeg') os.remove('./avatar.jpeg') if mess[1] == "capitalist": if int(mess[0]) == 2: if mess[2][2] != '!': userid = int(mess[2][2:len(mess[2]) - 1]) if mess[2][2] == '!': userid = int(mess[2][3:len(mess[2]) - 1]) print(f"User Tag : {userid}") user = client.get_user(userid) if not user: print("User Not Found") else: capitalistThis(user.avatar_url_as(format='jpeg', size=256)) await message.channel.send(file=discord.File("./my.jpg")) os.remove('./my.jpg') os.remove('./avatar.jpeg') if mess[1][:5] == "there": if (random.randint(1, 2)) % 2 == 0: await message.channel.send("Yup") else: await message.channel.send( "Always There For You :) <@{}>".format(message.author.id)) if mess[1] == "quote": if int(mess[0]) == 1: await message.channel.send( "Bro ! What do you even wanna know ? The Brocode or The Playbook ?" ) if int(mess[0]) == 3 or int(mess[0]) == 2: if mess[2] == "playbook": await message.channel.send(random.choice(playbook)) if mess[2] == "brocode": if (int(mess[0]) == 3 and int(mess[3]) > 0 and int(mess[3]) <= 82): await message.channel.send(brocode[int(mess[3] - 1)]) else: await message.channel.send(random.choice(brocode)) if mess[1] == "meme": if int(mess[0]) == 1: lst = red(random.choice(subs)) my_embed = discord.Embed(title=lst[0]) my_embed.set_image(url=lst[1]) await message.channel.send(embed=my_embed) else: lst = red(((message.content)[6:]).replace(" ", "")) em = discord.Embed(title=lst[0]) em.set_image(url=lst[1]) await message.channel.send(embed=em) if mess[1] == "join": channel = "" print(channel) if (message.author.voice) != None: channel = message.author.voice.channel voice = get(client.voice_clients, guild=message.guild) if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() await voice.disconnect() if voice and voice.is_connected(): await voice.move_to(channel) await message.channel.send( "I am in {} bitches".format(channel)) else: voice = await channel.connect() await message.channel.send( "I am in {} Voice bitches".format(channel)) else: await message.channel.send( "Bro You Need To Join A Voice Channel Yourself First !") if mess[1] == "leave": voice = get(client.voice_clients, guild=message.guild) if voice and voice.is_connected(): await voice.disconnect() VOICE_FLAG = False await message.channel.send(f"Imma Ight Head Out Of Voice") else: voice = await message.channel.send( "Bruh am not even in a Voice Channel !") if mess[1] == "joke": await message.channel.send(joke()) if mess[1] == "play": voice = get(client.voice_clients, guild=message.guild) if (message.author.voice) == None: await message.channel.send( "Bruh You Are not even in a Voice Channel !") await message.channel.send("Add Yourself In First") else: if not (voice and voice.is_connected()): channel = message.author.voice.channel voice = get(client.voice_clients, guild=message.guild) if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() await voice.disconnect() if voice and voice.is_connected(): await voice.move_to(channel) await message.channel.send( "I Let Myself In That Voice Channel ") else: voice = await channel.connect() await message.channel.send("I Helped Myself In") if int(mess[0]) > 2 and not mess[3].isnumeric(): str1 = (message.content[6:]).replace(" ", "+") elif int(mess[0]) == 1: str1 = "NeverGonnaGiveYouUp" else: str1 = mess[2] name = "" song_there = os.path.isfile("song.mp3") try: if song_there: os.remove("song.mp3") print("Removed Song File") except PermissionError: print("The Song Is On") await message.channel.send( "Bro I think the song is already playing !") return await message.channel.send("Firing That Up Now !") voice = get(client.voice_clients, guild=message.guild) ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } if int(mess[0]) == 3 and mess[3].isnumeric(): v_url = searchQuery(str1, int(mess[3])) else: v_url = searchQuery(str1, 0) with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading Song") ydl.download([v_url]) for file in os.listdir("./"): if file.endswith(".mp3"): name = file print(f"Renamed File {file}") os.rename(file, "song.mp3") try: voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: print("Vibing")) voice.souce = discord.PCMVolumeTransformer(voice.source) voice.souce.volume = 0.07 await message.channel.send(f"Playing {v_url}") except ClientException: await message.channel.send( "Looks like I am out of the voice channel !") if (message.author.voice) != None: channel = message.author.voice.channel voice = get(client.voice_clients, guild=message.guild) if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() await voice.disconnect() if voice and voice.is_connected(): await voice.move_to(channel) await message.channel.send( "I am back in {} bitches".format(channel)) else: voice = await channel.connect() await message.channel.send( "I am back in {} Voice bitches".format(channel) ) await message.channel.send("Let Me Play That Again !") await message.channel.send( f"~play {(message.content)[6:]}") else: await message.channel.send( "Bro You Need To Join A Voice Channel As Well!")
async def on_voice_state_update(self, member, before, after): if before.channel == after.channel: return guild = member.guild vc = guild.voice_client if guild in self.lock: return active = self.config.get('sound', guild.id) if not active: return most_people = self.get_fullest_channel(guild) # member joins in channel if after.channel is not None: if most_people is None and vc and len(vc.channel.members) == 1: logger.debug(f'disconnected from {vc.channel}') await vc.disconnect() return if after.channel == most_people and guild.me not in most_people.members: logger.debug(f'connecting to channel {most_people}') self.lock.append(guild) await asyncio.sleep(1) self.lock.remove(guild) if vc is None: await most_people.connect() else: member_ids = [m.id for m in after.channel.members] self.cache[guild] = member_ids await vc.move_to(most_people) logger.debug(f'connected to {most_people}') return # if after channel is None (leave) we look if we're in the fullest channel elif most_people and guild.me not in most_people.members: if vc is None: await most_people.connect() else: await vc.move_to(most_people) logger.debug(f'connected to {most_people}') return # if after channel is None (leave) looks if its connected and the only # one in the channel and leaves if, since we handle channel moves above elif vc and len(vc.channel.members) == 1: logger.debug(f'disconnected from {vc.channel}') await vc.disconnect() return if vc is None: return if vc.channel in (before.channel, after.channel): # bot join connect which seems to take a while internally if guild.me == member: if before.channel is None: while not vc.is_connected(): await asyncio.sleep(0.5) else: member_ids = self.cache.get(guild, []) ids = [m.id for m in vc.channel.members] if sorted(member_ids) == sorted(ids): return if not vc.is_playing() and vc.is_connected(): state = 'connect' if after.channel == vc.channel else 'disconnect' sound_path = self.get_sound_path(member.id, state) logger.debug(f'playing {state}-sound from {member}') sound = discord.FFmpegPCMAudio(source=sound_path) source = discord.PCMVolumeTransformer(sound, 0.18) vc.play(source=source)
async def play(self, ctx: commands.Context, name: str, *, args=None): """ Play a sound. :param name: The name of the sound to play. :param args: The volume/speed of playback, in format v[XX%] s[SS%]. e.g. v50 s100. """ if not name: raise commands.BadArgument('Invalid sound name.') async with self.bot.pool.acquire() as conn: filename = await conn.fetchval( 'SELECT filename FROM sounds WHERE guild_id = $1 AND name = $2', ctx.guild.id, name.lower()) if filename is None: raise commands.BadArgument(f'Sound **{name}** does not exist.') file = self.sound_path / str(ctx.guild.id) / filename volume = None speed = None if args is not None: for arg in args.split(): if volume is None and arg.startswith('v'): try: volume = int( arg[1:-1] if arg.endswith('%') else arg[1:]) if volume < 0: raise commands.BadArgument( 'Volume cannot be less than 0%.') except ValueError: raise commands.BadArgument( f'Could not parse `{args}`.') elif speed is None and arg.startswith('s'): try: speed = int( arg[1:-1] if arg.endswith('%') else arg[1:]) if not (50 <= speed <= 200): raise commands.BadArgument( 'Speed must be between 50% and 200%.') except ValueError: raise commands.BadArgument( f'Could not parse `{args}`.') if volume is None: volume = 100 if speed is None: speed = 100 channel = ctx.author.voice.channel if channel is None: raise commands.CommandError('No target channel.') vclient: VoiceClient = ctx.guild.voice_client or await channel.connect( ) vclient.move_to(channel) source = discord.FFmpegPCMAudio( str(file), options=f'-filter:a "atempo={speed/100}"') source = discord.PCMVolumeTransformer(source, volume=volume / 100) async def stop(): await vclient.disconnect(force=True) return name def wrapper(error): try: coro = self.playing.pop(ctx.guild.id) future = asyncio.run_coroutine_threadsafe(coro, self.bot.loop) try: future.result() except: pass except KeyError: # sound was stopped with stop command, so do nothing. pass self.playing[ctx.guild.id] = stop() async with self.bot.pool.acquire() as conn: await conn.execute( 'UPDATE sounds SET played = played + 1 WHERE guild_id = $1 AND name = $2', ctx.guild.id, name) vclient.play(source=source, after=wrapper)
async def PlayPomodoro(self, ctx): source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(self.basePath + "Lyt nu.mp3")) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
async def play_local(self, ctx, *, query): """Plays a file from the local filesystem.""" source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query)) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send('Now playing: {}'.format(query))
async def play(self, ctx, *url: str): global song_list_queue, collection voice = get(self.bot.voice_clients, guild=ctx.guild) if voice is None: await ctx.send("You have to add me to a voice channel first") return # List of predifined URLs to download from if user does not specify a song list_of_bhajans = [ 'https://www.youtube.com/watch?v=iW16WWmWZL4', 'https://www.youtube.com/watch?v=2yAzgg3zEjM', 'https://www.youtube.com/watch?v=Ezhdk82sR1Y', ] if not url: url = random.choice(list_of_bhajans) """ A downloaded song is added to a folder named by the server ID and named as 'song.mp3' Songs in queue are added to a folder 'Queue' within this folder and are named as 'song1.mp3', 'song2.mp3' and so on """ def check_queue(): Queue_infile = os.path.isdir("./" + str(ctx.guild.id) + "/Queue") if Queue_infile is True: DIR = os.path.abspath( os.path.realpath(str(ctx.guild.id) + "/Queue")) length = len(os.listdir(DIR)) try: first_file = os.listdir(DIR)[0] except: # print("No more queued song(s)\n") removed_value = song_list_queue.pop( ctx.guild.id, 'No Key Found') return main_location = os.path.dirname(os.path.realpath(__file__)) main_location += "/" + str(ctx.guild.id) song_path = os.path.abspath( os.path.realpath(str(ctx.guild.id) + "/Queue") + "/" + first_file) if length != 0: # print("Song done, playing next queued\n") # print(f"Songs still in queue: {still_q}") song_there = os.path.isfile( str(ctx.guild.id) + "/song.mp3") if song_there: os.remove(str(ctx.guild.id) + "/song.mp3") shutil.move(song_path, main_location) for file in os.listdir("./" + str(ctx.guild.id)): if file.endswith(".mp3"): os.rename( str(ctx.guild.id) + "/" + file, str(ctx.guild.id) + "/song.mp3") removed_value = song_list_queue.setdefault( ctx.guild.id, []).pop(0) voice.play(discord.FFmpegPCMAudio( str(ctx.guild.id) + "/song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.2 else: removed_value = song_list_queue.pop( ctx.guild.id, 'No Key Found') return else: removed_value = song_list_queue.pop(ctx.guild.id, 'No Key Found') # print("No songs were queued before the ending of the last song\n") song_there = os.path.isfile(str(ctx.guild.id) + "/song.mp3") try: if song_there: os.remove(str(ctx.guild.id) + "/song.mp3") removed_value = song_list_queue.pop(ctx.guild.id, 'No Key Found') # print("Removed old song file") except PermissionError: # print("Trying to delete song file, but it's being played") await ctx.send( "A song is already playing. Type kadle.add [song] to add a song to the queue. " "To delete the queue, type kadle.stop") return Queue_infile = os.path.isdir("./" + str(ctx.guild.id) + "/Queue") try: Queue_folder = "./" + str(ctx.guild.id) + "/Queue" if Queue_infile is True: # print("Removed old Queue Folder") shutil.rmtree(Queue_folder) except: # print("No old Queue folder") pass await ctx.send("Getting things ready. Please wait", delete_after=20) # Check docs of youtube-dl for more info ydl_opts = { 'format': 'bestaudio/best', 'quiet': False, 'outtmpl': "./" + str(ctx.guild.id) + "/song.mp3", 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } if isinstance(url, str): song_search = "".join(url) else: song_search = " ".join(url) query = {"_id": ctx.guild.id, "music_search": {"$exists": True}} results = collection.find_one(query) if not results: search_method = "YOUTUBE" else: search_method = results["music_search"] if search_method == "YOUTUBE": try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") ydl.download([f"ytsearch1:{song_search}"]) info_dict = ydl.extract_info(f"ytsearch1:{song_search}", download=False, ie_key='YoutubeSearch') song_title = None for res in info_dict.get('entries'): if 'title' in res.keys(): song_title = res['title'] break song_list_queue.setdefault(ctx.guild.id, []).append(song_title) except: print("Error in YouTube download") await ctx.send( "Sorry. I encountered an error. Please try again later") return else: try: c_path = os.path.dirname(os.path.realpath(__file__)) c_path += "/" + str(ctx.guild.id) system("spotdl -f " + '"' + c_path + '"' + " -s " + '"' + song_search + '"') for file in os.listdir("./" + str(ctx.guild.id)): if file.endswith(".mp3"): song_title = file[:-4] song_list_queue.setdefault(ctx.guild.id, []).append(song_title) os.rename( str(ctx.guild.id) + "/" + file, str(ctx.guild.id) + "/song.mp3") except: print("Error in Spotify download") await ctx.send( "Sorry. I encountered an error. Please try again later") return voice.play(discord.FFmpegPCMAudio(str(ctx.guild.id) + "/song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.2 if song_title is None: await ctx.send("Could not find the song") else: await ctx.send("Now playing " + song_title)
async def credit(self, ctx): embed = discord.Embed(title="제이봇 크레딧", description="잠시만 기다려주세요...", color=discord.Colour.from_rgb(225, 225, 225)) eun = self.bot.get_user(288302173912170497) gpm = self.bot.get_user(665450122926096395) rainy = self.bot.get_user(558323117802389514) msg = await ctx.send(embed=embed) """ user_voice = ctx.message.author.voice voice = discord.utils.get(self.bot.voice_clients, guild=ctx.guild) if voice is None and bool(user_voice) is True: is_playing = False elif voice is None: is_playing = True else: is_playing = voice.is_playing() if user_voice is None or is_playing: """ embed = discord.Embed(title="제이봇 크레딧", description="개발: Team EG", color=discord.Colour.from_rgb(225, 225, 225)) embed.add_field(name="메인 개발자", value=str(eun)) embed.add_field(name="전 대시보드 개발자", value=str(rainy)) embed.add_field(name="대시보드 개발자", value=str(gpm)) embed.add_field(name="Special thanks to...", value="Team EG members, KSP 한국 포럼 디스코드, and you!") await msg.edit(embed=embed) return channel = user_voice.channel await channel.connect() voice = discord.utils.get(self.bot.voice_clients, guild=ctx.guild) voice.play(discord.FFmpegPCMAudio("http://jebserver.iptime.org/discord/jbot_credit.mp3")) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.3 exist = await self.jbot_db_global.res_sql("SELECT credit FROM easteregg WHERE user_id=?", (ctx.author.id,)) if bool(exist[0]["credit"]): return await self.jbot_db_global.exec_sql("UPDATE easteregg SET credit=? WHERE user_id=?", (1, ctx.author.id)) await asyncio.sleep(1) embed = discord.Embed(title="제이봇 크레딧", description="개발: Team EG", color=discord.Colour.from_rgb(225, 225, 225)) embed.add_field(name="메인 개발자", value=str(eun)) await msg.edit(embed=embed) await asyncio.sleep(5) embed.add_field(name="제작 참여", value=str(gpm) + "\n" + str(rainy)) await msg.edit(embed=embed) await asyncio.sleep(5) embed.add_field(name="사용한 오픈소스", value="Python, discord.py, youtube_dl, aiomysql, beautifulsoup4, ffmpeg") await msg.edit(embed=embed) await asyncio.sleep(5) embed.add_field(name="히든 크레딧의 원본", value="Hacknet Labyrinths DLC 엔딩 (음악: HOME - Dream Head)") await msg.edit(embed=embed) await asyncio.sleep(5) embed.add_field(name="Special thanks to...", value="Team EG members, KSP 한국 포럼 디스코드, and you!") await msg.edit(embed=embed) await msg.add_reaction("⏹") def check(reaction, user): return user == ctx.author and str(reaction.emoji) == "⏹" try: await self.bot.wait_for('reaction_add', timeout=180.0, check=check) voice.stop() except asyncio.TimeoutError: pass await voice.disconnect()
async def play(self, ctx, url: str): try: if os.path.isfile('song.mp3'): os.remove('song.mp3') print('[log] Removed the old song file') except PermissionError: print('[log] Trying to delete song file, but it`s being played') await ctx.send('> ERROR: Music is playing') return await ctx.send('> Starting the preparations for playing an audio...') voice = get(self.client.voice_clients, guild=ctx.guild) ydl_opts = { 'format': 'bestaudio/best', 'quiet': True, 'outtmpl': '%(title)s.%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: print('[log] Downloading the audio...') audio = ydl.extract_info(url=url, download=True) for file in os.listdir('./'): if file.endswith('.mp3'): name = file print(f'[log] Renamed the file name - {file}') os.rename(file, 'song.mp3') voice.play(discord.FFmpegPCMAudio('song.mp3'), after=lambda e: print('[log] The audio is ready')) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = self.volume audio_name = name.rsplit('-', 2)[0] length = get_audio_length('song.mp3') embed = discord.Embed(title=audio.get('title'), url=url, description='Now playing', color=ColorsType.DEFAULT.value) embed.add_field(name='Duration', value=length, inline=True) embed.add_field(name='Author', value=audio.get('uploader'), inline=True) embed.set_image(url=audio.get('thumbnail')) embed.set_footer( text= f'Command used by {ctx.author.name}#{ctx.author.discriminator}', icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) print(f'[log] Starting to play the audio\n[{length}] {audio_name}')
async def play(ctx, client, *url): await ctx.message.delete() MUSIC_LIST.clear() voice = get(client.voice_clients, guild=ctx.guild) url = ' '.join(url) if not voice or not voice.is_connected(): await ctx.author.voice.channel.connect() voice = get(client.voice_clients, guild=ctx.guild) ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'outtmpl': r'./song.webm', } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=False) entries = info['entries'] for entry in entries: t = entry['title'], entry['webpage_url'] MUSIC_LIST.append(t) except KeyError: t = info['title'], info['webpage_url'] MUSIC_LIST.append(t) except: allSearch = Search(url, limit=5) print(str(allSearch.result())) list = re.findall( r'\bhttps://www\.youtube\.com/watch[^\']+\w+', str(allSearch.result())) print(list) list2 = re.findall(r'title\': \'[^\']+\w+.', str(allSearch.result())) list3 = [] count = 0 for e in list2: if count % 2 == 0: print(e) e = e.replace('title\': \'', '') list3.append(e) count += 1 print(list3) msg = f'1. {list3[0]}\n' \ f'2. {list3[1]}\n' \ f'3. {list3[2]}\n' \ f'4. {list3[3]}\n' \ f'5. {list3[4]}' embed = discord.Embed(title='Wyniki wyszukiwania:', description=msg, color=COLOR) message = await ctx.channel.send(embed=embed) await discord.Message.add_reaction(message, emoji=':first:813519059081232384') await discord.Message.add_reaction(message, emoji=':second:813519081697312819') await discord.Message.add_reaction(message, emoji=':third:813519093520924702') await discord.Message.add_reaction(message, emoji=':fourth:813519113354739783') await discord.Message.add_reaction(message, emoji=':fifth:813519124865089627') def _check(r, u): return ( u == ctx.author and r.message.id == message.id ) option, _ = await client.wait_for("reaction_add", timeout=60.0, check=_check) def switch(opt): return { 'first': 0, 'second': 1, 'third': 2, 'fourth': 3, 'fifth': 4, }[opt] await message.delete() print(option.emoji.name) with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([list[switch(option.emoji.name)]]) voice.play(discord.FFmpegPCMAudio('song.mp3')) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 1.0 embed = discord.Embed(title='Odtwarzam:', description=list[switch(option.emoji.name)], color=COLOR) message = await ctx.send(embed=embed) await discord.Message.add_reaction(message, emoji=':ipause:813867984644866099') await discord.Message.add_reaction(message, emoji=':iplay:813867994903216208') await discord.Message.add_reaction(message, emoji=':iskip:813868004664017004') while voice.is_playing() or voice.is_paused(): await asyncio.sleep(1) os.remove('./song.mp3') for tr in MUSIC_LIST: ydl.download([tr[1]]) # TODO: skad to 'ydl'? to z linijki 119 już nie istnieje voice.play(discord.FFmpegPCMAudio('song.mp3')) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 1.0 embed = discord.Embed(title='Odtwarzam:', description=tr[0], color=COLOR) message = await ctx.send(embed=embed) await discord.Message.add_reaction(message, emoji=':ipause:813867984644866099') await discord.Message.add_reaction(message, emoji=':iplay:813867994903216208') await discord.Message.add_reaction(message, emoji=':iskip:813868004664017004') while voice.is_playing() or voice.is_paused(): await asyncio.sleep(1) os.remove('./song.mp3')
async def invitame(self, ctx): voice, channel = await self.habla(ctx, called=True) voice.play(discord.FFmpegPCMAudio('voice/invitame.mp3'), after=None) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 1.
async def play(ctx, url): server = ctx.message.guild voice_channel = server.voice_client Queue.append(url) voice_channel.stop() if (url.find('spotify') != -1): async with ctx.typing(): player = await Factory.get_urlSpotify(url, loop=bot.loop) Rqueue.append(player) await ctx.send("**Added:** " + player + "** to the Queue**") while True: await asyncio.sleep(1) if voice_channel.is_playing() == False and len(Queue) > 1: CurSong.append(Rqueue.pop(0)) Queue.pop(0) if ((Queue[0]).find('youtube') != -1): nsong = await Factory.get_urlYoutube(Queue[0], loop=bot.loop) voice_channel.play(nsong, after=lambda e: CurSong.clear()) else: nsong = await Factory.get_urlSpotify(Queue[0], loop=bot.loop) voice_channel.play( discord.FFmpegPCMAudio( nsong, after=lambda e: CurSong.clear())) voice_channel.source = discord.PCMVolumeTransformer( voice_channel.source) voice_channel.source.volume = 0.5 if voice_channel.is_playing() == False and len(Queue) <= 1: if (url.find("youtube") != -1): CurSong.append(Rqueue.pop(0)) voice_channel.play(player, after=lambda e: CurSong.clear()) else: CurSong.append(Rqueue.pop(0)) voice_channel.play(discord.FFmpegPCMAudio(player), after=lambda e: CurSong.clear()) voice_channel.source = discord.PCMVolumeTransformer( voice_channel.source) voice_channel.source.volume = 0.5 elif (url.find('youtube') != -1): async with ctx.typing(): player = await Factory.get_urlYoutube(url, loop=bot.loop) Rqueue.append(player.title) await ctx.send("**Added:** " + player.title + "** to the Queue**") while True: await asyncio.sleep(1) if voice_channel.is_playing() == False and len(Queue) > 1: CurSong.append(Rqueue.pop(0)) Queue.pop(0) if ((Queue[0]).find('youtube') != -1): nsong = await Factory.get_urlYoutube(Queue[0], loop=bot.loop) voice_channel.play(nsong, after=lambda e: CurSong.clear()) else: nsong = await Factory.get_urlSpotify(Queue[0], loop=bot.loop) voice_channel.play(discord.FFmpegPCMAudio(nsong), after=lambda e: CurSong.clear()) voice_channel.source = discord.PCMVolumeTransformer( voice_channel.source) voice_channel.source.volume = 0.5 if voice_channel.is_playing() == False and len(Queue) <= 1: if (url.find("youtube") != -1): CurSong.append(Rqueue.pop(0)) voice_channel.play(player, after=lambda e: CurSong.clear()) else: CurSong.append(Rqueue.pop(0)) voice_channel.play(discord.FFmpegPCMAudio(player), after=lambda e: CurSong.clear()) voice_channel.source = discord.PCMVolumeTransformer( voice_channel.source) voice_channel.source.volume = 0.5 else: async with ctx.typing(): player = await Factory.get_urlString(url, loop=bot.loop) Rqueue.append(player) await ctx.send("**Added:** " + player + "** to the Queue**") while True: await asyncio.sleep(1) if voice_channel.is_playing() == False and len(Queue) > 1: CurSong.append(Rqueue.pop(0)) Queue.pop(0) if ((Queue[0]).find('youtube') != -1): nsong = await Factory.get_urlYoutube(Queue[0], loop=bot.loop) voice_channel.play(nsong, after=lambda e: CurSong.clear()) else: nsong = await Factory.get_urlSpotify(Queue[0], loop=bot.loop) voice_channel.play( discord.FFmpegPCMAudio( nsong, after=lambda e: CurSong.clear())) CurSong.clear() voice_channel.source = discord.PCMVolumeTransformer( voice_channel.source) voice_channel.source.volume = 0.5 if voice_channel.is_playing() == False and len(Queue) <= 1: if (url.find("youtube") != -1): CurSong.append(Rqueue.pop(0)) voice_channel.play(player, after=lambda e: CurSong.clear()) else: CurSong.append(Rqueue.pop(0)) voice_channel.play( discord.FFmpegPCMAudio( player, after=lambda e: CurSong.clear())) voice_channel.source = discord.PCMVolumeTransformer( voice_channel.source) voice_channel.source.volume = 0.5
async def play(self, ctx, *url: str): ############################################################################################################### voice = get(self.client.voice_clients, guild=ctx.guild) if voice and voice.is_playing(): await ctx.send("There is a song currently playing... !stop the song or !q to add a song to the queue...") else: server_name = str(ctx.guild) server_id = ctx.guild.id channel_id = ctx.message.author.voice.channel.id channel_name = str(ctx.message.author.voice.channel) try: SQL.execute( f'select Song_Name from Music where Server_ID="{server_id}" and Server_Name="{server_name}" and Voice_ID="{channel_id}" and Voice_Name="{channel_name}"') name_song = SQL.fetchone() SQL.execute(f'select Server_Name from Music where Server_ID="{server_id}" and Server_Name="{server_name}"') name_server = SQL.fetchone() except: await ctx.send("The bot must join a voice channel to play a song: Join one and use '!join'") return ############################################################################################################### def check_queue(): ########################################################################################################### DIR = os.path.dirname(__file__) db = sqlite3.connect(os.path.join(DIR, "SongTracker.db")) SQL = db.cursor() SQL.execute(f'select Queue_Name from Music where Server_ID="{server_id}" and Server_Name="{server_name}"') name_queue = SQL.fetchone() SQL.execute(f'select Server_Name from Music where Server_ID="{server_id}" and Server_Name="{server_name}"') name_server = SQL.fetchone() ########################################################################################################### Queue_infile = os.path.isdir("./Queues") if Queue_infile is True: DIR = os.path.abspath(os.path.realpath("Queues")) Queue_Main = os.path.join(DIR, name_queue[0]) length = len(os.listdir(Queue_Main)) still_q = length - 1 try: first_file = os.listdir(Queue_Main)[0] song_num = first_file.split('-')[0] except: print("No more queued song(s)\n") SQL.execute('update Music set Next_Queue = 1 where Server_ID = ? and Server_Name = ?', (server_id, server_name)) db.commit() return ####################################################################################################### main_location = os.path.dirname(os.path.realpath("./baron_bot")) # Change this back to __file__ print(main_location) print(__file__) song_path = os.path.abspath(os.path.realpath(Queue_Main) + "\\" + first_file) if length != 0: print("Song has completed playing, playing next song\n") print(f"Songs still in queue: {still_q}") song_there = os.path.isfile(f"{name_song[0]}({name_server[0]}).mp3") if song_there: os.remove(f"{name_song[0]}({name_server[0]}).mp3") shutil.move(song_path, main_location) for file in os.listdir("./"): if file == f"{song_num}-{name_song[0]}({name_server[0]}).mp3": os.rename(file, f'{name_song[0]}({name_server[0]}).mp3') ############################################################################################################### voice.play(discord.FFmpegPCMAudio(f'{name_song[0]}({name_server[0]}).mp3'), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 else: SQL.execute('update Music set Next_Queue = 1 where Server_ID = ? and Server_Name = ?', (server_id, server_name)) db.commit() return else: SQL.execute('update Music set Next_Queue = 1 where Server_ID = ? and Server_Name = ?', (server_id, server_name)) db.commit() print("No songs were queued before the ending of the last song\n") ############################################################################################################### song_there = os.path.isfile(f"{name_song[0]}({name_server[0]}).mp3") try: if song_there: os.remove(f"{name_song[0]}({name_server[0]}).mp3") SQL.execute('update Music set Next_Queue = 1 where Server_ID = ? and Server_Name = ?', (server_id, server_name)) db.commit() print("Removed old song file") except PermissionError: print("Trying to delete song file, but it's being played") await ctx.send("ERROR: Music playing") return ############################################################################################################### SQL.execute(f'select Queue_Name from Music where Server_ID="{server_id}" and Server_Name="{server_name}"') name_queue = SQL.fetchone() queue_infile = os.path.isdir("./Queues") if queue_infile is True: DIR = os.path.abspath(os.path.realpath("Queues")) Queue_Main = os.path.join(DIR, name_queue[0]) Queue_Main_infile = os.path.isdir(Queue_Main) if Queue_Main_infile is True: print("Removed old queue folder") shutil.rmtree(Queue_Main) ############################################################################################################### await ctx.send("Preparing the song... Please wait...") ############################################################################################################### voice = get(self.client.voice_clients, guild=ctx.guild) song_path = f"./{name_song[0]}({name_server[0]}).mp3" ydl_opts = { 'match_filter': youtube_dl.utils.match_filter_func("!is_live"), 'format': 'bestaudio/best', 'restrictfilenames': True, 'noplaylist': True, 'nocheckcertificate': True, 'ignoreerrors': False, 'logtostderr': False, 'quiet': False, 'no_warnings': True, 'outtmpl': song_path, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } song_search = ' '.join(url) try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") info = ydl.extract_info(f"ytsearch1:{song_search}", download=False) info_dict = info.get('entries', None)[0] print(info_dict) video_title = info_dict.get('title', None) ydl.download([f"ytsearch1:{song_search}"]) except: print("FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if spotify URL)") c_path = os.path.dirname(os.path.realpath(__file__)) system(f"spotdl -ff {name_song[0]}({name_server[0]}) -f " + '"' + c_path + '"' + " -s " + song_search) voice.play(discord.FFmpegPCMAudio(f"{name_song[0]}({name_server[0]}).mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 await ctx.send(f"Now playing... {video_title}") print("Playing Song\n")
async def playonline(self, ctx, url: str): # bugs with youtube-dl playing, currently offlining play command await ctx.send( "Youtube music streaming is currently offline, sorry for any inconvenience." ) return # check if bot is idle channel = ctx.message.author.voice.channel # join where join command sender is voice = get(self.bot.voice_clients, guild=ctx.guild) if voice and voice.is_connected(): # check if bot is being used in another channel if channel and channel != ctx.voice_client.channel: await ctx.send('I\'m currently being used in another channel') return else: voice = await channel.connect() await ctx.send(f'Joined {channel}') song_there = os.path.isfile("song.mp3") try: if song_there: os.remove("song.mp3") print("Removed current dir's song.mp3") except PermissionError: print("Can't delete song.mp3 since it's being played") await ctx.send("Music is being played") return # using youtube-dl module await ctx.send( "Loading...(sorry for the waiting but I\'m just a Raspberry Pi)") voice = get(self.bot.voice_clients, guild=ctx.guild) # quality set to 320, could result in errors. Default is 192 # toggle 'quiet' to get cleanner console ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Extracting audio and downloading now") ydl.download([url]) for file in os.listdir('./'): if file.endswith('.mp3'): name = file print(f'Renamed file: {file}') os.rename(file, 'song.mp3') voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: print(f'{name} has finished playing')) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 newName = name.rsplit('-', 2) await ctx.send(f'Playing: {newName[0]}') print("Playing...")
def check_queue(): ########################################################################################################### DIR = os.path.dirname(__file__) db = sqlite3.connect(os.path.join(DIR, "SongTracker.db")) SQL = db.cursor() SQL.execute(f'select Queue_Name from Music where Server_ID="{server_id}" and Server_Name="{server_name}"') name_queue = SQL.fetchone() SQL.execute(f'select Server_Name from Music where Server_ID="{server_id}" and Server_Name="{server_name}"') name_server = SQL.fetchone() ########################################################################################################### Queue_infile = os.path.isdir("./Queues") if Queue_infile is True: DIR = os.path.abspath(os.path.realpath("Queues")) Queue_Main = os.path.join(DIR, name_queue[0]) length = len(os.listdir(Queue_Main)) still_q = length - 1 try: first_file = os.listdir(Queue_Main)[0] song_num = first_file.split('-')[0] except: print("No more queued song(s)\n") SQL.execute('update Music set Next_Queue = 1 where Server_ID = ? and Server_Name = ?', (server_id, server_name)) db.commit() return ####################################################################################################### main_location = os.path.dirname(os.path.realpath("./baron_bot")) # Change this back to __file__ print(main_location) print(__file__) song_path = os.path.abspath(os.path.realpath(Queue_Main) + "\\" + first_file) if length != 0: print("Song has completed playing, playing next song\n") print(f"Songs still in queue: {still_q}") song_there = os.path.isfile(f"{name_song[0]}({name_server[0]}).mp3") if song_there: os.remove(f"{name_song[0]}({name_server[0]}).mp3") shutil.move(song_path, main_location) for file in os.listdir("./"): if file == f"{song_num}-{name_song[0]}({name_server[0]}).mp3": os.rename(file, f'{name_song[0]}({name_server[0]}).mp3') ############################################################################################################### voice.play(discord.FFmpegPCMAudio(f'{name_song[0]}({name_server[0]}).mp3'), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 else: SQL.execute('update Music set Next_Queue = 1 where Server_ID = ? and Server_Name = ?', (server_id, server_name)) db.commit() return else: SQL.execute('update Music set Next_Queue = 1 where Server_ID = ? and Server_Name = ?', (server_id, server_name)) db.commit() print("No songs were queued before the ending of the last song\n")
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 done, playing next queued\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("Trying to delete song file, but it's being played") await ctx.send("ERROR: Music playing") 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 old Queue folder") await ctx.send("Getting everything ready now") voice = get(self.client.voice_clients, guild=ctx.guild) ydl_opts = { 'format': 'bestaudio/best', 'quiet': True, '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") 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"Playing: {nname[0]}") print("playing\n")
async def play(ctx, url=None): station = voice_id(ctx) if url == None: await ctx.send(f"⚠ Link to dey ⚠") return url = str(url) voice = get(client.voice_clients, guild=ctx.guild) if not (voice and voice.is_connected()): await join(ctx) song = os.path.isfile("song.mp3") try: if song: os.remove("song.mp3") print("Removed old song file") except PermissionError: print("Song is being played") if voice.is_playing() or voice.is_paused(): await stop(ctx) os.remove("song.mp3") print("Removed old song file") await ctx.send(f"getting everything ready ⏳⏳") ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio ...\n") ydl.download([url]) for file in os.listdir("./"): if file.endswith(".mp3"): if os.name != "song.mp3": name = file os.rename(file, "song.mp3") else: os.remove("song.mp3") voice = get(client.voice_clients, guild=ctx.guild) voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: print(f"{name} has finished playing")) voice.source = discord.PCMVolumeTransformer(voice.source) global volume voice.source.volume = volume nname = name.rsplit("-", 2)[0] ##############testing p = "▶" m = "🎵" await ctx.send(f" {p} **playing**: {nname} {m}{m}{m}")
async def on_voice_state_update(member, before, after): buddy = str(member) ### ANY CHANNEL Intro Tunes ### if not member.bot: # disregards any bots if before.self_deaf == after.self_deaf: # stops if member toggled deafen if before.self_mute == after.self_mute: # stops if member toggled mute if not after.channel == None: vchanid = after.channel.id v_ids = [ 568612353613234190 ] # Add voicechannel IDs to this list to enable them for the intro if vchanid in v_ids: intpath = os.path.join(path, 'introdata/') intuser = os.path.join(intpath, buddy) inttime = intuser + '_time.txt' intvol = intuser + '_volume.txt' intmp3 = intuser + '.mp3' defaultmp3 = intpath + '/defaultintro.mp3' itime = time.time() if os.path.exists(inttime): with open(inttime, "r") as bf: tdata = bf.read() if tdata == '': tdata = 0 # buddyintrotime has no information so tdata resorts to 0 else: print('create new inttime') with open(inttime, "w") as bf: bf.write(str(itime)) tdata = 0 # buddyintrotime didnt exist so tdata resorts to 0 if os.path.exists(intvol): with open(intvol, "r") as rv: voldata = rv.read() voldata = float(voldata) if voldata == '': voldata = 0.25 # default intro volume else: voldata = 0.25 if os.path.exists(intmp3): mp3file = intmp3 else: mp3file = defaultmp3 tdelta = 3600 # time threshold in seconds since users last intro readtime = itime - float(tdata) if tdelta <= readtime: # if time delta crosses threshold, then play intro vc = await after.channel.connect() mp3source = discord.FFmpegPCMAudio(mp3file) mp3sourcetrans = discord.PCMVolumeTransformer( mp3source) mp3sourcetrans.volume = voldata vc.play(mp3sourcetrans) while vc.is_playing(): await asyncio.sleep(1) vc.stop() await vc.disconnect() with open(inttime, "w") as bf: bf.write(str(itime)) print('yes intro:', buddy) else: print(' no intro:', buddy)
async def play(self, ctx, *, search: str): '''Plays a song from YouTube''' if ctx.message.guild.voice_client is None: self.voice_client = await ctx.message.author.voice.channel.connect( ) if search.startswith('https://'): outtmpl = 'music/%(title)s.mp3' extractor = search else: outtmpl = 'music/' + search + '.mp3' extractor = 'ytsearch1:' + search ydl_opts = { 'format': 'bestaudio', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'outtmpl': outtmpl, 'logger': MyLogger(), } with youtube_dl.YoutubeDL(ydl_opts) as ydl: info_dict = ydl.extract_info(extractor, download=False) folder = os.path.join('music') if search.startswith('https://'): video_title = info_dict.get('title', None) + '.mp3' file_to_open = os.path.join(folder, video_title) else: video_title = info_dict['entries'][0].get('title', None) + '.mp3' file_to_open = os.path.join(folder, search + '.mp3') # file_name = self.fileCleanUp(video_title) ffmpeg_exe = os.path.join('ffmpeg', 'bin', 'ffmpeg.exe') print(search, extractor, video_title) videoDict = {'title': video_title} if not self.voice_client.is_playing(): try: ydl.download([extractor]) source = discord.FFmpegPCMAudio(file_to_open, executable=ffmpeg_exe) transformer = discord.PCMVolumeTransformer( source, self.vol) self.voice_client.play(transformer, after=lambda x: self.playNext()) except discord.ClientException: print('error') else: source = discord.FFmpegPCMAudio(file_to_open, executable=ffmpeg_exe) transformer = discord.PCMVolumeTransformer(source, self.vol) self.song_queue.put(transformer)
async def play(self, ctx): # 명령이 들어왔을 때 예외 처리 부분 user = ctx.author.voice # 사용자의 음성 voice = get(self.bot.voice_clients, guild=ctx.guild) # 봇의 음성 if not user: # 사용자가 음성 채널에 연결되어 있지 않으면 await ctx.send("사용자가 음성 채널에 연결되어 있지 않습니다.") return elif not voice: # 오픈이가 음성 채널에 연결되어 있지 않으면 await ctx.send("오픈이가 음성 채널에 연결되어 있지 않습니다.") return #=================================================== Queue_infile = os.path.isdir( "./Queue") # Queue 폴더가 있으면 True, 아니면 False song_there = os.path.isfile( "./song.mp3") # 현재 위치에 song.mp3 노래가 있으면 True, 아니면 False try: if song_there: # 현재 위치에 song.mp3 노래가 있으면 os.remove("./song.mp3") # song.mp3를 지우고 except PermissionError: # 만약 노래가 재생 중이면 print("이미 재생 중인 노래여서 삭제할 수 없습니다.") await ctx.send("ERROR : 노래가 재생 중입니다.") return try: Queue_folder = "./Queue" # Queue 폴더의 경로 if Queue_infile is False or self.queues.empty(): # Queue 폴더가 없으면 await self.bot.change_presence(status=discord.Status.online, activity=discord.Game("아무것도 안")) await ctx.send("플레이리스트가 비어있습니다. !추가 명령어를 통해 노래를 추가해주세요.") return except: # 예외가 발생되면 print("오래된 재생 폴더가 없습니다.") os.mkdir("./Queue") # Queue 폴더를 만듦 #========함수의 시작 | 재생 관련========= first_file = self.queues.get_nowait() main_location = os.getcwd() + "\\" + first_file song_path = os.path.abspath( os.path.realpath("Queue") + "\\" + first_file) #Queue 폴더에 있는 다음 노래 위치 for file in os.listdir("./Queue"): if file == first_file: song_there = os.path.isfile("song.mp3") if song_there: # 현재 위치에 song.mp3 노래가 있으면 os.remove("song.mp3") # song.mp3를 제거 shutil.move(song_path, main_location) # 다음 노래를 현재 위치로 옮김 name = first_file.rsplit("-", 1) os.rename(first_file, "song.mp3") break voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: self.check_queue(ctx)) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 await self.bot.change_presence(status=discord.Status.online, activity=discord.Game("노래를 재생")) await ctx.send(f"Playing : {name[0]}") print("재생 중\n")
async def play(self, ctx, args): source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("data/sounds/{}.mp3".format(args))) ctx.voice_client.play(source)
async def play(ctx, url: str): channel = ctx.message.author.voice.channel voice = get(client.voice_clients, guild=ctx.guild) song_chk = os.path.isfile("/bin/music/Now/song.mp3") if song_chk: os.remove("/bin/music/Now/song.mp3") song_chk2 = os.path.isfile("song.mp3") if song_chk2: os.remove("song.mp3") if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() def check_queue(): Queue_infile = os.path.isdir("./bin/music/Queue") if Queue_infile is True: DIR = os.path.abspath(os.path.realpath("bin/music/Queue")) length = len(os.listdir(DIR)) still_q = length - 1 try: first_file = os.listdir(DIR)[0] except: print(f"{Fore.RED}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("bin/music/Queue") + "/" + first_file) if length != 0: print(f"{Fore.RED}Song done, Playing Next Queued\n") print(f"{Fore.GREEN}Songs still in queue: {still_q}") song_there = os.path.isfile("./bin/music/Now/song.mp3") if song_there: os.remove("./bin/music/Now/song.mp3") shutil.move(song_path, main_location) for file in os.listdir("./"): if file.endswith(".mp3"): os.rename(file, 'song.mp3') shutil.move('song.mp3', 'bin/music/Now') voice.play(discord.FFmpegPCMAudio("./bin/music/Now/song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 nname = name[:-16] qnum = str(q_num) else: queues.clear() return else: queues.clear() print(f"{Fore.RED}No songs were queued before the ending of the last song\n") song_there = os.path.isfile("./bin/music/Now/song.mp3") queue_there = os.path.isdir("./bin/music/Queue") if song_there and queue_there is True: try: if song_there: Queue_infile = os.path.isdir("./bin/music/Queue") if Queue_infile is False: os.mkdir("bin/music/Queue") DIR = os.path.abspath(os.path.realpath("bin/music/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 embed1 = discord.Embed( color=0xf0ff39, title="Download Song Now!", description=f"Pleas Wait A Some Second!" ) embed1.set_author(name="MayBe", icon_url="https://i.imgur.com/rlx3WnT.png") embed1.set_thumbnail(url="https://i.imgur.com/5P4cCLB.png") embed1.set_footer(text="Via MaybeBot") embed1.add_field(name="Queue: ", value=str(q_num)) await ctx.send(embed=embed1) queue_path = os.path.abspath(f"song{q_num}") ydl_opt = { 'format': 'bestaudio/best', 'quit': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opt) as ydl: print(f"{Fore.LIGHTBLUE_EX} Downloading Song File now\n") ydl.download([url]) for file in os.listdir("./"): if file.endswith(".mp3"): name = file print(f"{Fore.GREEN} Renamed File: {file}") os.rename(file, queue_path + ".mp3") shutil.move(queue_path + ".mp3", 'bin/music/Queue') nname = name[:-16] embed = discord.Embed( color=0xf0ff39, title="Adding Song In The Queue:", description=nname ) embed.set_author(name="MayBe", icon_url="https://i.imgur.com/rlx3WnT.png") embed.set_thumbnail(url="https://i.imgur.com/5P4cCLB.png") embed.set_footer(text="Via MaybeBot") embed.add_field(name="Queue: ", value=str(q_num), inline=False) await ctx.send(embed=embed) print(f"{Fore.YELLOW}Song added to queue \n") except PermissionError: print(f"{Fore.RED}I Cant Remove song file now") embed = discord.Embed( color=discord.Color.red(), title="Error", description=f"Music Start Error" ) embed.set_author(name="MayBe", icon_url="https://i.imgur.com/rlx3WnT.png") embed.set_thumbnail(url="https://i.imgur.com/5P4cCLB.png") embed.set_footer(text="Via MaybeBot") await ctx.send(embed=embed) return if song_there is False: embed = discord.Embed( color=0xf0ff39, title="Download Song Now!", description=f"Pleas Wait A Some Second!" ) embed.set_author(name="MayBe", icon_url="https://i.imgur.com/rlx3WnT.png") embed.set_thumbnail(url="https://i.imgur.com/5P4cCLB.png") embed.set_footer(text="Via MaybeBot") await ctx.send(embed=embed) voice = get(client.voice_clients, guild=ctx.guild) ydl_opt = { 'format': 'bestaudio/best', 'quit': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opt) as ydl: print(f"{Fore.LIGHTBLUE_EX} Downloading Song File now\n") ydl.download([url]) for file in os.listdir("./"): if file.endswith(".mp3"): name = file print(f"{Fore.GREEN} Renamed File: {file}") song_there = os.path.isfile("./bin/music/Now/song.mp3") if song_there: os.remove("./bin/music/Now/song.mp3") os.rename(file, "song.mp3") shutil.move("song.mp3", "./bin/music/Now") voice.play(discord.FFmpegPCMAudio("./bin/music/Now/song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 try: nname = name[:-16] embed = discord.Embed( color=0xf0ff39, title="Playing Now", description=f"{nname}" ) embed.set_author(name="MayBe", icon_url="https://i.imgur.com/rlx3WnT.png") embed.set_thumbnail(url="https://i.imgur.com/5P4cCLB.png") embed.set_footer(text="Via MaybeBot") await ctx.send(embed=embed) except: embed = discord.Embed( color=0xf0ff39, title="Playing Now", description=f"Playing Now But idk, What is this Song Name?" ) embed.set_author(name="MayBe", icon_url="https://i.imgur.com/rlx3WnT.png") embed.set_thumbnail(url="https://i.imgur.com/5P4cCLB.png") embed.set_footer(text="Via MaybeBot") await ctx.send(embed=embed) print(f"{Fore.GREEN} Playing {nname}\n")
async def play(ctx, url: str): def check_queue(): global Queue_infile 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("Больше нет песен в очереди") 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("Музыка готова, сыграю в следующей очереди") print(f"Музыка еще в очереди: {still_q}") global song_there song_there = os.path.isfile("song.mp3") if song_there: os.remove("mp.3") global file shutil.move(song_path, main_location) for file in os.lostdir("./"): if file.endswith('mp.3'): 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("Больше нет музыки в очереди") global voice global name song_there = os.path.isfile("song.mp3") try: if song_there: os.remove("song.mp3") queues.clear() print("Удаление старого музыкального файла") except PermissionError: print("Пробую удалять музыкальный файл, но она играет") await ctx.send("Ошибка: Музыка играет!") return Queue_infile = os.path.isdir("./Queue") try: Queue_folder = "./Queue" if Queue_infile is True: print("Удаляю старую очередь") shutil.rmtree(Queue_folder) except: print("Нет очереди") await ctx.send("Получение чего-либо готового") voice = get(Bot.voice_clients, guild=ctx.guild) ydl_opts = { 'format': 'bestaudio/best', 'quiet': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }] } with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Загрузка музыки\n") ydl.download([url]) for file in os.listdir("./"): if file.endswith(".mp3"): name = file print(f"Переименовываю файл: {file}\n") 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 nname = name.rsplit("-", 2) await ctx.send(f"Играет: {nname}") print("playing\n")