async def twitter_unfollow(self, ctx, handle): """Unfollows a Twitter channel. The tweets from the given Twitter channel will not be sent to the channel this command was used in anymore. You do not need to include the '@' before the Twitter channel's handle, it will avoid unwanted mentions in Discord. """ sane_handle = handle.lower().lstrip('@') conf = dutils.get(self.conf.follows, screen_name=sane_handle) chan_conf = dutils.get(conf.discord_channels, id=ctx.message.channel.id) if conf is not None else None if chan_conf is None: raise TwitterError('Not following {} on this channel.'.format(handle)) # Remove the Discord channel from the Twitter channel conf conf.discord_channels.remove(chan_conf) if not conf.discord_channels: # If there are no more Discord channel to feed, unfollow the Twitter channel self.conf.follows.remove(conf) del conf # Update the tweepy stream if len(self.conf.follows) > 0: await self.stream.start() else: self.stream.stop() self.conf.save() await self.bot.say('\N{OK HAND SIGN}')
async def twitter_follow(self, ctx, handle): """Follows a Twitter channel. The tweets from the given Twitter channel will be sent to the channel this command was used in. You do not need to include the '@' before the Twitter channel's handle, it will avoid unwanted mentions in Discord. Following protected users is not supported by the Twitter API. See https://dev.twitter.com/streaming/overview/request-parameters#follow """ discord_channel = ctx.message.channel # Check for required permissions if not discord_channel.permissions_for(discord_channel.server.me).embed_links: raise TwitterError('\N{WARNING SIGN} The `Embed Links` permission in this channel is required to display tweets properly. \N{WARNING SIGN}') sane_handle = handle.lower().lstrip('@') conf = dutils.get(self.conf.follows, screen_name=sane_handle) if conf is None: # New Twitter channel, retrieve the user info partial = functools.partial(self.api.get_user, screen_name=sane_handle) try: user = await self.bot.loop.run_in_executor(None, partial) except tweepy.TweepError as e: if e.api_code == 50: raise TwitterError('User "{}" not found.'.format(handle)) from e else: log.error(str(e)) raise TwitterError('Unknown error, this has been logged.') from e # The Twitter API does not support following protected users # https://dev.twitter.com/streaming/overview/request-parameters#follow if user.protected: raise TwitterError('This channel is protected and cannot be followed.') # Register the new channel conf = FollowConfig(user.id_str, user.screen_name) self.conf.follows.append(conf) try: # Restart the stream await self.stream.start() except tweepy.TweepError as e: self.conf.follows.remove(conf) log.error(str(e)) raise TwitterError('Unknown error, this has been logged.') from e elif dutils.get(conf.discord_channels, id=discord_channel.id): raise TwitterError('Already following {} on this channel.'.format(handle)) # Add new Discord channel conf.discord_channels.append(ChannelConfig(discord_channel.id)) self.conf.save() await self.bot.say('\N{OK HAND SIGN}')
async def _welcome_remove(self, ctx, channel): server = ctx.message.server.id channel_mentions = ctx.message.channel_mentions if server not in self.welcome_messages: return channel = utils.get(channel_mentions, mention=channel) if channel is None: await self.bot.say('Invalid channel.') return if channel.id in self.welcome_messages[server]: del self.welcome_messages[server][channel.id] self.save_welcome()
async def tweepy_on_status(self, tweet): """Called by the stream when a tweet is received.""" self.processed_tweets += 1 if self.skip_tweet(tweet): return chan_conf = dutils.get(self.conf.follows, id=tweet.author.id_str) try: embed = await self.prepare_embed(tweet) content = None except: embed = None content = 'Failed to prepare embed for ' + tweet.tweet_web_url # If the preparation failed before setting tweet.tweet_web_url imma kms log.error('Failed to prepare embed for ' + str(tweet._json)) # Make sure we're ready to send messages await self.bot.wait_until_ready() for channel in chan_conf.discord_channels: discord_channel = self.bot.get_channel(channel.id) # Check if the channel still exists if discord_channel is None: log.error('Channel {} unavailable to display tweet {}.'.format(discord_channel.id, tweet.id_str)) continue # Check for required permissions perms = discord_channel.permissions_for(discord_channel.server.me) if not perms.embed_links: log.warning('Improper permissions in channel {} to display tweet {}.'.format(discord_channel.id, tweet.id_str)) try: warning = '\N{WARNING SIGN} Missed tweet from {} : `Embed links` permission missing. \N{WARNING SIGN}'.format(tweet.author.screen_name) await self.bot.send_message(discord_channel, warning) except discord.DiscordException as e: log.error('Could not send warning to channel {}.\n{}'.format(discord_channel.id, e)) continue # Send the embed to the appropriate channel log.debug('Scheduling Discord message on channel ({}) : {}'.format(channel.id, tweet.text)) await self.bot.send_message(discord_channel, content=content, embed=embed) # Update stats and latest id when processing newer tweets if tweet.id > chan_conf.latest_received: channel.received_count += 1 chan_conf.latest_received = tweet.id self.conf.save()
async def _welcome_set(self, ctx, *, message): """You can use $user to mention the member who joins""" server = ctx.message.server.id channel_mentions = ctx.message.channel_mentions if server not in self.welcome_messages: self.welcome_messages[server] = {} if len(channel_mentions) == 0: channel = ctx.message.server.default_channel else: poss_mention = message.split(" ")[0] if not re.compile(r'<#([0-9]+)>').match(poss_mention): channel = ctx.message.server.default_channel else: channel = utils.get(channel_mentions, mention=poss_mention) message = message[len(channel.mention) + 1:] # for the space self.welcome_messages[server][channel.id] = message fileIO("data/botinfo/welcome.json", "save", self.welcome_messages) await self.bot.say('Member join message on ' '{} set to:\n\n{}'.format(channel.mention, message))
async def unlockserver(self, ctx: commands.Context): """ Unlock the entire server for `@everyone` """ has_been_set = await self.config.guild(ctx.guild).has_been_set() if not has_been_set: return await ctx.send( f"You have to do `{ctx.clean_prefix}setlock setup` first!") async with ctx.typing(): toggle = await self.config.guild(ctx.guild).toggle() if not toggle: return await ctx.send( "Uh oh. Lock isn't enabled in this server. Ask your Admins to enable it." ) everyone = get(ctx.guild.roles, name="@everyone") mods_id = await self.config.guild(ctx.guild).moderator() mods = get(ctx.guild.roles, id=mods_id) which = await self.config.guild(ctx.guild).everyone() special = await self.config.guild(ctx.guild).special() defa = await self.config.guild(ctx.guild).defa() ignore = await self.config.guild(ctx.guild).ignore() if not mods: return await ctx.send( "Uh oh. Looks like your Admins haven't setup this yet.") for channel in ctx.guild.text_channels: if channel.id in ignore: continue if which: # if everyone can see the channels await channel.set_permissions(everyone, read_messages=True, send_messages=True) else: if special: # if True, some roles can see some channels if not defa: config_channels = await self.config.guild( ctx.guild).channels.get_raw() check_channels = [ int(c_id) for c_id in config_channels ] for ig_id in ignore: check_channels.append(ig_id) if any(channel.id not in check_channels for channel in ctx.guild.text_channels): return await ctx.send( "Uh oh. I cannot let you do this. Ask your Admins to add remaining channels." ) c = await self.config.guild( ctx.guild).channels.get_raw(channel.id) if c: for role_id in c["roles"]: ro = get(ctx.guild.roles, id=role_id) await channel.set_permissions( ro, read_messages=True, send_messages=True) else: def_roles = await self.config.guild(ctx.guild ).def_roles() for def_role_id in def_roles: def_ro = get(ctx.guild.roles, id=def_role_id) await channel.set_permissions( def_ro, read_messages=True, send_messages=True) else: # if False, all special roles can see same channels roles = await self.config.guild(ctx.guild).roles() for role_id in roles: ro = get(ctx.guild.roles, id=role_id) await channel.set_permissions(ro, read_messages=True, send_messages=True) await channel.set_permissions(mods, read_messages=True, send_messages=True) await ctx.send(":unlock: Server unlocked.")
async def lock(self, ctx: commands.Context, seconds=0): """Lock `@everyone` from sending messages. Optionally, you can set how many seconds the channel should stay locked for.""" has_been_set = await self.config.guild(ctx.guild).has_been_set() if not has_been_set: return await ctx.send( f"You have to do `{ctx.clean_prefix}setlock setup` first!") async with ctx.typing(): toggle = await self.config.guild(ctx.guild).toggle() if not toggle: return await ctx.send( "Uh oh. Lock isn't enabled in this server. Ask your Admins to enable it." ) everyone = get(ctx.guild.roles, name="@everyone") mods_id = await self.config.guild(ctx.guild).moderator() mods = get(ctx.guild.roles, id=mods_id) which = await self.config.guild(ctx.guild).everyone() special = await self.config.guild(ctx.guild).special() defa = await self.config.guild(ctx.guild).defa() ignore = await self.config.guild(ctx.guild).ignore() if not mods: return await ctx.send( "Uh oh. Looks like your Admins haven't setup this yet.") if ctx.channel.id in ignore: return await ctx.send( "Uh oh. This channel is in the ignored list.") if which: # if everyone can see the channels await ctx.channel.set_permissions(everyone, read_messages=True, send_messages=False) else: await ctx.channel.set_permissions(everyone, read_messages=False, send_messages=False) if special: # if True, some roles can see some channels c_ctx = ctx.channel.id c = await self.config.guild(ctx.guild ).channels.get_raw(c_ctx) if c: for role_id in c["roles"]: ro = get(ctx.guild.roles, id=role_id) await ctx.channel.set_permissions( ro, read_messages=True, send_messages=False) else: if not defa: return await ctx.send( "Uh oh. This channel has no settings. Ask your Admins to add it." ) def_roles = await self.config.guild(ctx.guild ).def_roles() for def_role_id in def_roles: def_ro = get(ctx.guild.roles, id=def_role_id) await ctx.channel.set_permissions( def_ro, read_messages=True, send_messages=False) else: # if False, all special roles can see same channels roles = await self.config.guild(ctx.guild).roles() for role_id in roles: ro = get(ctx.guild.roles, id=role_id) await ctx.channel.set_permissiouuuns( ro, read_messages=True, send_messages=False) await ctx.channel.set_permissions(mods, read_messages=True, send_messages=True) if seconds == 0: return await ctx.send( ":lock: Channel locked. Only Moderators can type.") await ctx.send( f":lock: Channel locked for {seconds} seconds. Only Moderators can type." ) await asyncio.sleep(seconds) await ctx.invoke(self.bot.get_command("unlock"))
async def play(self, ctx, url: str = ""): def check_queue(): Queue_infile = os.path.isdir("./music/queue") if Queue_infile is True: dir = "./music/queue" length = len(os.listdir(dir)) still_q = length - 1 try: first_file = os.listdir(dir)[0] except: queues.clear() return main_location = "./music/youtube" song_path = "./music/queue" + "/" + first_file if length != 0: print("Song done,playing next queued\n") song_there = os.path.isfile('./music/youtube/song.mp3') if song_there: os.remove('./music/youtube/song.mp3') shutil.move(song_path, main_location) for file in os.listdir("./music/youtube"): if file.endswith(".mp3"): os.rename('./music/youtube/' + file, './music/youtube/song.mp3') music_playlist.pop(0) voice.play( discord.FFmpegPCMAudio('./music/youtube/song.mp3'), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source) else: queues.clear() return else: queues.clear() def add_to_queue(): Queue_infile = os.path.isdir("./music/queue") print(Queue_infile) if Queue_infile is False: os.mkdir("./music/queue") dir = "./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 # queue_path = "./music/queue/%(title)s.%(ext)s" ydl_opts = { 'format': 'bestaudio/best', # 'outtmpl': queue_path, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") ydl.download([url]) info = ydl.extract_info(url) for file in os.listdir('./'): if file.endswith(".mp3"): name = file os.rename(file, f'./music/queue/song{q_num}.mp3') nname = name.rsplit("-", 2) music_playlist.append(info['title']) # ------------------------------------connect ------------------------------------------------------# global voice channel = ctx.message.author.voice.channel voice = get(self.bot.voice_clients, guild=ctx.guild) if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() # ------------------------------------------ download ----------------------------------------------------# path = "./music/youtube/song.mp3" song_there = os.path.isfile(path) try: if song_there: os.remove(path) queues.clear() except PermissionError: add_to_queue() emoji = '<:lm20:567188297638608914>' await ctx.send(F"加咗入條list,排緊隊{emoji}") return queue_infile = os.path.isdir("./music/queue") try: queue_folder = "./music/queue" if queue_infile is True: print("removed old queue folder") shutil.rmtree(queue_folder) except: print("No old queue folder") voice = get(self.bot.voice_clients, guild=ctx.guild) ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: print("Downloading audio now\n") ydl.download([url]) info = ydl.extract_info(url) for file in os.listdir("./"): if file.endswith(".mp3"): name = file os.rename(file, './music/youtube/song.mp3') # ------------------------------------------ play ----------------------------------------------------# nname = name.rsplit("-", 2) music_playlist.append(info['title']) voice.play(discord.FFmpegPCMAudio("./music/youtube/song.mp3"), after=lambda e: check_queue()) voice.source = discord.PCMVolumeTransformer(voice.source)
async def pause(self, ctx): voice = get(self.client.voice_clients, guild= ctx.guild) if voice and voice.is_playing(): voice.pause()
async def play(ctx,*,songName: 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.1 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("Remove 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(client.voice_clients, guild=ctx.guild) ydl_opts = { 'format':'bestaudio/best', 'quiet':True, 'outtmpl':"./Song.mp3", 'postprocessors': [{ 'key':'FFmpegExtractAudio', 'preferredcodec':'mp3', 'preferredquality':'320', }], } url = await gettingUrl(songName) if url: song_search = "".join(url) else: await ctx.send("Please put a valid 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 unantiraid(ctx): try: author = ctx.message.author message = ctx.message await message.delete() guild = ctx.guild staffrole = get(guild.roles, id=StaffRoleID) if staffrole in author.roles: global antiraidv if antiraidv == True: antiraidv = False await ctx.channel.edit(slowmode_delay=0) embed = discord.Embed( title=f'Anti-Raid Mode Disabled', description= f'''Anti-Raid has been disabled! New members will now be able to join. This channel's cooldown time has been set to 0.''', color=embedcolor) embed.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: message1 = await ctx.send(embed=embed) except discord.HTTPException: message1 = await ctx.send( f'''Anti-Raid is disabled!\nThis channel's cooldown time has been set to 0.''' ) syslogc = bot.get_channel(SystemLogsChannelID) embed2 = discord.Embed( title='Anti-Raid Mode Disabled', description= f'{author.mention} has disabled anti-raid mode for this server.', color=embedcolor) embed2.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed2.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed2.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: await syslogc.send(embed=embed2) except discord.HTTPException: await syslogc.send( f"Anti-Raid Mode Disabled\n{author.mention} has disabled anti-raid mode for this server." ) await asyncio.sleep(30) await message1.delete() if antiraidv == False: await ctx.channel.edit(slowmode_delay=0) embed = discord.Embed( title=f'Anti-Raid Mode', description= f'''Anti-Raid is disabled! This channel's cooldown time has been set to 0.''', color=embedcolor) embed.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: message1 = await ctx.send(embed=embed) except discord.HTTPException: message1 = await ctx.send( f"Anti-Raid is disabled!\nThis channel's cooldown time has been set to 0." ) await asyncio.sleep(30) await message1.delete() else: message5 = await ctx.send(f'{author.mention}') await message5.delete() embed5 = discord.Embed( description= f'''{author.mention}, you can't use that command!''', color=embedcolor) embed5.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed5.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed5.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: message6 = await ctx.send(embed=embed5) except discord.HTTPException: message6 = await ctx.send( f'''{author.mention}, **you can't use that command!**''') await asyncio.sleep(20) await message6.delete() except Exception as e: developer = bot.get_user(developerid) text = str('''Error on line {}'''.format(sys.exc_info()[-1].tb_lineno)) embed = discord.Embed(title='commands.unantiraid function fail', description=f'{text}, {str(e)}', color=embedcolor) try: await developer.send(embed=embed) except discord.HTTPException: await developer.send("commands.unantiraid function fail" + str(e)) print('[ERROR][Line {}]:'.format(sys.exc_info()[-1].tb_lineno) + f'{str(e)}') print("----------------------------------------") await asyncio.sleep(10)
async def namerater(self, ctx, arg1: str): if get(ctx.message.author.roles, name="Max Host") or get(ctx.message.author.roles, name="Mods"): await ctx.channel.edit(name = arg1)
async def play(ctx, url: str): if ctx.message.author.voice: channel = ctx.message.author.voice.channel voice = get(client.voice_clients, guild=ctx.guild) if voice and voice.is_connected(): await voice.move_to(channel) else: await channel.connect() await ctx.send(f"mugenMusicBot has joined the '{channel}' Channel") voice = get(client.voice_clients, guild=ctx.guild) queue.queue.clear() def queue_func(): if queue.not_empty: ydl_opts = { 'default_search': 'auto', 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } FFMPEG_OPTIONS = { 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn' } URL = queue.get() with youtube_dl.YoutubeDL(ydl_opts) as ydl: extracted_song = ydl.extract_info(URL, download=False) title = extracted_song.get('title') print(f'Extracting song : "{title}"') voice.guild.voice_client.play(discord.FFmpegPCMAudio( extracted_song["formats"][0]["url"], **FFMPEG_OPTIONS), after=lambda e: queue_func()) voice.source = discord.PCMVolumeTransformer( voice.guild.voice_client.source) voice.source.volume = 10.0 print('beta') elif not voice.is_playing(): queue.clear() ctx.send( 'No songs were queued before the ending of the last song\n') server = ctx.message.guild.voice_client server.disconnect() ydl_opts = { 'default_search': 'auto', 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } FFMPEG_OPTIONS = { 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn' } with youtube_dl.YoutubeDL(ydl_opts) as ydl: extracted_song = ydl.extract_info(url, download=False) title = extracted_song.get('title') print(f'Extracting song : "{title}"') voice.guild.voice_client.play(discord.FFmpegPCMAudio( extracted_song["formats"][0]["url"], **FFMPEG_OPTIONS), after=lambda e: queue_func()) voice.source = discord.PCMVolumeTransformer( voice.guild.voice_client.source) voice.source.volume = 10.0
async def getRole(guild, name, colour=0x1fff7c): role = get(guild.roles, name=name) if role is None: return await guild.create_role(name=name, colour=discord.Colour(colour)) else: return role
async def resume(ctx): voice = get(Bot.voice_clients, guild=ctx.guild) voice.resume()
async def pause(ctx): voice = get(Bot.voice_clients, guild=ctx.guild) voice.pause()
async def stop(ctx): voice = get(Bot.voice_clients, guild=ctx.guild) voice.stop()
async def antiraid(self, ctx): await ctx.send("Would you like to enable or disable the anti-raid feature?. ON/OFF") msg = await self.client.wait_for('message', timeout=60.0, check=lambda message: message.author == ctx.author) if not msg.content.lower() == 'off' and not msg.content.lower() == 'on': await ctx.send('Invalid argument given. Please restart.') return with open('max-server-joins.json', 'r') as f2: max_joins = json.load(f2) if msg.content.lower() == 'off': await ctx.send('Turning off...') max_joins[str(ctx.guild.id)] = [max_joins[str(ctx.guild.id)][0], max_joins[str(ctx.guild.id)][1], max_joins[str(ctx.guild.id)][2], False] with open('max-server-joins.json', 'w') as f: json.dump(max_joins, f, indent=4) await ctx.send('Disabled succesfully!') else: await ctx.send("Starting setup. Please note that if you do not reply for a minute it will be cancelled.") await ctx.send("Alright. First, send the name of the role you would like to be given to new members. (without the '@')") msg = await self.client.wait_for('message', timeout=60.0, check=lambda message: message.author == ctx.author) if get(ctx.guild.roles, name=msg.content): role = get(ctx.guild.roles, name=msg.content) else: await ctx.send('Invalid role given. Please restart setup.') return await ctx.send("""Alright. Now, please specify a time period in seconds you want to reset the join amount. Minimum is 60 and maximum is 86400. Examples: - 60 (one minute) - 3600 (one hour) - 86400 (one day)""") msg = await self.client.wait_for('message', timeout=60.0, check=lambda message: message.author == ctx.author) if not str(msg.content).isnumeric(): await ctx.send('Given time is not a number. Please restart setup.') return elif int(msg.content) > 86400: await ctx.send('Invalid time given. Please restart setup.') return else: await ctx.send(f'Time set to {int(msg.content)} seconds.') server_time = int(msg.content) await ctx.send("How many users can join in the specified time before the antiraid turns on?") msg = await self.client.wait_for('message', timeout=60.0, check=lambda message: message.author == ctx.author) if not str(msg.content).isnumeric(): await ctx.send('Given amount is not a number. Please restart setup.') return else: user_joins = str(msg.content) await ctx.send('Applying settings...') max_joins[str(ctx.guild.id)] = [user_joins, str(server_time), str(role), True] with open('max-server-joins.json', 'w') as f: json.dump(max_joins, f, indent=4) await ctx.send("Applied succesfully! Deleting messages...") await asyncio.sleep(2) await ctx.channel.purge(limit=13)
async def apply(self, ctx: commands.Context): """Apply to be a staff member.""" if not await self.config.guild(ctx.guild).channel_id(): return await ctx.send( "Uh oh, the configuration is not correct. Ask the Admins to set it." ) role_add = None channel = None if await self.config.guild(ctx.guild).applicant_id(): try: role_add = ctx.guild.get_role( await self.config.guild(ctx.guild).applicant_id() ) except TypeError: pass if not role_add: role_add = get(ctx.guild.roles, name="Staff Applicant") if not role_add: return await ctx.send( "Uh oh, the configuration is not correct. Ask the Admins to set it." ) try: channel = ctx.guild.get_channel( await self.config.guild(ctx.guild).channel_id() ) except TypeError: pass if not channel: channel = get(ctx.guild.text_channels, name="applications") if not channel: return await ctx.send( "Uh oh, the configuration is not correct. Ask the Admins to set it." ) try: await ctx.author.send("Let's start right away!") except discord.Forbidden: return await ctx.send( "I don't seem to be able to DM you. Do you have closed DMs?" ) await ctx.send(f"Okay, {ctx.author.mention}, I've sent you a DM.") embed = discord.Embed( color=await ctx.embed_colour(), timestamp=datetime.datetime.now() ) embed.set_author(name="New application!", icon_url=ctx.author.avatar_url) embed.set_footer( text=f"{ctx.author.name}#{ctx.author.discriminator} ({ctx.author.id})" ) embed.title = ( f"User: {ctx.author.name}#{ctx.author.discriminator} ({ctx.author.id})" ) def check(m): return m.author == ctx.author and m.channel == ctx.author.dm_channel questions = await self.config.guild(ctx.guild).questions() # list of lists default_questions = ( await self._default_questions_list() ) # default list of lists just in case for i, question in enumerate(questions): # for list in lists try: await ctx.author.send(question[0]) timeout = question[2] shortcut = question[1] except TypeError: await ctx.author.send(default_questions[i][0]) timeout = default_questions[i][2] shortcut = default_questions[i][1] try: answer = await self.bot.wait_for( "message", timeout=timeout, check=check ) except asyncio.TimeoutError: return await ctx.author.send("You took too long. Try again, please.") embed.add_field(name=shortcut + ":", value=answer.content) await channel.send(embed=embed) if role_add: await ctx.author.add_roles(role_add) await ctx.author.send( "Your application has been sent to the Admins, thank you!" )
async def _revive(self, ctx, *args, free=False): """ send revive message to @Reviver """ logging.info( f'[revive/revive] {ctx.guild}: {ctx.author.nick} / {ctx.author}') logging.info(f'[revive/revive] Free = {free}') # get configuration config = self.bot.get_guild_configuration_by_module( ctx.guild, "revive") if not config: return # check if channel is allowed allowed = await self.bot.check_channel_allowed(ctx, config) if not allowed: return # Get user key errors = [] status, id, name, key = await self.bot.get_user_key(ctx, ctx.author, needPerm=False, returnMaster=True, delError=True) # return 0, id, Name, Key: All good # return -1, None, None, None: no master key given # return -2, None, None, None: master key api error # return -3, master_id, None, master_key: user not verified # return -4, id, None, master_key: did not find torn id in yata db sendFrom = f'Sent from {ctx.guild}' # in this case it's not possible to link discordID with torn player # -> backup is to have the id as an argument # note: if status == -3 it converts master_id to actual tornId if status in [-1, -2, -3]: if len(args) and args[0].isdigit(): sendFrom += f' on behalf of {ctx.author.display_name}' tornId = int(args[0]) name = "Player" else: msg = await self.bot.send_error_message( ctx.channel, "Impossible to send revive call because you're not verified on the official Torn discord server.\nYou can use `!revive <tornId>`." ) await asyncio.sleep(30) try: await msg.delete() except BaseException: pass return else: if len(args) and args[0].isdigit(): sendFrom += f' on behalf of {ctx.author.display_name}' tornId = int(args[0]) else: tornId = id if key is not None: # api call to get potential status and faction response, e = await self.bot.api_call("user", tornId, ["profile", "timestamp"], key) if e and "error" in response: if status in [0]: errors.append( f'Problem using {name} [{id}]\'s key: *{response["error"]["error"]}*' ) elif status in [-3, -4]: errors.append( f'Problem using server admin key: *{response["error"]["error"]}*' ) else: errors.append( f'Problem with API key (status = {status}): *{response["error"]["error"]}*' ) errors.append( "I cannot specify faction or hospitalization time") else: return # create call message name = response.get("name", "Player") url = f'https://www.torn.com/profiles.php?XID={tornId}' lst = [] if response.get('faction', False) and response["faction"]["faction_id"]: f = response["faction"] lst.append( f'[{name} [{tornId}]](https://www.torn.com/profiles.php?XID={tornId}) from [{html.unescape(f["faction_name"])} [{f["faction_id"]}]](https://www.torn.com/factions.php?&step=profile&ID={f["faction_id"]}) needs a revive.' ) else: lst.append( f'[{name} [{tornId}]](https://www.torn.com/profiles.php?XID={tornId}) needs a revive.' ) if free: lst.append("**This is a call for a free revive** :kissing_heart:") # add status if response.get('status', False) and response["status"]["state"] == "Hospital": lst.append( f'{response["status"]["description"]} ({cleanhtml(response["status"]["details"])}).' ) eb = Embed(description='\n'.join(lst), color=my_blue) eb.set_author( name= f'{"Freevive" if free else "Revive"} call from {ctx.author.display_name}', icon_url=ctx.author.avatar_url) eb.timestamp = now() # list of messages to delete them after delete = config.get("other", {}).get("delete", False) msgList = [[ctx.message, ctx.channel, delete]] ts_init = ts_now() # send message to current channel if len(errors): msg = "\n".join(errors) m = await self.bot.send_error_message(ctx.channel, msg) msgList.append([m, ctx.channel, delete]) msg = "\n".join(lst) role = self.bot.get_module_role(ctx.guild.roles, config.get("roles_alerts", {})) mention = '' if role is None else f'{role.mention} ' alert_channel = self.bot.get_module_channel( ctx.guild.channels, config.get("channels_alerts", {})) if alert_channel is None: m = await ctx.send(f'{mention}', embed=eb) else: m = await alert_channel.send(f'{mention}', embed=eb) msgList.append([m, ctx.channel, delete]) # loop over all server to send the calls to_delete = [] sending_ids = config.get("sending", {}) for server_id, server_name in sending_ids.items(): logging.debug( f'[revive/revive] {ctx.guild} -> {server_name} [{server_id}]') eb_remote = eb try: # get remote server coonfig remote_guild = get(self.bot.guilds, id=int(server_id)) if remote_guild is None or isinstance(remote_guild, bool): logging.debug( f'[revive/revive] Delete unknown server: {ctx.guild} -> {server_name} [{server_id}]' ) to_delete.append(server_id) continue logging.debug( f'[revive/revive] Sending call: {ctx.guild} -> {remote_guild}' ) remote_config = self.bot.get_guild_configuration_by_module( remote_guild, "revive") if not remote_config: to_delete.append(server_id) # remote server disabled revives -> remove from origin server eb_bl = Embed( title="Revive call disabled", description= f'Server {remote_guild.name} disabled their revive option.', color=my_red) m = await ctx.send(embed=eb_bl) msgList.append([m, ctx.channel, delete]) elif str(ctx.guild.id) in remote_config.get("blacklist", {}): eb_bl = Embed( title="Revive call blacklisted", description= f'Server {remote_guild.name} has blacklisted you.', color=my_red) m = await ctx.send(embed=eb_bl) msgList.append([m, ctx.channel, delete]) else: # if freevive check if server accept freevives if free and not remote_config.get("other", {}).get( "freevive", False): logging.debug( f'[revive/revive] not accepting freevives: {ctx.guild} -> {remote_guild}' ) continue # get guild, role, channel and delete option remote_role = self.bot.get_module_role( remote_guild.roles, remote_config.get("roles_alerts", {})) remote_channel = self.bot.get_module_channel( remote_guild.channels, remote_config.get("channels_alerts", {})) remote_delete = remote_config.get("other", {}).get("delete", False) mention = '' if remote_role is None else f'{remote_role.mention} ' delay = f'(delay: {ts_now() - ts_init}s)' eb_remote.set_footer(text=f'{sendFrom} {delay}.') if remote_channel is not None: m = await remote_channel.send(mention, embed=eb_remote) msgList.append([m, remote_channel, remote_delete]) else: await self.bot.send_log( f'Error sending revive call to server {remote_guild}: revive channel not found', guild_id=ctx.guild.id) except BaseException as e: await self.bot.send_log( f'Error sending revive call to server {remote_guild}: {e}', guild_id=ctx.guild.id) await self.bot.send_log_main(e, full=True) if len(to_delete): for server_id in to_delete: del sending_ids[server_id] self.bot.configurations[ ctx.guild.id]["revive"]["sending"] = sending_ids await self.bot.set_configuration( ctx.guild.id, ctx.guild.name, self.bot.configurations[ctx.guild.id]) logging.debug(f"[revive/revive] {ctx.guild} push new sending list") # delete messages # wait for 5 minutes await asyncio.sleep(5 * 60) for [msg, cha] in [(m, c) for m, c, d in msgList if d]: try: await msg.delete() except BaseException as e: pass
async def roleinfo(self, ctx: Context, role): ''' Get information about a role! ''' try: role = int(role) except Exception as e: pass if type(role) == int: role = get(ctx.guild.roles, id=int(role)) if not role: await ctx.send(":x: Couldn't find a role with that ID!") return elif type(role) == str: for r in ctx.guild.roles: if role.lower() in r.name.lower(): role = r else: await ctx.send(":x: Couldn't find a role with that name!") return embed = discord.Embed( title="Role Info", color=discord.Color.blurple() ) embed.add_field( name="Name", value=f"`{role.name}`", inline=True ) embed.add_field( name="Role Color", value=f"`{role.color}`", inline=True ) embed.add_field( name="Created at", value=f"`{datetime.strftime(role.created_at, '%d-%m-%Y')}` @ `{datetime.strftime(role.created_at, '%H:%M:%Y')}`" ) embed.add_field( name="Members", value=f"`{len(role.members)}`" ) attrs = inspect.getmembers(role.permissions, lambda a:not(inspect.isroutine(a))) attrs = [a for a in attrs if not(a[0].startswith('__') and a[0].endswith('__'))] del attrs[0] del attrs[0] perms = {} for a in attrs: perms[a[0]] = a[1] final_perms = "" if perms['administrator'] is True: final_perms += "`Administrator`" embed.add_field( name="Key Permissions", value=final_perms ) else: for perm, value in perms.items(): if value is True: final_perms += f"`{perm.replace('_', ' ').title()}` " embed.add_field( name="Key Permissions", value=final_perms ) await ctx.send(embed=embed)
async def antiraid(ctx): try: author = ctx.message.author message = ctx.message await message.delete() guild = ctx.guild staffrole = get(guild.roles, id=StaffRoleID) if staffrole in author.roles: global antiraidv if antiraidv == False: antiraidv = True await ctx.channel.edit(slowmode_delay=300) embed = discord.Embed( title=f'Anti-Raid Mode Enabled', description= f'Anti-Raid has been enabled, no new members will be able to join, this channel has been set to a 5 minute cooldown.', color=embedcolor) embed.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: message1 = await ctx.send(embed=embed) except discord.HTTPException: message1 = await ctx.send( f"Anti-Raid Mode Enabled\nAnti-Raid has been enabled, no new members will be able to join, this channel has been set to a 5 minute cooldown." ) syslogc = bot.get_channel(SystemLogsChannelID) embed2 = discord.Embed( title='Anti-Raid Mode Enabled', description= f'{author.mention} has enabled anti-raid mode for this server.', color=embedcolor) embed2.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed2.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed2.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: await syslogc.send(embed=embed2) except discord.HTTPException: await syslogc.send( f"Anti-Raid Mode Enabled\n{author.mention} has enabled anti-raid mode for this server." ) now = (datetime.now(tz=timezone.utc)) for member in guild.members: current = (time.mktime(now.timetuple())) memberjoin = member.joined_at joinsec = (time.mktime(memberjoin.timetuple())) total = (current - joinsec) if (total <= GracePeriodForKicks): embed2 = discord.Embed( title=f'''You have been kicked from {guild.name}''', description= f"Hi there {member.mention}, you have been kicked from {guild.name}.", color=embedcolor) embed2.set_author(name=f'{member}', icon_url=member.avatar_url) embed2.add_field( name="**__Reason:__**", value= "Anti-Raid mode was enabled, all recently joined members are kicked!! Please try joining back later.", inline=True) embed2.add_field(name='**__Moderator:__**', value='Auto-Mod', inline=True) if IncludeInviteLink == True: embed2.add_field( name='**__Discord Invite Link:__**', value=f'{DiscordServerInviteLink}', inline=True) else: pass if customfooter == True: embed2.set_footer( text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed2.set_footer( text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: try: await member.send(embed=embed2) except discord.HTTPException: await member.send( f"You have been kicked from {guild.name} for **Anti-Raid mode was enabled, all recently joined members are kicked!! Please try joining back later.**" ) except Exception: pass await member.kick( reason= f'Anti-Raid mode was enabled, all recently joined members are kicked!! Please try joining back later.' ) user = bot.get_user(member.id) syslogc = bot.get_channel(SystemLogsChannelID) embed3 = discord.Embed(color=embedcolor) embed3.set_author(name=f'[AUTO-KICK] {user}', icon_url=user.avatar_url) embed3.add_field(name='**__Mention/ID:__**', value=f'{user.mention}\n{user.id}', inline=True) embed3.add_field( name="**__Reason:__**", value= "Anti-Raid mode was enabled, all recently joined members are kicked!! Please try joining back later.", inline=True) embed3.add_field(name='**__Moderator:__**', value='Auto-Mod', inline=True) if customfooter == True: embed3.set_footer( text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed3.set_footer( text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: await syslogc.send(embed=embed3) except discord.HTTPException: await syslogc.send( f"[AUTO-KICK][{user.mention} - {user.id}]\n**__Reason:__** Anti-Raid mode was enabled, all recently joined members are kicked!! Please try joining back later.\n**__Moderator:__** Auto-Mod" ) else: pass await asyncio.sleep(30) await message1.delete() elif antiraidv == True: await ctx.channel.edit(slowmode_delay=300) embed = discord.Embed( title=f'Anti-Raid Mode', description= f'Anti-Raid has already been enabled! No new members will be able to join, this channel has been set to a 5 minute cooldown.', color=embedcolor) embed.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: message1 = await ctx.send(embed=embed) except discord.HTTPException: message1 = await ctx.send( f"Anti-Raid Mode\nAnti-Raid has already been enabled! No new members will be able to join, this channel has been set to a 5 minute cooldown." ) await asyncio.sleep(30) await message1.delete() else: message5 = await ctx.send(f'{author.mention}') await message5.delete() embed5 = discord.Embed( description= f'''{author.mention}, you can't use that command!''', color=embedcolor) embed5.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed5.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed5.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: message6 = await ctx.send(embed=embed5) except discord.HTTPException: message6 = await ctx.send( f'''{author.mention}, **you can't use that command!**''') await asyncio.sleep(20) await message6.delete() except Exception as e: developer = bot.get_user(developerid) text = str('''Error on line {}'''.format(sys.exc_info()[-1].tb_lineno)) embed = discord.Embed(title='commands.antiraid function fail', description=f'{text}, {str(e)}', color=embedcolor) try: await developer.send(embed=embed) except discord.HTTPException: await developer.send("commands.antiraid function fail" + str(e)) print('[ERROR][Line {}]:'.format(sys.exc_info()[-1].tb_lineno) + f'{str(e)}') print("----------------------------------------") await asyncio.sleep(10)
async def buy(self, ctx: commands.Context, *, item: str = ""): """Buy an item from the cookie store.""" enabled = await self.config.guild(ctx.guild).enabled() if not enabled: return await ctx.send("Uh oh, store is disabled.") cookies = int(await self.bot.get_cog("Cookies").config.member(ctx.author ).cookies()) items = await self.config.guild(ctx.guild).items.get_raw() roles = await self.config.guild(ctx.guild).roles.get_raw() games = await self.config.guild(ctx.guild).games.get_raw() if not item: page_list = await self._show_store(ctx) if len(page_list) > 1: return await menu(ctx, page_list, DEFAULT_CONTROLS) return await ctx.send(embed=page_list[0]) item = item.strip("@") inventory = await self.config.member(ctx.author).inventory.get_raw() if item in inventory: return await ctx.send("You already own this item.") if item in roles: role_obj = get(ctx.guild.roles, name=item) if role_obj: role = await self.config.guild(ctx.guild).roles.get_raw(item) price = int(role.get("price")) quantity = int(role.get("quantity")) if quantity == 0: return await ctx.send("Uh oh, this item is out of stock.") if price <= cookies: pass else: return await ctx.send("You don't have enough cookies!") await ctx.author.add_roles(role_obj) cookies -= price quantity -= 1 await self.bot.get_cog("Cookies").config.member( ctx.author).cookies.set(cookies) await self.config.member(ctx.author).inventory.set_raw( item, value={ "price": price, "is_role": True, "is_game": False, "redeemable": False, "redeemed": True, }, ) await self.config.guild(ctx.guild ).roles.set_raw(item, "quantity", value=quantity) await ctx.send(f"You have bought {item}.") else: await ctx.send("Uh oh, can't find the role.") elif item in items: item_info = await self.config.guild(ctx.guild).items.get_raw(item) price = int(item_info.get("price")) quantity = int(item_info.get("quantity")) redeemable = item_info.get("redeemable") if not redeemable: redeemable = False if quantity == 0: return await ctx.send("Uh oh, this item is out of stock.") if price <= cookies: pass else: return await ctx.send("You don't have enough cookies!") cookies -= price quantity -= 1 await self.bot.get_cog("Cookies").config.member( ctx.author).cookies.set(cookies) await self.config.guild(ctx.guild).items.set_raw(item, "quantity", value=quantity) if not redeemable: await self.config.member(ctx.author).inventory.set_raw( item, value={ "price": price, "is_role": False, "is_game": False, "redeemable": False, "redeemed": True, }, ) await ctx.send(f"You have bought {item}.") else: await self.config.member(ctx.author).inventory.set_raw( item, value={ "price": price, "is_role": False, "is_game": False, "redeemable": True, "redeemed": False, }, ) await ctx.send( f"You have bought {item}. You may now redeem it with `{ctx.clean_prefix}redeem {item}`" ) elif item in games: game_info = await self.config.guild(ctx.guild).games.get_raw(item) price = int(game_info.get("price")) quantity = int(game_info.get("quantity")) redeemable = game_info.get("redeemable") if not redeemable: redeemable = False if quantity == 0: return await ctx.send("Uh oh, this item is out of stock.") if price <= cookies: pass else: return await ctx.send("You don't have enough cookies!") cookies -= price quantity -= 1 await self.bot.get_cog("Cookies").config.member( ctx.author).cookies.set(cookies) await self.config.guild(ctx.guild).games.set_raw(item, "quantity", value=quantity) if not redeemable: await self.config.member(ctx.author).inventory.set_raw( item, value={ "price": price, "is_role": False, "is_game": True, "redeemable": False, "redeemed": True, }, ) await ctx.send(f"You have bought {item}.") else: await self.config.member(ctx.author).inventory.set_raw( item, value={ "price": price, "is_role": False, "is_game": True, "redeemable": True, "redeemed": False, }, ) await ctx.send( f"You have bought {item}. You may now redeem it with `{ctx.clean_prefix}redeem {item}`" ) else: page_list = await self._show_store(ctx) if len(page_list) > 1: return await menu(ctx, page_list, DEFAULT_CONTROLS) return await ctx.send(embed=page_list[0])
async def ping(ctx): message = ctx.message await message.delete() try: guild = ctx.guild author = ctx.message.author srole = get(guild.roles, id=StaffRoleID) if srole in author.roles: latency = bot.latency * 1000 embed6 = discord.Embed( title='Ping Command!', description=f'Bot Latency ❤️: `{latency:.2f}ms`', color=embedcolor) if customfooter == True: embed6.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed6.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') embed6.set_author(name=f'{author}', icon_url=author.avatar_url) try: message8 = await ctx.send(embed=embed6) except discord.HTTPException: message8 = await ctx.send(f'Bot Latency: {latency:.2f}ms ❤️') await asyncio.sleep(15) await message8.delete() else: message5 = await ctx.send(f'{author.mention}') await message5.delete() embed5 = discord.Embed( description= f'''{author.mention}, you can't use that command!''', color=embedcolor) embed5.set_author(name=f'{author}', icon_url=f'{author.avatar_url}') if customfooter == True: embed5.set_footer(text=f'{customfootvalue}', icon_url=f'{bot.user.avatar_url}') else: embed5.set_footer(text=f'{bot.user.name} | {bot.user.id}', icon_url=f'{bot.user.avatar_url}') try: message6 = await ctx.send(embed=embed5) except discord.HTTPException: message6 = await ctx.send( f'''{author.mention}, **you can't use that command!**''') await asyncio.sleep(20) await message6.delete() except Exception as e: developer = bot.get_user(developerid) text = str('''Error on line {}'''.format(sys.exc_info()[-1].tb_lineno)) embed = discord.Embed(title='commands.ping function fail', description=f'{text}, {str(e)}', color=embedcolor) try: await developer.send(embed=embed) except discord.HTTPException: await developer.send("commands.ping function fail" + str(e)) print('[ERROR][Line {}]:'.format(sys.exc_info()[-1].tb_lineno) + f'{str(e)}') print("----------------------------------------")
async def play(self, ctx, *, music): if str(ctx.channel) != 'music': return channel = ctx.message.author.voice.channel voice = get(self.bot.voice_clients, guild=ctx.guild) self.ctx = ctx global video_choice if voice is None: await channel.connect() elif voice and voice.is_connected(): await voice.move_to(channel) voice = get(self.bot.voice_clients, guild=ctx.guild) option = None try: if music[-1].isdigit() and music[-2] == '=' and music[-3] == ' ': option = int(music[-1]) music = music[:-3] except Exception as e: print(e) if music.isdigit(): if int(music) > len(video_choice): await ctx.send("Wrong option") return else: music = video_choice[int(music) - 1] song_play = True song_there = os.path.isfile("song.mp3") try: if song_there: os.remove("song.mp3") await ctx.send("Preparing song") song_play = False except PermissionError: await ctx.send("Song is playing now. Your song will be in queue") try: if int(music_duration(music)) < 800: if song_play: title = music_title(music) song_queue.append([title, music]) await ctx.send("{} was placed in queue".format(title)) else: title = download(music) await ctx.send("{} is playing now".format(title)) voice.play(discord.FFmpegPCMAudio("song.mp3")) else: await ctx.send("Song too long") except Exception as e: print(e) if option is None: video_choice = {} videos = search(music) embed = discord.Embed(title="Select song", color=0x0ff0ff) for i in range(len(videos)): embed.add_field(name="** **", value="**{}**. {} | {}".format( i + 1, videos[i][3], videos[i][5]), inline=False) video_choice[i] = videos[i][2] await ctx.send(embed=embed) else: videos = search(music) for i in range(len(videos)): video_choice[i] = videos[i][2] if option > len(video_choice): await ctx.send("Wrong option") return else: music = video_choice[option - 1] if int(music_duration(music)) < 800: if song_play: title = music_title(music) song_queue.append([title, music]) await ctx.send("{} was placed in queue".format(title)) else: title = download(music) await ctx.send("{} is playing now".format(title)) voice.play(discord.FFmpegPCMAudio("song.mp3")) else: await ctx.send("Song too long") return
async def leave(self, ctx): voice = get( self.client.voice_clients, guild=ctx.guild ) if voice and voice.is_connected(): await voice.disconnect()
async def play(ctx, url: str): def check_queue(): Queue_infile = os.path.isdir("./soqu") if Queue_infile is True: DIR = os.path.abspath(os.path.realpath("soqu")) 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("soqu") + "\\" + 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("./soqu") try: Queue_folder = "./soqu" 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(koneko.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 resume(self, ctx): voice = get(self.client.voice_clients, guild= ctx.guild) if voice and voice.is_paused(): voice.resume()
async def setlock_settings(self, ctx: commands.Context): """ List all channels' settings. """ has_been_set = await self.config.guild(ctx.guild).has_been_set() if not has_been_set: return await ctx.send( f"You have to do `{ctx.clean_prefix}setlock setup` first!") data = await self.config.guild(ctx.guild).all() toggle = data["toggle"] if not toggle: toggle = False if not toggle: return await ctx.send("Lock is disabled.") mod = get(ctx.guild.roles, id=data["moderator"]).name if not mod: mod = None everyone = data["everyone"] special = data["special"] spec = "True" if not special else "False" ro_list = [] try: for role_id in data["roles"]: ro = get(ctx.guild.roles, id=role_id).name ro_list.append(ro) ro_desc = humanize_list(ro_list) except TypeError: ro_desc = "Not specified" except AttributeError: ro_desc = "Something went wrong." if ro_list == []: ro_desc = "Not specified" def_list = [] try: for def_role_id in data["def_roles"]: def_ro = get(ctx.guild.roles, id=def_role_id).name def_list.append(def_ro) def_desc = humanize_list(def_list) except TypeError: def_desc = "Not specified" except AttributeError: def_desc = "Something went wrong." if def_list == []: def_desc = "Not specified" ig_list = [] try: for ignore_id in data["ignore"]: ig = get(ctx.guild.text_channels, id=ignore_id).name ig_list.append(ig) ig_desc = humanize_list(ig_list) except TypeError: ig_desc = "Not specified" except AttributeError: ig_desc = f"Something went wrong. `{ctx.clean_prefix}setlock refresh` might fix it" if ig_list == []: ig_desc = "Not specified" c_list = [] try: config_channels = await self.config.guild(ctx.guild ).channels.get_raw() for c_id in config_channels: c = get(ctx.guild.text_channels, id=int(c_id)).name c_list.append(c) c_desc = humanize_list(c_list) except TypeError: c_desc = "Not specified" except AttributeError: c_desc = f"Something went wrong. `{ctx.clean_prefix}setlock refresh` might fix it" if c_list == []: c_desc = "Not specified" embed = discord.Embed(colour=await ctx.embed_colour(), timestamp=datetime.now()) embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url) embed.title = "**__Advanced Lock settings:__**" embed.add_field(name="Enabled:", value=toggle) embed.add_field(name="Moderator role:", value=mod) embed.add_field(name="Can everyone see all channels?", value=everyone, inline=False) embed.add_field(name="Ignored channels:", value=ig_desc, inline=False) if not everyone: embed.add_field(name="Can all roles see the same channels?", value=spec, inline=False) if not special: embed.add_field(name="What roles can see all channels?", value=ro_desc, inline=False) else: embed.add_field(name="Default permissions:", value=def_desc, inline=False) embed.add_field( name= (f"Channels with special settings (to see the settings, type `{ctx.clean_prefix}setlock channel <channel>`):" ), value=c_desc, inline=False, ) await ctx.send(embed=embed)
async def unlock(self, ctx: commands.Context): """ Unlock the channel for `@everyone`. """ has_been_set = await self.config.guild(ctx.guild).has_been_set() if not has_been_set: return await ctx.send( f"You have to do `{ctx.clean_prefix}setlock setup` first!") async with ctx.typing(): toggle = await self.config.guild(ctx.guild).toggle() if not toggle: return await ctx.send( "Uh oh. Lock isn't enabled in this server. Ask your Admins to enable it." ) everyone = get(ctx.guild.roles, name="@everyone") mods_id = await self.config.guild(ctx.guild).moderator() mods = get(ctx.guild.roles, id=mods_id) which = await self.config.guild(ctx.guild).everyone() special = await self.config.guild(ctx.guild).special() defa = await self.config.guild(ctx.guild).defa() ignore = await self.config.guild(ctx.guild).ignore() if not mods: return await ctx.send( "Uh oh. Looks like your Admins haven't setup this yet.") if ctx.channel.id in ignore: return await ctx.send( "Uh oh. This channel is in the ignored list.") if which: # if everyone can see the channels await ctx.channel.set_permissions(everyone, read_messages=True, send_messages=True) else: if not special: # if False, all special roles can see same channels roles = await self.config.guild(ctx.guild).roles() for role_id in roles: ro = get(ctx.guild.roles, id=role_id) await ctx.channel.set_permissions(ro, read_messages=True, send_messages=True) else: # if True, some roles can see some channels c_ctx = ctx.channel.id c = await self.config.guild(ctx.guild ).channels.get_raw(c_ctx) if not c: if not defa: return await ctx.send( "Uh oh. This channel has no settings. Ask your Admins to add it." ) def_roles = await self.config.guild(ctx.guild ).def_roles() for def_role_id in def_roles: def_ro = get(ctx.guild.roles, id=def_role_id) await ctx.channel.set_permissions( def_ro, read_messages=True, send_messages=True) else: for role_id in c["roles"]: ro = get(ctx.guild.roles, id=role_id) await ctx.channel.set_permissions( ro, read_messages=True, send_messages=True) await ctx.channel.set_permissions(mods, read_messages=True, send_messages=True) await ctx.send(":unlock: Channel unlocked.")
async def deny(self, ctx: commands.Context, target: discord.Member): """Deny a staff applicant. <target> can be a mention or an ID""" if not await self.config.guild(ctx.guild).channel_id(): return await ctx.send( "Uh oh, the configuration is not correct. Ask the Admins to set it." ) try: accepter = ctx.guild.get_role( await self.config.guild(ctx.guild).accepter_id() ) except TypeError: accepter = None if ( not accepter and not ctx.author.guild_permissions.administrator or (accepter and accepter not in ctx.author.roles) ): return await ctx.send("Uh oh, you cannot use this command.") applicant = None if await self.config.guild(ctx.guild).applicant_id(): try: applicant = ctx.guild.get_role( await self.config.guild(ctx.guild).applicant_id() ) except TypeError: applicant = None if not applicant: applicant = get(ctx.guild.roles, name="Staff Applicant") if not applicant: return await ctx.send( "Uh oh, the configuration is not correct. Ask the Admins to set it." ) if applicant not in target.roles: return await ctx.send( f"Uh oh. Looks like {target.mention} hasn't applied for anything." ) await ctx.send("Would you like to specify a reason? (yes/no)") pred = MessagePredicate.yes_or_no(ctx) try: await self.bot.wait_for("message", timeout=30, check=pred) except asyncio.TimeoutError: return await ctx.send("You took too long. Try again, please.") if pred.result: await ctx.send("Please, specify your reason now.") def check(m): return m.author == ctx.author try: reason = await self.bot.wait_for("message", timeout=120, check=check) except asyncio.TimeoutError: return await ctx.send("You took too long. Try again, please.") await target.send( f"Your application in {ctx.guild.name} has been denied.\n*Reason:* {reason.content}" ) else: await target.send(f"Your application in {ctx.guild.name} has been denied.") if applicant: await target.remove_roles(applicant) await ctx.send(f"Denied {target.mention}'s application.")
async def _unmute(self, ctx, member: discord.Member = None): member = member or ctx.message.author await member.remove_roles(get(ctx.guild.roles, name='뮤트')) await ctx.send(str(member) + "이젠 말 할 수 있을거에요!")
async def lockserver(self, ctx: commands.Context, confirmation: bool = False): """ Lock `@everyone` from sending messages in the entire server.""" has_been_set = await self.config.guild(ctx.guild).has_been_set() if not has_been_set: return await ctx.send( f"You have to do `{ctx.clean_prefix}setlock setup` first!") if not confirmation: return await ctx.send( "This will overwrite every channel's permissions.\n" f"If you're sure, type `{ctx.clean_prefix}lockserver yes` (you can set an alias for this so I don't ask you every time)." ) async with ctx.typing(): toggle = await self.config.guild(ctx.guild).toggle() if not toggle: return await ctx.send( "Uh oh. Lock isn't enabled in this server. Ask your Admins to enable it." ) everyone = get(ctx.guild.roles, name="@everyone") mods_id = await self.config.guild(ctx.guild).moderator() mods = get(ctx.guild.roles, id=mods_id) which = await self.config.guild(ctx.guild).everyone() special = await self.config.guild(ctx.guild).special() defa = await self.config.guild(ctx.guild).defa() ignore = await self.config.guild(ctx.guild).ignore() if not mods: return await ctx.send( "Uh oh. Looks like your Admins haven't setup this yet.") for channel in ctx.guild.text_channels: if channel.id in ignore: continue if which: # if everyone can see the channels await channel.set_permissions(everyone, read_messages=True, send_messages=False) else: await channel.set_permissions(everyone, read_messages=False, send_messages=False) if special: # if True, some roles can see some channels if not defa: config_channels = await self.config.guild( ctx.guild).channels.get_raw() check_channels = [ int(c_id) for c_id in config_channels ] for ig_id in ignore: check_channels.append(ig_id) if any(channel.id not in check_channels for channel in ctx.guild.text_channels): return await ctx.send( "Uh oh. I cannot let you do this. Ask your Admins to add remaining channels." ) c = await self.config.guild( ctx.guild).channels.get_raw(channel.id) if c: for role_id in c["roles"]: ro = get(ctx.guild.roles, id=role_id) await channel.set_permissions( ro, read_messages=True, send_messages=False) else: def_roles = await self.config.guild(ctx.guild ).def_roles() for def_role_id in def_roles: def_ro = get(ctx.guild.roles, id=def_role_id) await channel.set_permissions( def_ro, read_messages=True, send_messages=False) else: # if False, all special roles can see same channels roles = await self.config.guild(ctx.guild).roles() for role_id in roles: ro = get(ctx.guild.roles, id=role_id) await channel.set_permissions(ro, read_messages=True, send_messages=False) await channel.set_permissions(mods, read_messages=True, send_messages=True) await ctx.send(":lock: Server locked. Only Moderators can type.")
async def _mute(self, ctx, member: discord.Member = None): member = member or ctx.message.author await member.add_roles(get(ctx.guild.roles, name="뮤트")) await ctx.channel.send(str(member) + "님이 뮤트가 되었어요!!!")
async def on_member_join(self, member): server_id = member.guild.id if server_id == 515156152066244635: print("GermanReich") channel = self.client.get_channel(768940272561946645) await channel.edit( name='📊Member count: {}'.format(channel.guild.member_count)) #channel = client.get_channel(769528310552068106) print(member) embed = discord.Embed( title="RULES!", colour=0xff0000, url="https://daydream404.github.io/MeinBot/", description= "READ THE RULES!\n\n**0000. Respect everyone.\n\n0001. Use channels properly.\n\n0010. Speak only English.\n\n0011. Do not spam.\n\n0100. Do not advertise.\n\n0101. Do not post anything NSFW or you'll get banned.\n\n0110. Do not swear or use abusive language.\n\n0111. Do not start conversation with controversial topics.\n\n1000. Do not mention @everyone.\n\n1001. Do not share any files for download.**\n\nAfter reading the rules confirm accepting them by reacting with :thumbsup:" ) #await channel.send(embed=embed) await member.send(embed=embed) def check(reaction, user): return user == member and str(reaction.emoji) in ['👍'] reaction, user = await self.client.wait_for("reaction_add", check=check) role = get(member.guild.roles, name="Landwirt") await member.add_roles(role) meinbot_guild = self.client.get_guild(515156152066244635) #meinbot_guild is servername #server_id is id for channel in meinbot_guild.text_channels: if channel.permissions_for(meinbot_guild.me).send_messages: embed = discord.Embed(colour=0x520081, description=f"Welcome to the party!") embed.set_thumbnail(url=f"{member.avatar_url}") embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}") embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}") embed.add_field(name=f"Your role: ", value=role) embed.timestamp = datetime.datetime.now() await channel.send(embed=embed) break elif server_id == 751897980432547941: print("MeinbotServer") channel = self.client.get_channel(768941337927352342) await channel.edit( name='📊Member count: {}'.format(channel.guild.member_count)) role = get(member.guild.roles, name="noob") await member.add_roles(role) meinbot_guild = self.client.get_guild(751897980432547941) for channel in meinbot_guild.text_channels: if channel.permissions_for(meinbot_guild.me).send_messages: embed = discord.Embed(colour=0x520081, description=f"Welcome to the party!") embed.set_thumbnail(url=f"{member.avatar_url}") embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar_url}") embed.set_footer(text=f"{member.guild}", icon_url=f"{member.guild.icon_url}") embed.add_field(name=f"Your role: ", value=role) embed.timestamp = datetime.datetime.now() await channel.send(embed=embed) break else: try: role = get(member.guild.roles, name=ROLE) await member.add_roles(role) except Exception as e: await channel.send( "Well you f****d up something didn\'t you? Try Help on my [website](https://www.meinbot.com)" )