Пример #1
0
 async def command_disabled(ctx):
     """
     Checks if a command is disabled or blocked for user.
     This check will be executed before other command checks.
     """
     if bot.ignoring.check_command(ctx):
         raise commands.DisabledCommand()
     if bot.ignoring.check_user_command(ctx.author,
                                        ctx.command.qualified_name):
         raise commands.DisabledCommand()
     return True
Пример #2
0
class Questionnaire(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener("on_startup")
    async def on_startup(self):
        if not self.bot.debug:
            print("Added listeners: Questionnaire")

            self.bot.add_listener(self.on_message, "on_message")

    async def on_message(self, message):
        async def get_prefix():
            for pre in await self.bot.get_prefix(message):
                if message.content.lower().startswith(pre):
                    return pre

            return None

        if message.guild is None or message.author.bot:
            return None

        elif (prefix := await get_prefix()) is None:
            return None

        args = message.content[len(prefix):].split(" ")

        if len(args) > 0:
            questionnaire = await self.bot.db["questionnaires"].find_one({
                "server":
                message.guild.id,
                "command":
                args[0]
            })

            if questionnaire:
                if self.bot.has_permissions(message.channel,
                                            send_messages=True):
                    if not await self.bot.is_command_enabled(
                            message.guild, self):
                        raise commands.DisabledCommand(
                            "This command has been disabled in this server.")

                    elif not await self.bot.is_channel_whitelisted(
                            message.guild, message.channel):
                        raise commands.DisabledCommand(
                            "Commands have been disabled in this channel.")

                    else:
                        await self.send_questionnaire(message.channel,
                                                      message.author,
                                                      questionnaire)
Пример #3
0
def getAPIKey(service: str) -> str:
    if not service in apiKeys:
        raise commands.DisabledCommand(
            message=
            'Command disabled due to missing API key. Please contact bot owner'
        )
    return apiKeys[service]
Пример #4
0
    async def can_run(self, ctx):
        """Overwritten to also raise
        :exc:`.ReactionOnlyCommand` for commands that have
        :attr:`invoke_with_message <.ReactionCommand.invoke_with_message>`
        set to ``False``.

        Otherwise the same as :meth:`can_run() <discord.ext.commands.Command.can_run>`.

        Parameters
        ----------
        ctx: :class:`Context <discord.ext.reactioncommands.ReactionContext>`
            Context to check if it can run against.

        Raises
        ------
        :class:`discord.ext.commands.CommandError`
            Error for why command can't be run

        Returns
        -------
        :class:`bool`
            Whether or not the command can run.
        """
        if not self.enabled:
            raise commands.DisabledCommand(f'{self.name} command is disabled')
        if not getattr(ctx, 'reaction_command',
                       False) and not self.invoke_with_message:
            raise ReactionOnlyCommand(
                f'{self.name} command is only usable with reactions')
        return await super().can_run(ctx)
Пример #5
0
    async def bot_check(self, ctx) -> bool:
        if not self.exts_loaded or ctx.guild is None or ctx.author.bot:
            raise GlobalCheckFail("Bot not ready.")

        elif not self.has_permissions(ctx.channel, send_messages=True):
            raise GlobalCheckFail("Missing `Send Messages` permission.")

        elif not await self.is_command_enabled(ctx.guild, ctx.command):
            raise commands.DisabledCommand(
                "This command has been disabled in this server.")

        elif not await self.is_channel_whitelisted(
                ctx.guild, ctx.channel, command=ctx.command):
            raise commands.DisabledCommand(
                "Commands have been disabled in this channel.")

        return True
Пример #6
0
    async def _verify_checks(self, ctx):
        if not self.enabled:
            raise commands.DisabledCommand(f"{self.name} command is disabled")

        if not (await self.can_run(ctx, change_permission_state=True)):
            raise commands.CheckFailure(
                f"The check functions for command {self.qualified_name} failed."
            )
Пример #7
0
 def bot_check(self, ctx):
     if ctx.guild:
         if not CogController.is_disabled(ctx.command.cog_name,
                                          ctx.guild.id):
             if not CommandController.is_disabled(
                     ctx.command.qualified_name, ctx.guild.id):
                 if not BlacklistedUsers.is_blacklisted(
                         ctx.author.id, ctx.guild.id):
                     return True
                 else:
                     raise commands.CheckFailure(
                         "Failed global check because user is blacklisted.")
             else:
                 raise commands.DisabledCommand(
                     "This command is disabled on the server.")
         else:
             raise commands.DisabledCommand(
                 "Failed attempt to use command from a disabled module.")
     else:
         return True
Пример #8
0
    async def can_run(self, ctx):
        if not self.enabled:
            raise commands.DisabledCommand(
                '{0.name} command is disabled'.format(self))

        original = ctx.command
        ctx.command = self

        try:
            predicates = self.checks
            if not predicates:
                return True
            return await discord.utils.async_all(
                predicate(ctx) for predicate in predicates)
        finally:
            ctx.command = original
Пример #9
0
    async def on_message(self, msg):
        """Will be called from on_message listener to react for custom cmds"""

        # get cmd parts/args
        msg_args = cmd_re.findall(msg.content)
        cmd_name = msg_args[0][1].lower(
        ) if msg_args[0][1] else msg_args[0][0].lower()

        cmd_args = msg_args[1:]
        if cmd_name not in self.commands:
            return
        elif (self.bot.ignoring.check_command_name(cmd_name, msg.channel)
              or self.bot.ignoring.check_user_command(msg.author, cmd_name)):
            raise commands.DisabledCommand()

        cmd_content = await self.commands[cmd_name].get_ran_formatted_text(
            self.bot, msg, cmd_args)

        await msg.channel.send(cmd_content)
Пример #10
0
    async def can_run(self, ctx):
        if not self.enabled:
            raise commands.DisabledCommand(
                '{0.name} command is disabled'.format(self))

        original = ctx.command
        ctx.command = self

        try:
            if not await ctx.bot.can_run(ctx):
                raise commands.CheckFailure(
                    f'The global check functions for command {self.qualified_name} failed.'
                )

            cog = self.cog
            # Other checks should have more priority first
            if cog is not None:
                local_check = commands.Cog._get_overridden_method(
                    cog.cog_check)
                if local_check is not None:
                    ret = await discord.utils.maybe_coroutine(local_check, ctx)
                    if not ret:
                        return False

            if not self.checks:
                return await self._check_level(ctx)

            checks = self._filter_out_permissions()
            pred = await discord.utils.async_all(
                predicate(ctx) for predicate in checks)
            if pred is False:
                # An important check failed...
                return False

            return await self._check_level(ctx)
        finally:
            ctx.command = original
Пример #11
0
 def predicate(ctx):
     for member in ctx.guild.members:
         if member.id == ctx.bot.owner_id:
             return True
     raise commands.DisabledCommand(
         f'{ctx.invoked_with} command is disabled.')
Пример #12
0
 async def disabler(ctx: "Context") -> bool:
     if ctx.guild == guild:
         raise commands.DisabledCommand()
     return True
Пример #13
0
def bot_cli(ctx):
    # Because the is_admin check runs before this, we can safely assume
    # that we are in a guild
    if ctx.message.channel.name != CLI_CHANNEL:
        raise commands.DisabledCommand()
    return True
Пример #14
0
def is_channel(ctx, channel=channel_jail):
    if ctx.message.channel.name == channel:
        return True
    else:
        raise commands.DisabledCommand(f'This command is not applicable here')
Пример #15
0
    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"])
Пример #16
0
 def isEnabled(ctx):
     if Storage.isEnabled(ctx.guild, 'Moderation') is False:
         raise commands.DisabledCommand()
     else:
         return True