當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。