def check( check_message ): # Modify this function to provide more than just bot messages. if prune_type == None or prune_type == 'all': if manage_messages: return True else: if prune_type == 'all': return Response(permissions_error=True) else: if not self.bot.user.bot: if check_message.author == self.bot.user: return True else: return False else: return Response(permissions_error=True) elif prune_type == 'commands': return is_bot_command(check_message) elif user_mentions: if check_message.author in user_mentions: return True else: return False else: return False
async def cmd_listunits(self, unit_type=None): """ Usage: {command_prefix}listunits [unit_type] List Units for {command_prefix}convert """ if not unit_type: type_list = [] for key in self.unit_dict: if self.unit_dict[key][1] not in type_list: type_list.append(self.unit_dict[key][1]) ret = 'The following unit types are supported by the converter:' for unit in type_list: ret = ret + '\n-' + unit ret = ret + '\n\nUse `' + self.bot.config.prefix + 'listunits [unit_type]` to list the supported units of each type' return Response(ret, reply=False, delete_after=45) else: unit_list = [] for key in self.unit_dict: if self.unit_dict[key][1] == unit_type: unit_list.append(key) if len(unit_list) < 1: return Response('The unit type `' + unit_type + '` is not supported.', reply=False, delete_after=45) ret = 'The following units of type `' + unit_type + '` are supported by the converter:' for unit in unit_list: ret = ret + '\n-' + unit return Response(ret, reply=False, delete_after=45)
async def cmd_sudo(self, message, channel, server, auth_perms, user_mentions, leftover_args): """ Usage: {command_prefix}sudo (user_mention) (command_sequence_to_be_ran) Run a command as another user. Requires Owner Permissions (100) help_exclude """ if auth_perms >= 35: if user_mentions: sudo_user = user_mentions[0] sudo_perms = await self.bot.permissions.check_permissions( sudo_user, channel, server) if auth_perms > sudo_perms or auth_perms >= 100: if leftover_args[0] == sudo_user.mention: sudo_string = self.bot.config.prefix + 'sudo ' sudo_string += sudo_user.mention sudo_length = len(sudo_string) sudo_message = copy.copy(message) sudo_message.content = message.content[ sudo_length:].strip() sudo_message.author = sudo_user del sudo_message.mentions[0] del sudo_message.raw_mentions[0] await self.bot.on_message(sudo_message) return else: return Response(permissions_error=True) else: return Response(send_help=True) else: return Response(permissions_error=True)
async def cmd_8ball(self, leftover_args): """ Usage: {command_prefix}8ball (question) Ask the Magic 8-Ball a question """ if leftover_args: response = random.choice(self.ball_responses) return Response(response, reply=True, delete_after=60) else: return Response(send_help=True)
async def cmd_id(self, author, user_mentions): """ Usage: {command_prefix}id Get's a User's ID """ if not user_mentions: return Response('your ID is `{}`'.format(author.id), reply=True, delete_after=30) else: user = user_mentions[0] return Response("<@{0}>'s ID is `{0}`".format(user.id), reply=False, delete_after=30)
async def cmd_ping(self): """ Usage: {command_prefix}ping Test the operation of the bot and plugin systems. """ return Response('pong!', reply=True, delete_after=10)
async def cmd_perms(self, author, channel, server, user_mentions): """ Usage: {command_prefix}perms (@Mentioned_User) [@AnotherMentionedUser] [@YetAnotherUser] ... Get the permissions of a mentioned user or users. help_exclude """ if user_mentions: for user in user_mentions: perms = await self.bot.permissions.check_permissions( user, channel, server) if perms == 100: perms_message = '{} is my Owner'.format(user.mention) elif perms == 50: perms_message = '{} is a Server Administrator'.format( user.mention) elif perms == 45: perms_message = '{} holds this server\'s Administrator Role'.format( user.mention) elif perms == 30 and user.id == self.bot.user.id: perms_message = 'I am {}!'.format(self.bot.config.bot_name) elif perms == 35: perms_message = '{} holds this server\'s Moderator Role'.format( user.mention) elif perms == 25: perms_message = '{} holds this server\'s Helper Role'.format( user.mention) elif perms == 10: perms_message = '{} is a Standard User on this Server'.format( user.mention) elif perms == 9: perms_message = '{} is a Standard User on this Server. However, Server Specific Permissions have not yet been set up on this Server'.format( user.mention) elif perms == 5: perms_message = '{} is a Standard User in this Direct Message'.format( user.mention) elif perms == 0: perms_message = '{} is a Blacklisted User on this Server'.format( user.mention) else: perms_message = '{} has permissions level {}'.format( user.mention, perms) perms_message = author.mention + ', ' + perms_message await self.bot.safe_send_message( channel, perms_message, expire_in=30 if self.bot.config.delete_messages else 0, also_delete=message if self.bot.config.delete_invoking else None) else: return Response(send_help=True)
async def cmd_diceroll(self): """ Usage: {command_prefix}diceroll (question) Roll a Dice! """ coin = random.choice([1, 2, 3, 4, 5, 6]) response = 'Dice rolled a {}.'.format(coin) return Response(response, reply=True, delete_after=60)
async def cmd_examplecommand(self, desired_arguments_passed_here): """ Usage: {command_prefix}command_key (required arguments have parenthesis) [optional_arguments have brackets] A string about how the plugin works command_modifier_strings help_exclude _is_a_string_and_excludes_this_commmand_from_help remove_last_two_lines_if_no_modifiers """ #command runs here return Response('DEFAULT_EXAMPLE_MESSAGE. PROGRAMMER FORGOT TO CHANGE DEFAULTS', reply=True, delete_after=45)
async def cmd_toggle(self, auth_perms, server, key): """ Usage: {command_prefix}toggle Test the operation of the bot and plugin systems. help_exclude """ if auth_perms >= 45: response = await self.bot.toggle_key(server, key.lower()) if response[0] == 'SUCCESS': return Response( 'Toggled Server-Key `{}` to state: `{}`'.format( key, response[1]), reply=True, delete_after=30) else: return Response('No Server-Key `{}` Available'.format(key), reply=True, delete_after=15) else: return Response(permissions_error=True)
async def cmd_coinflip(self): """ Usage: {command_prefix}8ball Flip a Coin! """ flip = bool(random.getrandbits(1)) if flip: response = 'Coin has flipped Heads.' else: response = 'Coin has flipped Tails.' return Response(response, reply=True, delete_after=60)
async def cmd_setperms(self, message, channel, server, author, auth_perms, raw_role_mentions): """ Usage: {command_prefix}setperms (Administrator_Rank_Mention) (Moderator_Rank_Mention) (Helper_Rank_Mention) (Blacklisted_Rank_Mention) Sets the Permissions Ranks for the Server. Author must have the Manage Server Permission. help_exclude """ if channel.permissions_for(author).manage_server or auth_perms >= 100: if len(raw_role_mentions) == 4: admin_role_id = raw_role_mentions[0] mod_role_id = raw_role_mentions[1] helper_role_id = raw_role_mentions[2] black_role_id = raw_role_mentions[3] self.bot.permissions.set_server_permissions( server, admin_role_id, mod_role_id, helper_role_id, black_role_id) return Response( "Server Permissions Ranks have been updated succesfully! :+1:\n\n_Administrator Role_: <@&{}>\n_Moderator Role_: <@&{}>\n_Helper Role_: <@&{}>\n_Blacklisted Role_: <@&{}>" .format(admin_role_id, mod_role_id, helper_role_id, black_role_id)) else: return Response( send_help=True, help_message='Invalid Number of Ranks Mentioned' if role_mentions else None) else: return Response( "You must have the Manage Server Permission in order to set Server Permissions", reply=True, delete_after=45)
async def cmd_invite(self, message, auth_perms, server_link=None): """ Usage: {command_prefix}invite [server_link if not bot] Invite the bot or get it's Invite Link! """ if self.bot.config.allow_invites or auth_perms >= 100: if self.bot.user.bot: app_info = await self.bot.application_info() join_url = discord.utils.oauth_url( app_info.id) + '&permissions=66321471' return Response('Invite {} to your server! See: {}'.format( self.bot.config.bot_name, join_url), reply=True, delete_after=30) try: if server_link: await self.bot.accept_invite(server_link) return Response(':thumbsup: Joined Server!', reply=True, delete_after=30) except: raise exceptions.CommandError( 'Invalid URL provided:\n{}\n'.format(server_link), expire_in=30) else: return Response( '{} is not currently accepting server invitations!'.format( self.bot.config.bot_name), reply=True, delete_after=30)
async def cmd_examplecommand( self, desired_arguments_passed_here ): #args can be any args from the list at the bottom of the page, which will return the item as shown below. Any args not in this list will read from words sent after the messages, split by spaces, from left to right. These args can be set as optional by asigning them a default value if not present. """ Usage: {command_prefix}command_key (required arguments have parenthesis) [optional_arguments have brackets] A string about how the plugin works help_exclude modifier_strings_modify_functionality help_exclude_excludes_command_from_help_list """ #This docstring must be here for the help command to work. Command Modifier Strings modify the command's effect in the rest of the bot. Bot will not error out if they do not exist. #do stuff here return Response( 'message string or variable to send to the channel where the message was sent', reply=True, delete_after=15 ) #reply = True if you want the message to reply to the original message author, delete_after is the time until bot's message will be auto-deleted, 0 means never delete (although don't do this unless necesary as it is a config feature to delete messages or not) OPTIONAL ARGUMENTS: (1) return Response(send_help=True) will send the command's help message, and can be used in combination with help_message='Error Message to Be included' to include an Error Message in with the Help Response. (2) return Response(permissions_error=True) returns the default Permissions Error message to the channel.
async def cmd_afk(self, message, author): """ Usage: {command_prefix}afk (message) Set your global state as AFK with a message! """ if author == self.bot.user: return afk_message = message.content[len(self.bot.config.prefix + 'afk '):].strip() afk_message = afk_message.replace('\n', ' ') user_return = self.utilities_db.table('afk').select("AFK_STATE").where( "USER_ID").equals(author.id).execute() afk_state = None for user in user_return: afk_state = user[0] if afk_state: self.utilities_db.table('afk').update("AFK_STATE").setTo( 'True').where("USER_ID").equals(author.id).execute() self.utilities_db.table('afk').update("AFK_MESSAGE").setTo( afk_message).where("USER_ID").equals(author.id).execute() else: self.utilities_db.table('afk').insert(author.id, 'True', afk_message).into( "USER_ID", "AFK_STATE", "AFK_MESSAGE") return Response('🔹 🔶 🔹 {} is AFK: {} 🔹 🔶 🔹'.format( self.bot.get_display_name(author), afk_message), reply=False, delete_after=45)
async def cmd_custom(self, message, auth_perms, leftover_args): """ Usage: {command_prefix}custom [modifier] List Custom Commands. Moderators: Modify Server's Custom Commands """ if message.server: server = message.server else: return Response( 'Custom Commands are not enabled in Direct Messages', reply=False, delete_after=120) if leftover_args: modifier = leftover_args[0] del leftover_args[0] else: modifier = None if not modifier: if not self.commands_db.table('server_{}'.format( server.id)).tableExists(): return Response( '{} does not have Custom Commands enabled'.format( server.name), reply=False, delete_after=30) else: commands_response = '**{}\'s Custom Commands:**\n```'.format( server.name) commands_return = self.commands_db.table('server_{}'.format( server.id)).select("COMMAND_KEY").execute() for custom_command in commands_return: commands_response += ' • ' + self.bot.config.prefix + custom_command[ 0] + '\n' commands_response += '```' return Response(commands_response, reply=False, delete_after=60) elif modifier == 'add' or modifier == 'create': if auth_perms >= 35: possible_command_name = leftover_args[0].strip() raw_commands_return = self.bot.plugin_db.table( 'commands').select("PLUGIN_NAME").where( "COMMAND_KEY").equals( possible_command_name.lower()).execute() does_exist = False for command in raw_commands_return: does_exist = True if does_exist: return Response( 'Bot Command `{prefix}{custom_command}` can not be overwriten by a Custom Command!' .format(prefix=self.bot.config.prefix, custom_command=possible_command_name.lower()), reply=True, delete_after=15) possible_command_response = message.content[ len(self.bot.config.prefix + 'custom {} {} '.format(modifier, leftover_args[0]) ):].strip() if not self.commands_db.table('server_{}'.format( server.id)).tableExists(): initiation_glob = dbt_custom_commands_server_instance() self.commands_db.table('server_{}'.format( server.id)).init(initiation_glob) raw_custom_commands_return = self.commands_db.table( 'server_{}'.format(server.id)).select("RESPONSE").where( "COMMAND_KEY").equals( possible_command_name.lower()).execute() custom_does_exist = False for custom_command in raw_custom_commands_return: custom_does_exist = True if custom_does_exist: return Response( 'Custom Command `{prefix}{custom_command}` already exists! Use `{prefix}custom edit {custom_command} (New_Response)` to modify it.' .format(prefix=self.bot.config.prefix, custom_command=possible_command_name), reply=True, delete_after=30) self.commands_db.table('server_{}'.format(server.id)).insert( possible_command_name.lower(), possible_command_response).into("COMMAND_KEY", "RESPONSE") return Response( 'Custom Command `{prefix}{custom_command}` Successfully Created!' .format(prefix=self.bot.config.prefix, custom_command=possible_command_name.lower()), reply=True, delete_after=30) else: return Response(permissions_error=True) elif modifier == 'edit' or modifier == 'update': if auth_perms >= 35: possible_command_name = leftover_args[0].strip() possible_command_response = message.content[ len(self.bot.config.prefix + 'custom {} {} '.format(modifier, leftover_args[0]) ):].strip() if not self.commands_db.table('server_{}'.format( server.id)).tableExists(): return Response( '{} does not have Custom Commands enabled. Use `{}custom add {} (content)` to create this command' .format(server.name, self.bot.config.prefix, possible_command_name.lower()), reply=True, delete_after=30) raw_custom_commands_return = self.commands_db.table( 'server_{}'.format(server.id)).select("RESPONSE").where( "COMMAND_KEY").equals( possible_command_name.lower()).execute() custom_does_exist = False for custom_command in raw_custom_commands_return: custom_does_exist = True if custom_does_exist: if possible_command_response == '': return Response( 'Custom Command `{prefix}{command}` can not have an empty response. Use `{prefix}custom edit {command} (content)` to edit this command' .format(prefix=self.bot.config.prefix, command=possible_command_name.lower()), reply=True, delete_after=30) self.commands_db.table('server_{}'.format( server.id)).update("RESPONSE").setTo( possible_command_response).where( "COMMAND_KEY").equals( possible_command_name.lower()).execute() return Response( 'Response for `{prefix}{command}` updated!'.format( prefix=self.bot.config.prefix, command=possible_command_name.lower()), reply=True, delete_after=30) else: return Response( 'Custom Command `{prefix}{command}` does not exist. Use `{prefix}custom add {command} (content)` to create this command' .format(prefix=self.bot.config.prefix, command=possible_command_name.lower()), reply=True, delete_after=30) else: return Response(permissions_error=True) elif modifier == 'remove' or modifier == 'delete': if auth_perms >= 35: possible_command_name = leftover_args[0].strip() if not self.commands_db.table('server_{}'.format( server.id)).tableExists(): return Response( '{} does not have Custom Commands enabled.'.format( server.name), reply=True, delete_after=30) raw_custom_commands_return = self.commands_db.table( 'server_{}'.format(server.id)).select("RESPONSE").where( "COMMAND_KEY").equals(possible_command_name).execute() custom_does_exist = False for custom_command in raw_custom_commands_return: custom_does_exist = True if not custom_does_exist: return Response( 'Custom Command `{prefix}{command}` does not exist.'. format(prefix=self.bot.config.prefix, command=possible_command_name), reply=True, delete_after=30) all_custom_commands_return = self.commands_db.table( 'server_{}'.format( server.id)).select("COMMAND_KEY").execute() custom_commands_list = [] for custom_command_all in all_custom_commands_return: custom_commands_list += [custom_command[0]] if len(custom_commands_list) == 1: self.commands_db_cursor.execute( 'DROP TABLE IF EXISTS server_{}'.format(server.id)) self.commands_db_connection.commit() return Response( 'Custom Command `{prefix}{command}` has been removed and Custom Commands have been disabled.' .format(prefix=self.bot.config.prefix, command=possible_command_name), reply=True, delete_after=30) else: self.commands_db.table('server_{}'.format( server.id)).delete().where("COMMAND_KEY").equals( possible_command_name).execute() return Response( 'Custom Command `{prefix}{command}` has been removed.'. format(prefix=self.bot.config.prefix, command=possible_command_name), reply=True, delete_after=30) else: return Response(permissions_error=True) else: return Response( send_help=True, help_message='Unrecognized Modifier \'{}\''.format(modifier))
async def cmd_convert(self, value, from_unit, to_unit): """ Usage: {command_prefix}convert (value) (fromUnit) (toUnit) Convert 'value' from 'fromUnit' to 'toUnit' """ for key in self.unit_dict: try: if self.unit_dict[key][2]: if self.unit_dict[key][2] == from_unit: from_unit = key if self.unit_dict[key][2] == to_unit: to_unit = key if self.unit_dict[key][3]: if self.unit_dict[key][3] == from_unit: from_unit = key if self.unit_dict[key][3] == to_unit: to_unit = key except: pass try: value = float(value) except: return Response('First argument must be numerical.', reply=False, delete_after=45) if from_unit not in self.unit_dict: return Response('Unit `' + from_unit + '` is not recognized.', reply=False, delete_after=45) if to_unit not in self.unit_dict: return Response('Unit `' + to_unit + '` is not recognized.', reply=False, delete_after=45) if to_unit == from_unit: return Response('Units must be different.', reply=False, delete_after=45) if self.unit_dict[from_unit][1] != self.unit_dict[to_unit][1]: return Response('Units must be of same type.', reply=False, delete_after=45) #command runs here if self.unit_dict[from_unit][1] != 'temperature': output = value * self.unit_dict[from_unit][0] / self.unit_dict[ to_unit][0] output = self.round_sig(output) return Response(str(value) + ' ' + self.unit_dict[from_unit][2] + ' converts to ' + str(output) + ' ' + self.unit_dict[to_unit][2], reply=False, delete_after=45) else: if to_unit == 'celcius': output = (value - 32) * (5 / 9) else: output = (value * 1.8) + 32 output = self.round_sig(output) return Response(str(value) + ' degrees ' + from_unit + ' converts to ' + str(output) + ' degrees ' + to_unit, reply=False, delete_after=45)
async def cmd_meme(self, message, leftover_args, user_mentions): """ Usage: {command_prefix}meme template first line : second line Generate a Meme based on the provided template, first line and second line. Lines are seperated by ':' Templates can be found by calling '{command_prefix}meme template' """ if not leftover_args: return Response(send_help=True) template_list = [ 'tenguy', 'afraid', 'older', 'aag', 'tried', 'biw', 'blb', 'kermit', 'bd', 'ch', 'cbg', 'wonka', 'cb', 'keanu', 'dsm', 'live', 'ants', 'doge', 'alwaysonbeat', 'ermg', 'facepalm', 'fwp', 'fa', 'fbf', 'fmr', 'fry', 'ggg', 'hipster', 'icanhas', 'crazypills', 'mw', 'noidea', 'regret', 'boat', 'sohappy', 'captain', 'inigo', 'iw', 'ackbar', 'happening', 'joker', 'ive', 'll', 'morpheus', 'badchoice', 'mmm', 'jetpack', 'red', 'mordor', 'oprah', 'oag', 'remembers', 'philosoraptor', 'jw', 'sad-obama', 'sad-clinton', 'sadfrog', 'sad-bush', 'sad-biden', 'sad-boehner', 'sarcasticbear', 'dwight', 'sb', 'ss', 'sf', 'dodgson', 'money', 'sohot', 'awesome-awkward', 'awesome', 'awkward-awesome', 'awkward', 'fetch', 'success', 'ski', 'officespace', 'interesting', 'toohigh', 'bs', 'both', 'winter', 'xy', 'buzz', 'yodawg', 'yuno', 'yallgot', 'bad', 'elf', 'chosen' ] if leftover_args[0].lower() == 'templates': dictionary_string = '**MEME TEMPLATES:**\n' for template in template_list: dictionary_string += template + ', ' return Response(dictionary_string, reply=True, delete_after=60) meme_type = leftover_args[0] if not meme_type in template_list: return Response( 'Template `{}` not available. Run `{}meme templates` for a list of templates' .format(meme_type, self.bot.config.prefix), reply=True, delete_after=30) meme_raw = message.content[len(self.bot.config.prefix + 'meme ' + meme_type + ' '):].replace(' : ', ":").replace( '?', '~q').replace('/', '~s').replace( '%', '~p').replace('\:', '%3A').strip() url_base = 'http://memegen.link/' if user_mentions: for user in user_mentions: mention = user.mention if user.nick: replacement_name = user.nick else: replacement_name = user.name meme_raw = meme_raw.replace(mention, replacement_name) if meme_raw == '': return Response( 'Message Required for Meme to be generated. To create a meme, use `{}meme template first line:second line`' .format(self.bot.config.prefix), reply=True, delete_after=10) if ':' in meme_raw: meme_sections = meme_raw.split(":") if meme_sections[0].strip() == '': meme_sections[0] = '%20' url = url_base + meme_type + '/' + meme_sections[0].strip( ).replace(' ', '%20') + '/' + meme_sections[1].strip().replace( ' ', '%20') + '.jpg' else: url = url_base + meme_type + '/' + meme_raw.strip().replace( ' ', '%20') + '.jpg' return Response(url, reply=True, delete_after=600)
async def cmd_prune(self, message, channel, server, bot_member, author, auth_perms, user_mentions, prune_number=50, prune_type=None): """ Usage: {command_prefix}prune (number) [Prune Type] Prunes (number) Messages from the chat help_exclude """ if auth_perms >= 35: # Check if prune_number is a number try: float(prune_number) prune_number = min( int(prune_number) + 1, 1000 ) # Set prune_number to 1000 if greater than 1000. Add 1 to the number to counteract the initiation message except: return Response( "The number of messages to prune must be a number.", reply=True, delete_after=15) delete_invokes = True manage_messages = channel.permissions_for( bot_member).manage_messages def is_bot_command(possible_command_fire): if possible_command_fire.content.strip().startswith( self.bot.config.prefix): possible_command_handler, *args = possible_command_fire.content.strip( ).split() possible_command_handler = possible_command_handler[ len(self.bot.config.prefix):].lower().strip() possible_command_info = self.bot.plugin_db.table( 'commands').select("PLUGIN_NAME").where( "COMMAND_KEY").equals( possible_command_handler).execute() possible_plugin_name = None for possible_command in possible_command_info: possible_plugin_name = possible_command[0] if possible_plugin_name: return True else: return False elif possible_command_fire.author == bot_member: return True else: return False def check( check_message ): # Modify this function to provide more than just bot messages. if prune_type == None or prune_type == 'all': if manage_messages: return True else: if prune_type == 'all': return Response(permissions_error=True) else: if not self.bot.user.bot: if check_message.author == self.bot.user: return True else: return False else: return Response(permissions_error=True) elif prune_type == 'commands': return is_bot_command(check_message) elif user_mentions: if check_message.author in user_mentions: return True else: return False else: return False if self.bot.user.bot: if manage_messages: deleted = await self.bot.purge_from(channel, check=check, limit=prune_number) num_messages = len(deleted) if check(message): num_messages += -1 if num_messages <= 1: message_suffix = '' else: message_suffix = 's' return Response('Pruned {} message{}.'.format( num_messages, message_suffix), delete_after=5) else: return Response(permissions_error=True) deleted = 0 async for entry in self.bot.logs_from(channel, prune_number, before=message): should_delete = check(entry) if should_delete: await self.bot.safe_delete_message(entry) deleted += 1 await asyncio.sleep(0.21) if check(message): deleted += -1 if deleted <= 1: message_suffix = '' else: message_suffix = 's' return Response('Purged {} message{}.'.format( deleted, message_suffix), delete_after=55) else: return Response(permissions_error=True)
async def cmd_undeafen(self, message, server, auth_perms, user_mentions): """ Usage: {command_prefix}undeafen (UserMention) [UserMention] [UserMention]... Undeafen a user or set of users help_exclude """ if auth_perms >= 35: if not user_mentions: return Response(send_help=True) server_preserve_overrides = await self.get_key( server, 'preserve_overrides') server_soft_mute = await self.get_key(server, 'soft_mute') user_count = len(user_mentions) check_count = 0 response = 'Undeafened ' if server_soft_mute: server_roles = await self.get_roles(server) if server_roles[0] == None and server_roles[1] == None: return Response(permissions_error=True) deafen_role = server_roles[1] for user in user_mentions: user_permissions = await self.bot.permissions.check_permissions( user, message.channel, message.server) if user_permissions >= auth_perms: return Response(permissions_error=True) check_count += 1 if server_soft_mute: if not server_roles[2]: return Response(permissions_error=True) await self.bot.remove_roles(user, deafen_role) else: for channel in server.channels: try: if not server_preserve_overrides == True: overwrite = channel.overwrites_for(user) else: overwrite = discord.PermissionOverwrite() overwrite.send_messages = None overwrite.read_messages = None await self.bot.edit_channel_permissions( channel, user, overwrite) except: self.bot.safe_send_message( message.channel, 'Error Undeafened {} in {}'.format( user.mention, channel.mention), expire_in=10) if check_count != user_count: response += user.mention + ' & ' else: response += user.mention response += '.' return Response(response, reply=False, delete_after=10) else: return Response(permissions_error=True)
async def cmd_unban(self, message, server, auth_perms, user_mentions, leftover_args): """ Usage: {command_prefix}unban (UserMention | Username) [UserMention] [UserName]... UnBan a User or Set of Users help_exclude """ if auth_perms >= 35: if not user_mentions or not leftover_args: return Response(send_help=True) try: ban_list = await self.bot.get_bans(server) except discord.Forbidden: return Response(permissions_error=True) not_unbanned_list = [] unbanned_list = [] for user in user_mentions: while user.mention in leftover_args: leftover_args.remove(user.mention) if user in ban_list: try: await self.bot.unban(server, user) unbanned_list = unbanned_list + [user] except: not_unbanned_list = not_unbanned_list + [user] else: not_unbanned_list = not_unbanned_list + [user] for user in ban_list: if user.name in leftover_args: leftover_args.remove(user.name) try: await self.bot.unban(server, user) unbanned_list = unbanned_list + [user] except: not_unbanned_list = not_unbanned_list + [user] else: pass response = '' ubl_len = len(unbanned_list) nbl_len = len(not_unbanned_list) la_len = len(leftover_args) if ubl_len == 0 and nbl_len == 0 and la_len == 0: response = 'ERROR Handling Unbans' if ubl_len >= 1: response = 'Successfully Unbanned ' ubl_check = 0 for user in unbanned_list: ubl_check += 1 if ubl_check != ubl_len: response += user.mention + ' & ' else: response += user.mention response += '. ' if nbl_len >= 1 or la_len >= 1: response = 'Failed to Unban ' nbl_check = 0 la_check = 0 for user in not_unbanned_list: nbl_check += 1 if nbl_check != nbl_len or la_len >= 1: response += user.mention + ' & ' else: response += user.mention for string in leftover_args: la_check += 1 if la_check != la_len: response += string + ' & ' else: response += string response += '.' return Response(response, reply=False, delete_after=10) else: return Response(permissions_error=True)
async def cmd_ban(self, message, auth_perms, user_mentions): """ Usage: {command_prefix}ban (UserMention) [UserMention2] [UserMention3]... Ban a given User or set of Users help_exclude """ if auth_perms >= 35: if not user_mentions: return Response(send_help=True) users_to_ban = user_mentions response = '' num_users = len(users_to_ban) user_number = 0 perms_error = [] success_message = 'Successfully Banned ' for user in users_to_ban: user_permissions = await self.bot.permissions.check_permissions( user, message.channel, message.server) if user_permissions >= auth_perms: perms_error = perms_error + [user] else: try: user_number = user_number + 1 await self.bot.ban(user) if user_number != num_users: success_message += user.mention + ' & ' else: success_message += user.mention except: pass num_fail = len(perms_error) if num_fail < num_users: response = success_message response += '.' if num_fail >= 1 and num_fail < num_users: response += " " if num_fail >= 1: response += 'Insufficient Permissions to ban ' fail_number = 0 for user in perms_error: fail_number = fail_number + 1 if fail_number != num_fail: response += user.mention + ' & ' else: response += user.mention response += "." return Response(response, reply=True, delete_after=15) else: return Response(permissions_error=True)
async def cmd_tba(self, message, channel, leftover_args): """ Usage: {command_prefix}TBA (Item to return) (Search Parameters) Pulls data from TBA. For more info, do {command_prefix}tba """ no_response = '```The Blue Alliance - ' no_response += 'Pulls Data from The Blue Alliance API\n' no_response += ' • ' + self.bot.config.prefix + 'tba team (team_number)\n' no_response += ' - pulls Team Information\n' no_response += ' • ' + self.bot.config.prefix + 'tba event (year)(event_name)\n' no_response += ' ' + self.bot.config.prefix + 'tba event (event_key)\n' no_response += ' - pulls Event Information\n' no_response += ' • ' + self.bot.config.prefix + 'tba awards (team_number) [year]\n' no_response += ' - pulls Team Awards [Year Optional]\n' try: cmd_type = leftover_args[0] del leftover_args[0] except: no_response += '```' return Response(no_response, reply=False, delete_after=45) if cmd_type == 'team': if bool(self.team_key_pattern.search(leftover_args[0])): key = leftover_args[0] else: param = '' for partial_msg in leftover_args: param += partial_msg + ' ' param = param[:-1] try: num = int(param) except: no_response += '\n\nInvalid Team Number Supplied```' return Response(no_response, reply=False, delete_after=45) key = "frc" + str(num) try: team = self.TBA.get_team(key) except: no_response += '\n\nTeam doesn\'t exist or an error occured.```' return Response(no_response, reply=False, delete_after=45) team_data = "Team " + str(team.team_number) + ": " + str(team.nickname)+ "\nFrom: " + str(team.location) if team.website != None: team_data += "\nWebsite: " + team.website if team.motto != None: team_data += '\nMotto: "' + team.motto + '"' team_data += '\nhttp://www.thebluealliance.com/team/' + str(team.team_number) return Response(team_data, reply=False, delete_after=60) elif cmd_type == 'event': if bool(self.event_key_pattern.search(leftover_args[0])): key = leftover_args[0] else: try: year_str = leftover_args[0] del leftover_args[0] param = '' for partial_msg in leftover_args: param += partial_msg + ' ' param = param[:-1] except: return Response('Additional arguments needed. ```' + self.bot.config.prefix + 'tba event [Year] [Beginning of event name]```', reply=False, delete_after=30) try: year = int(year_str) except: no_response += '\n\nYear must be an integer.```' return Response(no_response, reply=False, delete_after=45) key = self.TBA.calc_event_key(year, param) if key == '1': return Response('Multiple events found. Please refine your search.', reply=False, delete_after=30) if key == '0': return Response('No events found. Please ensure spelling is correct.', reply=False, delete_after=30) event = self.TBA.get_event(key) event_data = event.name + "\nYear: " + str(event.year) + "\nLocation: " + str(event.location) + "\nDates: " + str(event.start_date) + " to " + str(event.end_date) + "\nEvent Type: " + str(event.event_type_string) + "\nhttps://www.thebluealliance.com/event/" + str(event.key) return Response(event_data, reply=False, delete_after=60) elif cmd_type == 'awards': if len(leftover_args) >= 1: if bool(self.team_key_pattern.search(leftover_args[0])): team_key = leftover_args[0] team_number = team_key[3:] else: try: team_number = int(leftover_args[0]) except: no_response += '\n\nInvalid Team Number Supplied```' return Response(no_response, reply=False, delete_after=45) team_key = 'frc' + str(team_number) if len(leftover_args) >= 2: try: search_year = int(leftover_args[1]) except: no_response += '\n\nSearch Year Provided but Invalid```' return Response(no_response, reply=False, delete_after=45) else: search_year = None try: team_awards = self.TBA.get_team_history_awards(team_key) except: return Response('Something went wrong in collecting Team Awards') awards_msg_content = '**Team Awards for Team {}'.format(team_number) if search_year: awards_msg_content += ' in {}**\n'.format(search_year) else: awards_msg_content += '**\n' for award in team_awards: if not search_year or search_year == award.year: award_string = '{}: {} ({})\n'.format(str(award.year), str(award.name), str(award.event_key)) tentative_msg = awards_msg_content + award_string if len(tentative_msg) > 2000: await self.bot.safe_send_message( channel, awards_msg_content, expire_in=120 if self.bot.config.delete_messages else 0, also_delete=message if self.bot.config.delete_invoking else None ) awards_msg_content = '' else: awards_msg_content = tentative_msg return Response(awards_msg_content, reply=False, delete_after=120) else: no_response += '\n\nInvalid Team Number Supplied```' return Response(no_response, reply=False, delete_after=45) else: no_response += '\n\nInvalid Secondary Command Supplied```' return Response(no_response, reply=False, delete_after=45)
async def cmd_help(self, help_command=None): """ Usage: {command_prefix}help [command] Get a List of Bot Commands, or get help about a given Command. """ if help_command: help_command = help_command.lower().strip() raw_commands_return = self.bot.plugin_db.table('commands').select( "PLUGIN_NAME", "COMMAND_USAGE", "COMMAND_DESCRIPTION").where( "COMMAND_KEY").equals(help_command).execute() cmd_plugin = '' cmd_usage = '' cmd_description = '' for command_data in raw_commands_return: cmd_plugin = command_data[0] cmd_usage = command_data[1] cmd_description = command_data[2] if cmd_plugin == '': return raw_plugin_return = self.bot.plugin_db.table('plugins').select( "FANCY_NAME").where("PLUGIN_NAME").equals( cmd_plugin).execute() for item in raw_plugin_return: cmd_plugin = item[0] help_response = '```Usage for ' + self.bot.config.prefix + help_command help_response += ' (' + cmd_plugin + '):' help_response += '\n ' help_response += cmd_usage + '\n\n' help_response += cmd_description + '```' else: plugins_commands_dict = {} raw_commands_return = self.bot.plugin_db.table('commands').select( "COMMAND_KEY", "PLUGIN_NAME", "COMMAND_DESCRIPTION", "HELP_EXCLUDE").execute() for command in raw_commands_return: command_key = command[0] plugin = command[1] description = command[2] exclude = command[3] if not exclude == "YES": cmd_entry = command_key + ": " + description if not plugin in plugins_commands_dict: plugins_commands_dict[plugin] = [cmd_entry] else: plugins_commands_dict[plugin] = plugins_commands_dict[ plugin] + [cmd_entry] help_response = "**{}'s Commands:**```\n".format( self.bot.config.bot_name) secondary_response = '' for plugin, commands in plugins_commands_dict.items(): raw_plugin_return = self.bot.plugin_db.table('plugins').select( "FANCY_NAME").where("PLUGIN_NAME").equals( plugin).execute() for item in raw_plugin_return: fancy_name = item[0] if plugin == 'BaseCommands': help_response += fancy_name + '\n' for command in commands: help_response += ' • ' + self.bot.config.prefix + command + '\n' help_response += '\n' else: secondary_response += fancy_name + '\n' for command in commands: secondary_response += ' • ' + self.bot.config.prefix + command + '\n' secondary_response += '\n' help_response += secondary_response help_response += '```' return Response(help_response, reply=False, delete_after=60)