当前位置: 首页>>代码示例>>Python>>正文


Python commands.BotMissingPermissions方法代码示例

本文整理汇总了Python中discord.ext.commands.BotMissingPermissions方法的典型用法代码示例。如果您正苦于以下问题:Python commands.BotMissingPermissions方法的具体用法?Python commands.BotMissingPermissions怎么用?Python commands.BotMissingPermissions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord.ext.commands的用法示例。


在下文中一共展示了commands.BotMissingPermissions方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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) 
开发者ID:NullPxl,项目名称:NullCTF,代码行数:14,代码来源:nullctf.py

示例2: connect

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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) 
开发者ID:initzx,项目名称:rewrite,代码行数:32,代码来源:lavalink.py

示例3: bot_has_permissions

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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 
开发者ID:FRCDiscord,项目名称:Dozer,代码行数:28,代码来源:_utils.py

示例4: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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__))) 
开发者ID:FRCDiscord,项目名称:Dozer,代码行数:32,代码来源:bot.py

示例5: play

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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}`") 
开发者ID:initzx,项目名称:rewrite,代码行数:57,代码来源:music.py

示例6: search

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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}`") 
开发者ID:initzx,项目名称:rewrite,代码行数:52,代码来源:music.py

示例7: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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)) 
开发者ID:F4stZ4p,项目名称:DJ5n4k3,代码行数:48,代码来源:handler.py

示例8: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import BotMissingPermissions [as 别名]
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}") 
开发者ID:python-discord,项目名称:code-jam-5,代码行数:49,代码来源:error_handler.py


注:本文中的discord.ext.commands.BotMissingPermissions方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。