def predicate(ctx): dj_role_id = int(ctx.options['dj_role'].data) #Will be zero if unset if not dj_role_id: return True #Allow if there is no DJ role set dj_role = ctx.guild.get_role(dj_role_id) if dj_role: #If the role exists if discord.utils.get( ctx.author.roles, id=dj_role_id) is not None: #If the author has the role return True if ctx.voice_client: bot_channel = ctx.voice_client.channel if ctx.author.voice: #If the author is in a voice channel... if ctx.author.voice.channel == bot_channel and len( bot_channel.members ) <= 2: #and its the same as the bot and there's two or less members return True else: raise commands.MissingAnyRole(("DJ")) elif len(bot_channel.members ) == 1: #If the bot is the only one in the channel return True elif ctx.author.voice: #implied 'and not ctx.voice_client' due to above condition if len(ctx.author.voice.channel.members) == 1: return True raise commands.MissingAnyRole(("DJ"))
async def disable(self, ctx, command, *args): user = ctx.author date_args_start_index = 0 if len(args) > 0: try: user = await commands.MemberConverter().convert(ctx, args[0]) date_args_start_index = 1 except (commands.CommandError, IndexError): date_args_start_index = 0 if user != ctx.author and not permChecks.check_full_access(ctx.author): raise commands.MissingAnyRole(Config().FULL_ACCESS_ROLES) until = utils.analyze_time_input(*args[date_args_start_index:]) result = self.bot.ignoring.add_user_command(user, command, until) if result == IgnoreEditResult.Success: await ctx.message.add_reaction(Lang.CMDSUCCESS) elif result == IgnoreEditResult.Already_in_list: await ctx.message.add_reaction(Lang.CMDERROR) await ctx.send(Lang.lang(self, 'user_cmd_already_blocked', command, utils.get_best_username(user))) elif result == IgnoreEditResult.Until_in_past: await ctx.message.add_reaction(Lang.CMDERROR) await ctx.send(Lang.lang(self, 'no_time_machine')) await utils.log_to_admin_channel(ctx)
def command_check_staff_roles(ctx): check_roles = (ctx.bot.server_config["staff_roles"][str(ctx.guild.id)] + ctx.bot.server_config["admin_roles"][str(ctx.guild.id)]) if check_role_list(ctx.author, check_roles): return True error_roles = [ ctx.guild.get_role(role).name for role in check_roles if ctx.guild.get_role(role) is not None ] raise commands.MissingAnyRole(error_roles)
def predicate(ctx): if not isinstance(ctx.channel, discord.abc.GuildChannel): raise commands.NoPrivateMessage() if config.DEMOCRACIV_GUILD_ID != ctx.guild.id: raise exceptions.NotDemocracivGuildError() getter = functools.partial(discord.utils.get, ctx.author.roles) if any(getter(id=role.value) is not None for role in roles): return True raise commands.MissingAnyRole(roles)
def check_roles(ctx, roles): """Checks that the user has all the required roles.""" if type(roles) is str: roles = [roles] user = ctx.author # Get the list of IDs from user.roles, and list of IDs from arg roles user_roles = [role.id for role in user.roles] req_roles = [ROLE_IDS[req_role] for req_role in roles] # Check intersection of roles in user_roles and req_roles. if not [role for role in user_roles if role in req_roles]: raise commands.MissingAnyRole(roles) return True
async def enable(self, ctx, command, user: discord.Member = None): if user is None: user = ctx.author if user != ctx.author and not permChecks.check_full_access(ctx.author): raise commands.MissingAnyRole(*Config().FULL_ACCESS_ROLES) result = self.bot.ignoring.remove_user_command(user, command) if result == IgnoreEditResult.Success: await ctx.message.add_reaction(Lang.CMDSUCCESS) elif result == IgnoreEditResult.Not_in_list: await ctx.message.add_reaction(Lang.CMDERROR) await ctx.send(Lang.lang(self, 'user_cmd_not_blocked', command, utils.get_best_username(user))) await utils.log_to_admin_channel(ctx)
async def real_check(ctx: Optional[commands.Context] = None, channel: Optional[discord.TextChannel] = None, member: Optional[discord.Member] = None) -> bool: member = member if not ctx else ctx.author channel = channel if not ctx else ctx.channel if check_adm: perms = channel.permissions_for(member) if perms.administrator: return True for rid in roles: if rid in [role.id for role in member.roles]: return True if throw_exc: raise commands.MissingAnyRole(roles)
async def hasroles(self, ctx): for rolename in config["roles"]: for role in ctx.author.roles: if role.name == rolename: return raise commands.MissingAnyRole(config["roles"])
async def test__on_command_error(self): """Unit tests for bot._on_command_error function.""" # async def _on_command_error(bot, ctx, exc) _on_command_error = bot._on_command_error # mauvais serveur ctx = mock.NonCallableMock(commands.Context, guild=10) await _on_command_error(config.bot, ctx, None) ctx.send.assert_not_called() # STOP ctx = mock_discord.get_ctx() exc = commands.CommandInvokeError(blocs.tools.CommandExit()) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("Mission aborted") # STOP custom message ctx = mock_discord.get_ctx() exc = commands.CommandInvokeError(blocs.tools.CommandExit("cust0m")) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("cust0m") # BDD error - MJ ctx = mock_discord.get_ctx() ctx.author.top_role = mock.MagicMock(discord.Role, __ge__=lambda s, o: True) # >= MJ exc = commands.CommandInvokeError(bdd.SQLAlchemyError("bzzt")) try: raise exc.original # creating traceback except bdd.SQLAlchemyError: pass await _on_command_error(config.bot, ctx, exc) mock_discord.assert_sent(config.Channel.logs, "Rollback session") config.Channel.logs.send.reset_mock() config.session.rollback.assert_called_once() config.session.rollback.reset_mock() ctx.assert_sent(["Un problème est survenu", "Traceback", "SQLAlchemyError", "bzzt"]) # BDD error - not MJ ctx = mock_discord.get_ctx() ctx.author.top_role = mock.MagicMock(discord.Role, __ge__=lambda s, o: False) # < MJ exc = commands.CommandInvokeError(bdd.DriverOperationalError("bzoozt")) try: raise exc.original # creating traceback except bdd.DriverOperationalError: pass await _on_command_error(config.bot, ctx, exc) mock_discord.assert_sent(config.Channel.logs, "Rollback session") config.Channel.logs.send.reset_mock() config.session.rollback.assert_called_once() config.session.rollback.reset_mock() ctx.assert_sent(["Un problème est survenu", bdd.DriverOperationalError.__name__, "bzoozt"]) ctx.assert_not_sent("Traceback") # BDD error - session not ready : on vérifie juste que pas d'erreur ctx = mock_discord.get_ctx() _session = config.session del config.session ctx.author.top_role = mock.MagicMock(discord.Role, __ge__=lambda s, o: True) # >= MJ exc = commands.CommandInvokeError(bdd.SQLAlchemyError("bzzt")) await _on_command_error(config.bot, ctx, exc) mock_discord.assert_sent(config.Channel.logs) # nothing config.Channel.logs.send.reset_mock() ctx.assert_sent(["Un problème est survenu", "SQLAlchemyError", "bzzt"]) config.session = _session # CommandNotFound ctx = mock_discord.get_ctx() await _on_command_error(config.bot, ctx, commands.CommandNotFound()) ctx.assert_sent("je ne connais pas cette commande") # DisabledCommand ctx = mock_discord.get_ctx() await _on_command_error(config.bot, ctx, commands.DisabledCommand()) ctx.assert_sent("Cette commande est désactivée") # ConversionError command = mock.Mock() ctx = mock_discord.get_ctx(command) exc = commands.ConversionError("bkrkr", "kak") await _on_command_error(config.bot, ctx, exc) ctx.assert_sent(["ce n'est pas comme ça qu'on utilise cette commande", "ConversionError", "bkrkr", "kak"]) config.bot.get_context.assert_called_with(ctx.message) self.assertEqual(ctx.message.content, f"!help {command.name}") config.bot.get_context.return_value.reinvoke.assert_called() # UserInputError command = mock.Mock() ctx = mock_discord.get_ctx(command) exc = commands.UserInputError("bakaka") await _on_command_error(config.bot, ctx, exc) ctx.assert_sent(["ce n'est pas comme ça qu'on utilise cette commande", "UserInputError", "bakaka"]) config.bot.get_context.assert_called_with(ctx.message) self.assertEqual(ctx.message.content, f"!help {command.name}") config.bot.get_context.return_value.reinvoke.assert_called() # UserInputError derivate command = mock.Mock() ctx = mock_discord.get_ctx(command) exc = commands.BadArgument("bakaka") await _on_command_error(config.bot, ctx, exc) ctx.assert_sent(["ce n'est pas comme ça qu'on utilise cette commande", "BadArgument", "bakaka"]) config.bot.get_context.assert_called_with(ctx.message) self.assertEqual(ctx.message.content, f"!help {command.name}") config.bot.get_context.return_value.reinvoke.assert_called() # CheckAnyFailure ctx = mock_discord.get_ctx() exc = commands.CheckAnyFailure(mock.ANY, mock.ANY) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("cette commande est réservée aux MJs") # MissingAnyRole ctx = mock_discord.get_ctx() exc = commands.MissingAnyRole([mock.ANY]) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("Cette commande est réservée aux joueurs") # MissingRole ctx = mock_discord.get_ctx() exc = commands.MissingRole(mock.ANY) await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("cette commande est réservée aux joueurs en vie") # one_command.AlreadyInCommand, not addIA/modifIA command = mock.Mock() command.configure_mock(name="blabla") ctx = mock_discord.get_ctx(command) exc = blocs.one_command.AlreadyInCommand() await _on_command_error(config.bot, ctx, exc) ctx.assert_sent("Impossible d'utiliser une commande pendant") # one_command.AlreadyInCommand, addIA command = mock.Mock() command.configure_mock(name="addIA") ctx = mock_discord.get_ctx(command) exc = blocs.one_command.AlreadyInCommand() await _on_command_error(config.bot, ctx, exc) ctx.assert_sent() # one_command.AlreadyInCommand, modifIA command = mock.Mock() command.configure_mock(name="modifIA") ctx = mock_discord.get_ctx(command) exc = blocs.one_command.AlreadyInCommand() await _on_command_error(config.bot, ctx, exc) ctx.assert_sent() # CheckFailure (autre check erreur) ctx = mock_discord.get_ctx() exc = commands.CheckFailure("jojo") with mock.patch("lgrez.blocs.tools.mention_MJ") as mmj_patch: await _on_command_error(config.bot, ctx, exc) mmj_patch.assert_called_once_with(ctx) ctx.assert_sent(["cette commande ne puisse pas être exécutée", "CheckFailure", "jojo"]) # other exception ctx = mock_discord.get_ctx() exc = AttributeError("oh") with mock.patch("lgrez.blocs.tools.mention_MJ") as mmj_patch: await _on_command_error(config.bot, ctx, exc) mmj_patch.assert_called_once_with(ctx) ctx.assert_sent(["Une erreur inattendue est survenue", "AttributeError", "oh"]) # other exception ctx = mock_discord.get_ctx() class SomeException(Exception): pass exc = SomeException("p!wet") with mock.patch("lgrez.blocs.tools.mention_MJ") as mmj_patch: await _on_command_error(config.bot, ctx, exc) mmj_patch.assert_called_once_with(ctx) ctx.assert_sent(["Une erreur inattendue est survenue", "SomeException", "p!wet"])
async def cog_check(self, ctx): if self.is_staff(ctx, ctx.author): return True raise commands.MissingAnyRole(self.mod_role_ids)