async def on_voice_state_update(member, before, after): print(before) print(after) print(member) if member.bot: return if after.channel is not None and 'General' in after.channel.name: print("Hi ", member.name) elif after.channel is None: print("Bye ", member.name) if before.self_stream is not after.self_stream: # or before.self_deaf is not after.self_deaf return if before.self_mute is not after.self_mute and before.self_deaf is after.self_deaf: return if ( before.self_deaf is False and after.self_deaf is True and before.channel.name == after.channel.name) or after.channel is None: file = open("goodbyes.json", "r") data = json.load(file) for user in data["data"]["users"]: if user["id"] == member.id or user["name"] == member.name: if before.channel is not None: voice_channel = before.channel try: open(os.getcwd() + user["url"]) except FileNotFoundError: print("audio not found for ", member.name) return vc = await voice_channel.connect() vc.play( discord.FFmpegPCMAudio(executable="ffmpeg", source=os.getcwd() + user["url"])) while vc.is_playing(): time.sleep(.1) await vc.disconnect() file.close() elif ( before.self_deaf is True and after.self_deaf is False and before.channel.name == after.channel.name) or 'General' in after.channel.name: file = open("greetings.json", "r") data = json.load(file) for user in data["data"]["users"]: if user["id"] == member.id or user["name"] == member.name: if after.channel is not None: voice_channel = after.channel try: open(os.getcwd() + user["url"]) except FileNotFoundError: print("audio not found for ", member.name) return vc = await voice_channel.connect() vc.play( discord.FFmpegPCMAudio(executable="ffmpeg", source=os.getcwd() + user["url"])) while vc.is_playing(): time.sleep(.1) await vc.disconnect() file.close()
async def on_message(message): if message.author.bot: return #タッチよくない if message.content == tc.touch[0]: await message.channel.send(trs.touch_bad[random.randint( 0, len(trs.touch_bad) - 1)]) #たっち if message.content == tc.touch[1]: await message.channel.send(trs.touch_good[random.randint( 0, len(trs.touch_good) - 1)]) #朝の挨拶 if message.content in tc.morning: await message.channel.send(trs.greetings[random.randint( 0, len(trs.greetings) - 1)]) #挨拶 if message.content in tc.greet: await message.channel.send(trs.greetings[random.randint( 0, len(trs.greetings) - 1)]) #おやすみ if message.content in tc.good_night: await message.channel.send(Images.Oyasuminasai) #なーちゃん if message.content in tc.to_amana: await message.channel.send(trs.against_amana[random.randint( 0, len(trs.against_amana) - 1)]) #ひぃん if message.content in tc.hiin: print(vl.hiin) channel = client.get_channel(voice_ID) if message.guild.voice_client is None: vc = await channel.connect() else: vc = message.guild.voice_client vc.play(discord.FFmpegPCMAudio(vl.hiin)) vc.source = discord.PCMVolumeTransformer(vc.source) vc.source.volume = 1.0 while not vc.is_playing(): await asyncio.sleep(1) #あう… if message.content in tc.auu: channel = client.get_channel(voice_ID) if message.guild.voice_client is None: vc = await channel.connect() else: vc = message.guild.voice_client vc.play(discord.FFmpegPCMAudio(vl.au)) vc.source = discord.PCMVolumeTransformer(vc.source) vc.source.volume = 0.7 while not vc.is_playing(): await asyncio.sleep(1) #にへへ if message.content in tc.nihehe: channel = client.get_channel(voice_ID) if message.guild.voice_client is None: vc = await channel.connect() else: vc = message.guild.voice_client vc.play(discord.FFmpegPCMAudio(vl.nihehe)) vc.source = discord.PCMVolumeTransformer(vc.source) vc.source.volume = 1.0 while not vc.is_playing(): await asyncio.sleep(1) #がんばります!! if message.content in tc.ganbaru: channel = client.get_channel(voice_ID) if message.guild.voice_client is None: vc = await channel.connect() else: vc = message.guild.voice_client vc.play(discord.FFmpegPCMAudio(vl.ganbarimasu)) vc.source = discord.PCMVolumeTransformer(vc.source) vc.source.volume = 1.0 while not vc.is_playing(): await asyncio.sleep(1) #ばいばい if message.content in tc.bye: for voice_client in client.voice_clients: await voice_client.disconnect()
async def startq(ctx): channel = discord.utils.get(ctx.guild.channels, name='queue') vc = await channel.connect() vc.play(discord.FFmpegPCMAudio("countdown.mp3"), after=lambda e: print('done', e)) bot.run(token)
async def on_voice_state_update(member, before, after): if member.guild.voice_client: if '{0.user}'.format(client) != str( member) and after.channel is not None: member.guild.voice_client.play( discord.FFmpegPCMAudio(source="pigeonpy.mp3"))
def __init__(self, song_info, volume=1.0): self.info = song_info.info self.requester = song_info.requester self.channel = song_info.channel self.filename = song_info.filename super().__init__(discord.FFmpegPCMAudio(self.filename, options='-vn'), volume=volume)
async def playFile(self, fileName): while self.vc.is_playing(): await asyncio.sleep(3) self.vc.play(discord.FFmpegPCMAudio(fileName, **self.ffmpeg_local_opts))
async def initialize(self, ctx, *args): global VC # Sanity check the user sending the message. voice = ctx.author.voice if voice is None: # todo: check if user is in the same voice channel. return await ctx.send(f"{ctx.author.mention} is not in a channel.") voice_channel = voice.channel # Set up the embed message. embed = discord.Embed(title=surround_message( "Processing request", ":arrows_counterclockwise:")) embed.add_field(name="Request", value=" ".join(args)) embed.add_field(name="From", value=ctx.author.name) message = await ctx.send(embed=embed) embed.clear_fields() # Wait if there's nothing playing and I'm not the first one. while VC is not None and not VC.is_playing() and DEQUE[0] != self: await asyncio.sleep(BOT_LATENCY) # Process the arguments. url = args[0] if urlparse( args[0]).scheme else "ytsearch1:" + " ".join(args) # Preprocess the url. with youtube_dl.YoutubeDL(Music.ytdl_opts) as ytdl: info = ytdl.extract_info(url, download=False) if "entries" in info: info = info["entries"][0] embed.title = surround_message("In queue", ":arrows_counterclockwise:") embed.add_field(name="Title", value=info["title"], inline=True) embed.add_field(name="Uploader", value=info["uploader"], inline=True) embed.set_image(url=info["thumbnail"]) embed.set_footer(text="Retrieved from: " + info["webpage_url"]) await message.edit(embed=embed) if info["filesize"] > MAX_FILE_SIZE: embed.title = surround_message("Sorry; item too large.", ":no_entry_sign:") return await message.edit(embed=embed) # Wait until it's my turn. while DEQUE[0] != self: await asyncio.sleep(BOT_LATENCY) # Download the item. with youtube_dl.YoutubeDL(Music.ytdl_opts) as ytdl: embed.title = surround_message("Downloading item", ":arrow_double_down:") await message.edit(embed=embed) ytdl.download([info["webpage_url"]]) # Join the voice channel and play the item. embed.title = surround_message("Now playing", ":musical_note:") await message.edit(embed=embed) if VC is None: VC = await voice_channel.connect() VC.play( discord.FFmpegPCMAudio("download.m4a", options="-maxrate 96k -bufsize 192k")) # Sleep while audio is playing. while VC.is_playing(): await asyncio.sleep(BOT_LATENCY) # Clean up. embed.title = surround_message("Finished playing", ":white_check_mark:") await message.edit(embed=embed) DEQUE.popleft() if not DEQUE: await VC.disconnect() VC = None
def add_stream(self, file): if self.vc is not None: self.audio.add_stream(discord.FFmpegPCMAudio(file))
async def on_message(self, message): if message.author == client.user: return print("Message:" + str(message.content)) print("Channel: " + str(message.channel.id)) if message.content == "SeniorBot Go": await add_senior_role() if message.content.startswith(self.prefix + "play"): where = message.content.split(" ")[1] channel = discord.utils.get(message.guild.channels, name=where) voicechannel = await channel.connect() voicechannel.play(discord.FFmpegPCMAudio("your_music_file.mp3")) while voicechannel.is_playing(): time.sleep(5) if voicechannel.is_paused(): pass voicechannel.stop() voicechannel.pause() voicechannel.resume() if message.content.startswith(self.prefix + "wichteln"): await message.delete() msg = "Bist du wirklich beim Wichteln dabei? falls ja, sende !confirm" await message.author.send(msg) if message.content.lower() == self.prefix + "confirm" and str( message.channel.type) == "private": await message.author.send( "Teilnahme bestätigt! viel Spaß beim Wichteln! :) ") name = str((message.author)).split(" ") add_user(name[0] + " " + name[1]) #JEDER USER KANN DAS STARTEN! -> gotta do that differently. ''' if message.content.lower() == self.prefix +"finish_wichteln": receivers = users[:] senders = users[:] while is self_sender(receivers,senders): print("recalculating") random.shuffle(receivers) random.shuffle(senders) for i,u in enumerate(senders): user = discord.utils.get(message.guild.members, name=u,) ''' if message.content.startswith(self.prefix + "hello bot"): await message.channel.send("Hello There ( ͡° ͜ʖ ͡°) ") await message.channel.send("What do you want from me? ") await message.channel.send("What do you want from me? ", tts=True, delete_after=3.1) if message.content.startswith(self.prefix + "help"): await message.channel.send( '''Hello there! I see you need somehelp here: lemme school you in boy. Send !roulette <bet> to the chat to play roulette. you can bet the following way: "vdz" = voisins_du_zero = [0, 2, 3, 4, 7, 12, 15, 18, 19, 21, 22, 25, 26, 28, 29, 32, 35] "jeu" = jeu= [0, 3, 12, 15, 26, 32, 35] "orp" = orphelins = [1, 6, 9, 14, 17, 20, 31, 34] tdc = tiers_du_cylindre=[5, 8, 10, 11, 13, 16, 23, 24, 27, 30, 33, 36] black = black = [ 2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35] red = red = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36] ''') if message.content.startswith(self.prefix + "stats"): messages = await message.channel.history(limit=50).flatten() for i in messages: print(i.content) counter = 0 async for m in message.channel.history(): if m.author == client.user and m.content.startswith( "nope. that was wrong m8"): counter += 1 print(counter) if message.content.startswith(self.prefix + "onlinemembers"): members = client.guilds[0].members for i in members: if i.status == discord.Status.offline: members.remove(i) for i in members: print(str(i)) #Roulette: if message.content.lower().startswith(self.prefix + "roulette "): bid = message.content.split(" ")[1] jeu_c = False vdz_c = False zero_c = False orp_c = False tdc_c = False black_c = False red_c = False lower_c = False higher_c = False number = None even_c = False uneven_c = False if bid == "jeu": jeu_c = True elif bid == "vdz": vdz_c = True elif bid == "0": zero_c = True elif bid == "orp": orp_c = True elif bid == "tdc": tdc_c = True elif bid == "black": black_c = True elif bid == "red": red_c = True elif bid == "lower": lower_c = True elif bid == "higher": higher_c = True elif bid == "uneven": uneven_c = True elif bid == "even": even_c = True else: try: number = int(bid) except: message.channel.send( "Invalid command. to view how to play this game u cuk, type \"!help\"" ) voisins_du_zero = [ 0, 2, 3, 4, 7, 12, 15, 18, 19, 21, 22, 25, 26, 28, 29, 32, 35 ] jeu = [0, 3, 12, 15, 26, 32, 35] orphelins = [1, 6, 9, 14, 17, 20, 31, 34] tiers_du_cylindre = [5, 8, 10, 11, 13, 16, 23, 24, 27, 30, 33, 36] black = [ 2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35 ] red = [ 1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36 ] zero_w = False result = random.randint(0, 36) message_ = "Congrats {a}, you won! the winning number was {b}! \n You won with: ".format( a=message.author, b=result) if result == 0: if self.win_check([jeu_c, vdz_c, zero_c]): await message.channel.send(message_ + "Zero!") return if self.binary_search(jeu, result): if self.win_check([jeu_c]): await message.channel.send(message_ + "Jeu!") return if self.binary_search(voisins_du_zero, result): if self.win_check([vdz_c], ): await message.channel.send(message_ + "Voisins_du_zero!") return if self.binary_search(orphelins, result): if self.win_check([orp_c]): await message.channel.send(message_ + "Orphelins!") return if self.binary_search(tiers_du_cylindre, result): if self.win_check([tdc_c]): await message.channel.send(message_ + "Tiers du Cylindre!") return if self.binary_search(black, result): if self.win_check([black_c]): await message.channel.send(message_ + "black numbers!") return if self.binary_search(red, result): if self.win_check([red_c]): await message.channel.send(message_ + "red numbers!") return if result < 19: if self.win_check([lower_c]): await message.channel.send(message_ + "lower numbers!") return if result > 17: if self.win_check([higher_c]): await message.channel.send(message_ + "higher numbers!") return if result % 2: if self.win_check([even_c]): await message.channel.send(message_ + "even numbers!") return if result % 2 == 1: if self.win_check([uneven_c]): await message.channel.send(message_ + "uneven numbers!") return if result == number: self.win_check([True]) await message.channel.send(message_ + "Hitting the right number!") return else: await message.channel.send( "nope. that was wrong m8.\n- Result: {}\n- Your Choice: {}" .format(result, bid)) return
async def start(self): self.entry = await self.get_info(self.entry.url) self.source = discord.FFmpegPCMAudio(self.entry.download_url, before_options='-reconnect 1')
async def play(ctx, url: str): channel = ctx.author.voice.channel await channel.connect() await ctx.message.delete() 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 songs(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 = 1.00 else: queues.clear() return 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', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") ydl.download([url]) 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 -f " + '""' + c_path + '""' + " -s " + 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 = 1.00 nname = name.rsplit("-", 2) await ctx.send(f"Playing: {nname[0]}") print("playing\n")
async def invoke(self, message, ctx, args): await super().invoke(message, ctx, args) try: channel = ctx.author.voice.channel print("User is in channel : " + str(channel)) except AttributeError: print("Error : user in not is a voice channel.") await ctx.send( "You must be in a voice channel to use this commmand!") return await channel.connect() query = "+".join(args) html = urllib.request.urlopen( "https://www.youtube.com/results?search_query=" + query) video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode()) for video_id in video_ids: print("https://www.youtube.com/watch?v=" + str(video_id)) top_url = "https://www.youtube.com/watch?v=" + str(video_ids[0]) print("Playing : " + top_url) await ctx.send("Now playing " + top_url) #new stuff vc = ctx.voice_client ydl_opts = { 'max-filesize': "20M", 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } #add remove song stuff song_exists = os.path.isfile("song.mp3") if song_exists: try: os.remove("song.mp3") except PermissionError: await ctx.send( "Wait for current song to finish (this will be fixed later)" ) return with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([top_url]) for file in os.listdir("./"): if file.endswith(".mp3"): os.rename(file, "song.mp3") vc.play(discord.FFmpegPCMAudio("song.mp3")) vc.source = discord.PCMVolumeTransformer(vc.source, volume=2.0) vc.is_playing()
async def on_message(message): # runs on a new message being sent in the server global votes global voters global u_votes global u_voters global echoes_mode message_content = message.content # store message content in a variable author = message.author # grab the author name from the message if author == bot.user: # make sure the message was not sent by the bot return if vote: # check if votemute is active if (message_content == 'yes') and not(author in voters): # check if someone typed 'yes' votes['yes'] = votes['yes'] + 1 # add 1 to votes counter voters.append(author) # add author to voters list print(f'{author} voted yes') elif (message_content == 'no') and not(author in voters): # check if someone typed 'no' votes['no'] = votes['no'] + 1 # add 1 to the no counter voters.append(author) # add author to voters list print(f'{author} voted no') elif u_vote: # check if voteunmute is active if (message_content == 'yes') and not(author in u_voters): u_votes['yes'] = u_votes['yes'] + 1 u_voters.append(author) print(f'{author} voted yes') elif (message_content == 'no') and not(author in u_voters): u_votes['no'] = u_votes['no'] + 1 u_voters.append(author) print(f'{author} voted no') else: pass # TO-DO: To be decided if is_admin(author): if message_content == "!toggle echoes": echoes_mode = not echoes_mode if echoes_mode: await message.channel.send(f":moyai: Echoes Mode: ON :moyai:") else: await message.channel.send(f":moyai: Echoes Mode: OFF :moyai:") if (echoes_mode): if message.author.bot: return await message.add_reaction("🗿") await message.channel.send(f":moyai: {next(echoes_lyrics)} :moyai:") voice_channel = message.guild.get_channel(619595098279378977) try: vc = await voice_channel.connect() except: print(f"something went wrong :)") vc.play(discord.FFmpegPCMAudio(executable="C:/ffmpeg/bin/ffmpeg.exe", source="C:/Users/nullptr/Projects/Personal/justForAK/turkey-bot/sounds/echoes.mp3")) while vc.is_playing(): time.sleep(.1) if not vc.is_playing(): time.sleep(.3) await vc.disconnect() # log all messages sent in the server with a time stamp in the format YYYY:MM:DD HH:MM:SS dir = 'cache\log.txt' with open(dir, 'a') as f: time_stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') f.write(f"<{time_stamp}>{message_content}\n") await bot.process_commands(message) # tells bot to process the custom commands below
async def on_voice_state_update(member, before, after): #when user (not bot) connect to voice chat #and only if bot wasn't disconnected to any voice channel, connect him to same channel as this user if after.channel != None and before.channel == None and not member.bot: bot.number_of_users_in_voice_channels[member.guild.id] += 1 if bot.connected[member.guild.id] == False: bot.connected[member.guild.id] = True bot.moving[member.guild.id] = True bot.voice_state[member.guild.id] = await after.channel.connect() bot.moving[member.guild.id] = False #when user (not bot) moves to other voice chat #and only if there is no other user in current bot's channel, connect bot to same channel user has moved to elif after.channel != None and before.channel != None and not member.bot: users_in_channel = 0 for user in before.channel.members: if not user.bot: users_in_channel += 1 if users_in_channel == 0: bot.moving[member.guild.id] == True if bot.voice_state[member.guild.id].is_playing(): bot.voice_state[member.guild.id].stop() await bot.voice_state[member.guild.id].move_to(after.channel) bot.moving[member.guild.id] == False #when user (not bot) disconnect from voice chat #either find other member and connect to his voice channel #or disconenct from voice channels if there is no other user connected to voice channel elif after.channel == None and before.channel != None and not member.bot: bot.number_of_users_in_voice_channels[member.guild.id] -= 1 if bot.number_of_users_in_voice_channels[member.guild.id] > 0: bot.moving[member.guild.id] == True if bot.voice_state[member.guild.id].is_playing(): bot.voice_state[member.guild.id].stop() users_in_channel = 0 for user in before.channel.members: if not user.bot: users_in_channel += 1 if users_in_channel == 0: #connect to random member of guild if there is at least 1 user in voice chat #if random function find bot, we have to randomize again while bot.moving[member.guild.id] == True: user = random.choice(member.guild.members) if not user.bot: bot.connected[user.guild.id] = True bot.voice_state[user.guild.id] = await bot.voice_state[ user.guild.id].move_to(user.voice.channel) bot.moving[member.guild.id] == False else: bot.connected[member.guild.id] = False bot.voice_state[member.guild.id].stop() await bot.voice_state[member.guild.id].disconnect() #when this bot connects to channel, check if all states are ready (has bot moved) before loop elif member == bot.user: while bot.moving[member.guild.id] == True: await asyncio.sleep(0.1) #every 60 seconds play random audio. Stop it once bot disconnect or moves to other channel #there are issues when switching channels - previous loops are not lost while bot.connected[member.guild.id] == True and bot.moving[ member.guild. id] == False and bot.voice_state[member.guild.id] != None: source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(bot.dir + '/' + random.choice(os.listdir(bot.dir)))) bot.voice_state[member.guild.id].play(source) while bot.voice_state[member.guild.id].is_playing(): await asyncio.sleep(60) #all other cases (other bot connecting/moving/disconnecting) else: pass
async def verificateurHoraire(heure, minute, nom_priere, horaire_priere): global jour_actu, compteur_priere, priere_actu heure = conv_temp(heure) minute = conv_temp(minute) #verif heure if heure + ":" + minute in horaire_priere: #trouve index for i in range(len(horaire_priere)): if heure + ":" + minute == horaire_priere[i]: print("c'est l'heure") #trouve serv for guild in bot.guilds: #test_nb_priere if 0 <= int(compteur_priere[guild.id]): print(compteur_priere[guild.id]) #gestion du nb de rappel point_priere(guild) #text #trouve channel for channel in guild.text_channels: if channel.name == channel_horaire_priere: #message et suppr await channel.send( "LES FRERES C'EST L'HEURE de " + str(nom_priere[i])) #mention """for role in guild.roles: if role_horaire_priere == role.name: await channel.send(role.mention)""" #audio voc_ADHAN = None for vocal in guild.voice_channels: if vocal.name == voc_horaire_priere: voc_ADHAN = vocal if voc_ADHAN != None: for voc in guild.voice_channels: if voc.members != None: for membre in voc.members: if discord.utils.get( membre.roles, name=role_horaire_priere): await membre.move_to(voc_ADHAN) #test la connexion a un channel vocal try: await voc_ADHAN.connect() except: print("deja co " + str(guild)) finally: nb = randint(0, 2) if nb not in [0, 1, 2]: nb = 0 voice = discord.utils.get(bot.voice_clients, guild=guild) try: voice.play( discord.FFmpegPCMAudio("adhan_" + str(nb) + ".mp3")) while voice.is_playing() == True: await sleep(10) await voice.disconnect() except: print("deja Adhan " + str(guild)) else: for guild in bot.guilds: #initialisation si pas encore deja faite init_priere(guild)
async def on_message(message: discord.Message): global patternlist global word serverid = message.guild.id print(serverid) if message.author.bot: return if message.content[0:4] == "!!aw": m = message.content[5:] s = m.split(" ") df = pd.read_csv('pattern.csv') drop_index = df.index[df['before'] == s[0]] df = df.drop(drop_index) df.to_csv('pattern.csv', encoding='utf_8_sig', index=False) with open('pattern.csv', 'a', encoding="utf-8_sig") as f: writer = csv.writer(f) writer.writerow([s[0], s[1], serverid]) update() await message.channel.send("このサーバーの辞書に登録しました。" + s[0] + "→" + s[1]) if message.content[0:9] == "!!diclist": dl = "| 変換前 | 変換後 |" for i in range(0, len(patternlist)): dl += "\n" + "| " + patternlist[i] + " | " + word[i] + " |" await message.channel.send(dl) elif message.content == "!!join": if message.author.voice is None: await message.channel.send("あなたはボイスチャンネルに接続していません。") return true # ボイスチャンネルに接続する await message.author.voice.channel.connect() await message.channel.send("接続しました。") elif message.content == "!!leave": if message.guild.voice_client is None: await message.channel.send("接続していません。") return # 切断する await message.guild.voice_client.disconnect() await message.channel.send("切断しました。") elif message.content.startswith('!!'): pass else: if message.guild.voice_client: vocl = message.guild.voice_client while vocl.is_playing(): time.sleep(0.01) mc = remove_custom_emoji(message.content, serverid) with open('output.mp3', 'wb') as f: i3 = 0 for i in range(0, len(mc)): m = re.match('[a-z|A-Z|\s]+', mc[i3:]) #[ぁ-ん|ァ-ン|一-龥|ー|ア-ン| ゙|ァ-ョ] # #m1 = re.match('[ぁ-ん|ァ-ン|一-龥|ー|ア-ン| ゙|ァ-ョ|\d|%|\s|ヶ|a-z|ゔ|ヴ|→|←|↑|↓]+',mc[i3:]) m1 = re.match("[^a-zA-Z]+", mc[i3:]) if m != None: #print(inputText[i3:]) print(m.group()) tts_en = gTTS(text=m.group(), lang='en-us') tts_en.write_to_fp(f) i3 += len(m.group()) elif m1 != None: try: print(m1.group()) tts_jp = gTTS(text=m1.group(), lang='ja') tts_jp.write_to_fp(f) i3 += len(m1.group()) except AssertionError: continue else: i3 += 1 source = discord.FFmpegPCMAudio("output.mp3") message.guild.voice_client.play(source) else: pass
def add_playlist(data, new_songs): for x in data['entries']: song = Song( discord.FFmpegPCMAudio(x['url'], **self.ffmpeg_opts), x['title'], x['duration'], x['view_count'], x['url']) new_songs.append(song)
async def play(self, text_channel): """ Plays through the song queue :param channel: discord.TextChannel to send now playing message """ # Allow one thread in here at a time if self.play_lock: return self.play_lock = True # Require voice client to exist if self.vc is None: await text_channel.send(f"Voice client does not exist. Please send stop command and try again.") print(f"Voice client does not exist: {self.vc}") self.play_lock = False return ## Require voice client to be connected #if not self.vc.is_connected(): # await text_channel.send(f"Failed to join channel. Please send stop command and try again.") # await self.vc.disconnect(force=True) # self.vc = None # self.play_lock = False # return # Do nothing if already playing if self.vc.is_playing(): print("Player already playing") self.play_lock = False return # Change status text to "Now playing" if self.np_message is not None and self.np_message.embeds: try: embed = self.np_message.embeds[0] title = "Now Playing ♫" if not title == embed.title: embed.title = title await self.np_message.edit(embed=embed) except discord.errors.NotFound: pass # Player was previously paused if self.vc.is_paused(): self.vc.resume() print("Played was paused, resuming") self.play_lock = False return # Delete now playing message if no song in queue if self.queue.next_song is None: print(f"[{text_channel.guild.name}] Nothing left in queue") await self.queue.update_queue_message() await self.bot.delete_message(self.np_message) self.np_message = None self.play_lock = False return # Grab the next song and get it ready try: song = self.queue.next_song song = await self.youtube.load_song(song) except IndexError: await text_channel.send(f"Something went wrong fetching song from queue (Error code: {len(self.queue.songs)} {self.queue.position})") self.play_lock = False return # Get the mp3 ready try: await self.download_song(song) except Exception as error: await text_channel.send(f"Error downloading {song.title} {error}") await self.increment_position() self.play_lock = False return # Log song info print(f"[{text_channel.guild.name}] ({song.user.display_name}) playing {song.title} ({song.plays} plays)") # Create the audio source. FFmpegPCMAudio reference: # https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegPCMAudio options = f"-af loudnorm=I=-16.0:TP=-1.0 -ss {song.position}" try: audio_source_raw = discord.FFmpegPCMAudio(source=song.path, options=options) except discord.errors.ClientException: audio_source_raw = discord.FFmpegPCMAudio(source=song.path, executable="C:/ffmpeg/bin/ffmpeg.exe", options=options) # Set the volume. PCMVolumeTransformer reference: # https://discordpy.readthedocs.io/en/latest/api.html#discord.PCMVolumeTransformer audio_source = discord.PCMVolumeTransformer(audio_source_raw, volume=self.volume / 100.0) # Begin playback self.vc.play(audio_source) # Send now-playing message and update queue await self.send_now_playing(text_channel=text_channel) await self.queue.update_queue_message() # Wait for it to finish while self.vc and self.vc.is_playing(): await asyncio.sleep(2) # Player was stopped or paused if self.vc is None or self.vc.is_paused(): self.play_lock = False return # Song finished playing - increment playcount in database song.plays += 1 self.bot.db.save_song(song) # Go on to the next song await self.increment_position() # Update queue message await self.queue.update_queue_message() self.play_lock = False await self.play(text_channel)
async def play(ctx, *, command=None): global server, server_id, name_channel author = ctx.author if command is None: server = ctx.guild name_channel = author.voice.channel.name voice_channel = discord.utils.get(server.voice_channels, name=name_channel) params = command.split(' ') if len(params) == 1: source = params[0] server = ctx.guild name_channel = author.voice.channel.name voice_channel = discord.utils.get(server.voice_channels, name=name_channel) elif len(params) == 3: server_id = params[0] voice_id = params[1] source = params[2] try: server_id = int(server_id) voice_id = int(voice_id) except Exception as e: await ctx.chanell.sen( f'{author.mention}, id the server or voice must be an integer!' ) print(e) return server = bot.get_guild(server_id) voice_channel = discord.utils.get(server.voice_channels, id=voice_id) else: await ctx.channel.send(f'{author.mention}, command is not correct') return voice = discord.utils.get(bot.voice_clients, guild=server) if voice is None: await voice_channel.connect() voice = discord.utils.get(bot.voice_clients, guild=server) if source is None: pass elif source.startswith('http'): if not check_domains(source): await ctx.channel.send(f'{author.mention}, link is not allowed') return song_there = os.path.isfile('music/song.mp3') try: if song_there and voice is None: os.remove('music/song.mp3') elif not (voice is None) and False: await ctx.channel.send(f'{author.mention}, wait then bot stop.' ) except PermissionError: await ctx.channel.send('Not enough rights to delete file!') return ydl_opts = { 'outtmpl': "music/song.mp3", 'format': 'bestaudio/best', 'noplaylist': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }] } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([source]) voice.play( discord.FFmpegPCMAudio(executable='ffmpeg.exe', source='music/song.mp3')) await ctx.channel.send(f'')
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(que) still_q = length - 1 search = queue_coll.find_one({'guildid': ctx.guild.id, 'song_num': 1}) dwnld = search['url'] q_num = search['song_num'] queue_path = os.path.abspath(os.path.realpath("Queue")) print("Downloading song to: " + queue_path) ydl_opts = { 'format': 'bestaudio/best', 'noplaylist': '', 'default_search': 'ytsearch', 'outtmpl': queue_path, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading Queued audio now\n") ydl.download([dwnld]) except: print("FALLBACK: Youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)") system("spotdl -f " + '"' + queue_path + '" -nf ' + " -s " + dwnld) print('Song downloaded.') queue_coll.delete_one({'guildid': ctx.guild.id, 'song_num': 1}) for x in queue_coll.find({'guildid': ctx.guild.id}): num = x["song_num"] queue_coll.update_one(x, {'$set': {'song_num': (num-1)}}) print("Collection updated") try: first_file = os.listdir(DIR)[0] print("Found first file") except: print('No more songs queued\n') que.clear() queue_coll.delete_many({'guildid': ctx.guild.id}) print("Collection cleared") return main_location = os.path.dirname(os.path.realpath(__file__)) song_path = os.path.abspath(os.path.realpath('Queue') + "\\" + first_file) print("Found file path") if length != 0: print('Song done. Playing next in Queue\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) print("Removed old song file") for file in os.listdir('./'): if file.endswith('.mp3'): os.renames(file, 'song.mp3') print("Renamed new song to song.mp3") voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.5 else: que.clear() print('No songs were queued before the end of the last song.\n') channel = ctx.author.voice.channel song_there = os.path.isfile("song.mp3") try: if song_there: os.remove("song.mp3") que.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') 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) if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() await ctx.send(f'Connected to {channel}') ydl_opts = { 'format': 'bestaudio/best', 'noplaylist': '', 'default_search': 'ytsearch', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") ydl.download([url]) title = ydl.extract_info(url, download=False).get('title', None) 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 -f " + '"' + c_path + '" -nf ' + " -s " + url) for file in os.listdir("./"): if file.endswith(".mp3"): name = file print(f'Renamed File: {file} to song.mp3\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.5 nname = name.rsplit("-", 2) try: await ctx.send(f'Playing: {nname[0]}\n') await ctx.send(f'Title: {title}\n') except: await ctx.send('Playing Song') print("playing\n")
def play_next(ctx=ctx, data=data): ctx.voice_client.play(discord.FFmpegPCMAudio( data['url'], **self.FFMPEG_OPTIONS), after=lambda _: play_next() if self.repeat 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(que) still_q = length - 1 search = queue_coll.find_one({'guildid': ctx.guild.id, 'song_num': 1}) dwnld = search['url'] q_num = search['song_num'] queue_path = os.path.abspath(os.path.realpath("Queue")) print("Downloading song to: " + queue_path) ydl_opts = { 'format': 'bestaudio/best', 'noplaylist': '', 'default_search': 'ytsearch', 'outtmpl': queue_path, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading Queued audio now\n") ydl.download([dwnld]) except: print("FALLBACK: Youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)") system("spotdl -f " + '"' + queue_path + '" -nf ' + " -s " + dwnld) print('Song downloaded.') queue_coll.delete_one({'guildid': ctx.guild.id, 'song_num': 1}) for x in queue_coll.find({'guildid': ctx.guild.id}): num = x["song_num"] queue_coll.update_one(x, {'$set': {'song_num': (num-1)}}) print("Collection updated") try: first_file = os.listdir(DIR)[0] print("Found first file") except: print('No more songs queued\n') que.clear() queue_coll.delete_many({'guildid': ctx.guild.id}) print("Collection cleared") return main_location = os.path.dirname(os.path.realpath(__file__)) song_path = os.path.abspath(os.path.realpath('Queue') + "\\" + first_file) print("Found file path") if length != 0: print('Song done. Playing next in Queue\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) print("Removed old song file") for file in os.listdir('./'): if file.endswith('.mp3'): os.renames(file, 'song.mp3') print("Renamed new song to song.mp3") voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.5 else: que.clear() print('No songs were queued before the end of the last song.\n')
async def play(vc, file): vc.play(discord.FFmpegPCMAudio(source=file)) while vc.is_playing(): await asyncio.sleep(1)
async def on_message(message): # We do not want the bot to reply to itself if message.author == client.user: return channel = message.channel # Only respond to allowed channel if channel.id != bot_control_channel_id: return author = str(message.author) if message.content.startswith('!hello'): msg = 'Hello {0.author.mention}'.format(message) await channel.send(msg) elif message.content.startswith('!work'): if message.author in work_time_dictionary: old_tuple = work_time_dictionary[message.author] work = message.content.replace('!work ', '') work_time_dictionary[message.author] = (old_tuple[0], old_tuple[1], old_tuple[2], work) await channel.send("C'est noté") else: await channel.send("T'es pas en session de travail présentement") elif message.content.startswith('!csv'): if (path.exists("./Persistence/Work.csv")): file_to_send = discord.File(open("./Persistence/Work.csv", "rb")) await channel.send("Keep up the good work", file=file_to_send) file_to_send.close() else: await channel.send("Aucun csv n'a été créé pour le moment") elif message.content.startswith('!dashboard'): if (path.exists("./Persistence/Work.csv")): await channel.send("Voici les statistiques calculées par JM") await channel.send(func.CreateListMessage(dashboard.dashboard())) else: await channel.send("Aucun csv n'a été créé pour le moment") elif message.content.startswith('!version'): try: await channel.send("JM est présentement au commit: " + func.get_version()) except: await channel.send("Git n'est pas disponible...") elif message.content.startswith('!what is my purpose'): msg = 'https://www.youtube.com/watch?v=wqzLoXjFT34'.format(message) await channel.send(msg) elif message.content.startswith('!time'): work = message.content.replace('!time ', '') try: date, date_delta, desc = func.get_time_to_add_and_desc(work) tuple_time = (message.author, date_delta, date, "MANUAL_TIME[" + desc + "]") func.print_to_csv(tuple_time) await channel.send("Temps ajouté!") except ValueError as err: await channel.send( "Format non valide, devrait être !commande XXHXXM description") elif message.content.startswith('!play'): if (message.author.voice == None): await channel.send("T'es même pas connecté... Git Gud!") else: message_content = message.content.lower() audio_track = "./Audio/" + \ message_content.replace('!play ', '')+".mp3" if (path.exists(audio_track)): voice_channel = client.get_channel( message.author.voice.channel.id) voice_client = await voice_channel.connect(reconnect=False) if voice_client != None: audio = discord.FFmpegPCMAudio(audio_track) voice_client.play(audio) while (voice_client.is_playing()): time.sleep(0.25) continue await voice_client.disconnect() else: if (message.content == '!play'): await channel.send( "U Stupid!? Quel fichier tu veux que je joue?") else: await channel.send("Bro... ça existe ton fichier " + message.content.replace('!play ', '') + "!") elif message.content.startswith('!list'): await channel.send("Voici la liste des fichiers audios disponibles:") await channel.send( func.CreateListMessage(func.GetFilesFromFolder("./Audio"))) elif message.content.startswith('!help'): await channel.send("You must be desperate to come to me for help...") actionList = [ '!hello si tu te cherches un ami', '!play _nom de piste voulu_', '!list pour voir les pistes disponibles', '!work pour décrire ta session de travail, si elle existe', '!csv envoye le csv de travail', '!version pour voir la version déployée', '!dashboard pour avoir le nombre d\'heure des membres de UNC-I', '!time pour ajouter manuellement du temps de travail, devrait être !time XXHXXM description' ] await channel.send(func.CreateListMessage(actionList)) elif message.content.startswith('!saucemepls'): await channel.send(func.WeirdGIFpourPhil())
async def rick(ctx, channel: discord.VoiceChannel): connection = await channel.connect() connection.play(discord.FFmpegPCMAudio("rick.mp3", executable="ffmpeg.exe"))
async def play_audio(client: discord.Client, message: discord.Message): sections = message.content.split(' ') if sections[0] == "!play": if _PLAYING: if _CURRENT_USER_PLAYING_MUSIC != message.author: return if not is_sender_counselor(message): log.debug( f"[PREPA_BREACH] user {message.author.nick} tried to to command {message.content}") await message.author.send(f"{message.author.nick}, no tienes los permisos para usar este comando") return if not hasattr(message.author, 'voice'): await message.author.send('No puedes unirme a un canal de voz desde el DM') return user_name = None if hasattr(message.author, 'nick'): user_name = message.author.nick else: user_name = message.author.name if len(sections) < 2: await message.author.send(f"{user_name}, te falto el URL del video o cancion. Puede ser de cualquier website publico. (Youtube, Soundcloud, etc.)") return url = sections[1] global _MUSIC_FILE try: if os.path.isfile(_MUSIC_FILE): os.remove(_MUSIC_FILE) except PermissionError: await message.author.send('No puedo dar play a otra cancion. Un audio esta en play.\nPonlo en pausa.') return voice_client: discord.VoiceClient = discord.utils.get( client.voice_clients, guild=message.guild) if not voice_client: await message.author.send(f"No estoy conectado a ningun canal de voz") return if voice_client.is_playing(): await message.author.send(f'No puedo darle PLAY a un audio mientras uno esta en PLAY. Intenta pausar el audio primero') return ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': f"{os.path.join(_CURRENT_DIR, 'res', 'audio', '%(title)s.%(ext)s')}", 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") ydl.download([url]) except youtube_dl.DownloadError as err: print(f'[ERROR] {err}') await message.author.send(f'Me econtre con un error descargando el video.\n' f"Error:\n{str(err)}") return name = "" for file in os.listdir(os.path.join(_CURRENT_DIR, "res", "audio")): if file.endswith(".mp3"): name = file os.rename(os.path.join(_CURRENT_DIR, "res", "audio", file), _MUSIC_FILE) voice_client.play(discord.FFmpegPCMAudio(_MUSIC_FILE)) name = name.replace('.mp3', '') nname = name.rsplit("-", 2) await message.author.send(f"{user_name}, ya **'{name} '** esta en PLAY")
async def listen(ctx): ctx.guild.voice_client.play( discord.FFmpegPCMAudio(config_ini['DEFAULT']['FILEPATH'])) time.sleep(5)
async def play2(self, ctx, url): 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()[0] except: print("No more queued song(s)\n") asyncio.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') server = ctx.message.author.guild voice = server.voice_client voice.play(discord.FFmpegPCMAudio('song.mp3'), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) voice.source.volume = 0.07 else: asyncio.queues.clear() return else: asyncio.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") asyncio.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") server = ctx.message.author.guild voice = server.voice_client 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") 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")
def updateSource(): global source #global currentWeather global cur_user source = discord.PCMVolumeTransformer( discord.FFmpegPCMAudio(currentWeather))
async def banger(ctx): await ctx.author.voice.channel.connect() voice = ctx.channel.guild.voice_client voice.play( discord.FFmpegPCMAudio(executable="YOURFFMPEGPATH", source="./audio/tektonik.mp3"))