Python discord.ext.commands.BotMissingPermissions() Examples

The following are 8 code examples of discord.ext.commands.BotMissingPermissions(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord.ext.commands , or try the search function .
Example #1
Source File: nullctf.py    From NullCTF with GNU General Public License v3.0 5 votes vote down vote up
def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Missing a required argument.  Do >help")
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You do not have the appropriate permissions to run this command.")
    if isinstance(error, commands.BotMissingPermissions):
        await ctx.send("I don't have sufficient permissions!")
    else:
        print("error not caught")
        print(error) 
Example #2
Source File: lavalink.py    From rewrite with GNU General Public License v3.0 5 votes vote down vote up
def connect(self, channel):
        """
        Connect to a voice channel

        :param channel: The voice channel to connect to
        :return:
        """
        # We're using discord's websocket, not lavalink
        if not channel.guild == self.guild:
            raise InvalidArgument("The guild of the channel isn't the the same as the link's!")
        if channel.guild.unavailable:
            raise IllegalAction("Cannot connect to guild that is unavailable!")

        me = channel.guild.me
        permissions = me.permissions_in(channel)
        if not permissions.connect and not permissions.move_members:
            raise BotMissingPermissions(["connect"])

        self.set_state(State.CONNECTING)
        payload = {
            "op": 4,
            "d": {
                "guild_id": channel.guild.id,
                "channel_id": str(channel.id),
                "self_mute": False,
                "self_deaf": False
            }
        }

        await self.bot._connection._get_websocket(channel.guild.id).send_as_json(payload) 
Example #3
Source File: _utils.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def bot_has_permissions(**required):
    """Decorator to check if bot has certain permissions when added to a command"""
    def predicate(ctx):
        """Function to tell the bot if it has the right permissions"""
        given = ctx.channel.permissions_for((ctx.guild or ctx.channel).me)
        missing = [name for name, value in required.items() if getattr(given, name) != value]

        if missing:
            raise commands.BotMissingPermissions(missing)
        else:
            return True

    def decorator(func):
        """Defines the bot_has_permissions decorator"""
        if isinstance(func, Command):
            func.checks.append(predicate)
            func.required_permissions.update(**required)
        else:
            if hasattr(func, '__commands_checks__'):
                func.__commands_checks__.append(predicate)
            else:
                func.__commands_checks__ = [predicate]
            func.__required_permissions__ = discord.Permissions()
            func.__required_permissions__.update(**required)
        return func
    return decorator 
Example #4
Source File: bot.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def on_command_error(self, context, exception):
        if isinstance(exception, commands.NoPrivateMessage):
            await context.send('{}, This command cannot be used in DMs.'.format(context.author.mention))
        elif isinstance(exception, commands.UserInputError):
            await context.send('{}, {}'.format(context.author.mention, self.format_error(context, exception)))
        elif isinstance(exception, commands.NotOwner):
            await context.send('{}, {}'.format(context.author.mention, exception.args[0]))
        elif isinstance(exception, commands.MissingPermissions):
            permission_names = [name.replace('guild', 'server').replace('_', ' ').title() for name in exception.missing_perms]
            await context.send('{}, you need {} permissions to run this command!'.format(
                context.author.mention, utils.pretty_concat(permission_names)))
        elif isinstance(exception, commands.BotMissingPermissions):
            permission_names = [name.replace('guild', 'server').replace('_', ' ').title() for name in exception.missing_perms]
            await context.send('{}, I need {} permissions to run this command!'.format(
                context.author.mention, utils.pretty_concat(permission_names)))
        elif isinstance(exception, commands.CommandOnCooldown):
            await context.send(
                '{}, That command is on cooldown! Try again in {:.2f}s!'.format(context.author.mention, exception.retry_after))
        elif isinstance(exception, (commands.CommandNotFound, InvalidContext)):
            pass  # Silent ignore
        else:
            await context.send('```\n%s\n```' % ''.join(traceback.format_exception_only(type(exception), exception)).strip())
            if isinstance(context.channel, discord.TextChannel):
                DOZER_LOGGER.error('Error in command <%d> (%d.name!r(%d.id) %d(%d.id) %d(%d.id) %d)',
                                   context.command, context.guild, context.guild, context.channel, context.channel,
                                   context.author, context.author, context.message.content)
            else:
                DOZER_LOGGER.error('Error in command <%d> (DM %d(%d.id) %d)', context.command, context.channel.recipient,
                                   context.channel.recipient, context.message.content)
            DOZER_LOGGER.error(''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))) 
Example #5
Source File: music.py    From rewrite with GNU General Public License v3.0 4 votes vote down vote up
def play(self, ctx, *, query: str):
        mp = self.mpm.get_music_player(ctx)
        splitted = query.split()
        should_shuffle = False

        if splitted[0] in ("shuffle", "sh"):
            should_shuffle = True
            query = "".join(splitted[1:])

        voice = ctx.guild.me.voice
        if not voice or not voice.channel:
            try:
                await mp.link.connect(ctx.author.voice.channel)
            except commands.BotMissingPermissions:
                await ctx.send(f"{ERROR} I am unable to connect to **{ctx.author.voice.channel.name}**, "
                               f"check if the permissions are correct!")
                return

        if query == "init0":  # easter egg?
            query = "https://www.youtube.com/playlist?list=PLzME6COik-H9hSsEuvAf26uQAN228ESck"
        elif query == "autoplay":
            settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id)
            if settings.autoplay == "NONE":
                await ctx.send(f"{WARNING} An autoplay playlist has not been set yet, "
                               f"set one with: `.settings autoplay [DEFAULT/link]`")
            else:
                await mp.load_autoplay(settings.autoplay)
                await ctx.send(f"{NOTES} **Added** the autoplay playlist to the queue")
            return
        elif ctx.guild.id in self.bot.bot_settings.patrons.values():
            settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id)
            if settings.aliases and query in settings.aliases:
                query = settings.aliases[query]

        if query.startswith("http"):
            results = await mp.link.get_tracks(query)
        else:
            results = await mp.link.get_tracks_yt(query)

        if not results:
            await ctx.send(f"{WARNING} No results found!")
            return

        if query.startswith("http") and len(results) != 1:
            if should_shuffle:
                random.shuffle(results)
            for track in results:
                await mp.add_track(track, ctx.author)
            await ctx.send(f"{NOTES} **Added** {len(results)} entries to the queue")
        else:
            pos = await mp.add_track(results[0], ctx.author)
            if pos == -1:
                await ctx.send(f"{NOTES} **Added** `{results[0].title}` to be played now")
                return
            await ctx.send(f"{NOTES} **Added** `{results[0].title}` to position: `{pos+1}`") 
Example #6
Source File: music.py    From rewrite with GNU General Public License v3.0 4 votes vote down vote up
def search(self, ctx, *, query):
        mp = self.mpm.get_music_player(ctx)
        sc = ctx.invoked_with == "scsearch"
        if sc:
            results = await mp.link.get_tracks_sc(query)
        else:
            results = await mp.link.get_tracks_yt(query)

        if not results:
            await ctx.send(f"{WARNING} No results found!")
            return

        desc = ""
        for i in range(5):
            desc += f"{i+1}. [{results[i].title}]({results[i].uri})\n"

        e = discord.Embed(colour=COLOR, description=desc)
        e.set_footer(text=f"Results fetched from {'SoundCloud' if sc else 'YouTube'}", icon_url=ctx.author.avatar_url)
        await ctx.send(content=f"{NOTES} Type the number of the entry you wish to play", embed=e)

        try:
            msg = await self.bot.wait_for("message", check=lambda msg: msg.author.id == ctx.author.id, timeout=30.0)
            index = int(msg.content)
        except ValueError:
            await ctx.send(f"{WARNING} Please use a number as the index!")
            return
        except futures.TimeoutError:
            await ctx.send(f"{WARNING} You have not entered a selection!")
            return

        if not 0 < index < 6:
            await ctx.send(f"{WARNING} The index must be from 1-5!")
            return

        selected = results[index-1]

        voice = ctx.guild.me.voice
        if not voice or not voice.channel:
            try:
                await mp.link.connect(ctx.author.voice.channel)
            except commands.BotMissingPermissions:
                await ctx.send(f"{ERROR} I am unable to connect to **{ctx.author.voice.channel.name}**, "
                               f"check if the permissions are correct!")
                return

        pos = await mp.add_track(selected, ctx.author)
        if pos == -1:
            await ctx.send(f"{NOTES} **Added** `{selected.title}` to be played now")
            return
        await ctx.send(f"{NOTES} **Added** `{selected.title}` to position: `{pos+1}`") 
Example #7
Source File: handler.py    From DJ5n4k3 with MIT License 4 votes vote down vote up
def on_command_error(self, ctx, error):
        if hasattr(ctx.command, 'on_error'):
            return
        
        ignored = (commands.MissingRequiredArgument, commands.BadArgument, commands.NoPrivateMessage, commands.CheckFailure, commands.CommandNotFound, commands.DisabledCommand, commands.CommandInvokeError, commands.TooManyArguments, commands.UserInputError, commands.CommandOnCooldown, commands.NotOwner, commands.MissingPermissions, commands.BotMissingPermissions)   
        error = getattr(error, 'original', error)
        

        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.BadArgument):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.NoPrivateMessage):
            return

        elif isinstance(error, commands.CheckFailure):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command is thought for other users. You can't use it.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.DisabledCommand):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command in disabled.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.CommandInvokeError):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like something went wrong. Report this issue to the developer.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.TooManyArguments):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you gave too many arguments.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.UserInputError):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you did something wrong.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.CommandOnCooldown):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.NotOwner):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you do not own this bot.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.MissingPermissions):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.BotMissingPermissions):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url)) 
Example #8
Source File: error_handler.py    From code-jam-5 with MIT License 4 votes vote down vote up
def on_command_error(self, ctx, error):
        """Task when an error occurs."""

        if isinstance(error, commands.CommandNotFound):
            return logger.info(f"{ctx.author} used {ctx.message.content} "
                               f"but nothing was found.")

        if isinstance(error, commands.MissingRequiredArgument):
            logger.info(f"{ctx.author} called {ctx.message.content} and "
                        f"triggered MissingRequiredArgument error.")
            return await ctx.send(f"`{error.param}` is a required argument.")

        if isinstance(error, commands.CheckFailure):
            logger.info(f"{ctx.author} called {ctx.message.content} and triggered"
                        f" CheckFailure error.")
            return await ctx.send("You do not have permission to use this command!")

        if isinstance(error, (commands.UserInputError, commands.BadArgument)):
            logger.info(f"{ctx.author} called {ctx.message.content} and triggered"
                        f" UserInputError error.")
            return await ctx.send("Invalid arguments.")

        if isinstance(error, commands.CommandOnCooldown):
            logger.info(f"{ctx.author} called {ctx.message.content} and"
                        f" triggered ComamndOnCooldown error.")
            return await ctx.send(f"Command is on cooldown!"
                                  f" Please retry after `{error.retry_after}`")

        if isinstance(error, commands.BotMissingPermissions):
            logger.info(f"{ctx.author} called {ctx.message.content} and triggered"
                        f" BotMissingPermissions error.")
            embed = discord.Embed()
            embed.colour = discord.Colour.blue()
            title = "The bot lacks the following permissions to execute the command:"
            embed.title = title
            embed.description = ""
            for perm in error.missing_perms:
                embed.description += str(perm)
            return await ctx.send(embed=embed)

        if isinstance(error, commands.DisabledCommand):
            logger.info(f"{ctx.author} called {ctx.message.content} and"
                        f" triggered DisabledCommand error.")
            return await ctx.send("The command has been disabled!")

        logger.warning(f"{ctx.author} called {ctx.message.content} and"
                       f" triggered the following error:\n {error}")