Python discord 模块,Permissions() 实例源码

我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用discord.Permissions()

项目:LunaBot    作者:miraai    | 项目源码 | 文件源码
def feeds_create(self, ctx, *, name : str):
        """Creates a feed with the specified name.

        You need Manage Roles permissions to create a feed.
        """
        channel = ctx.message.channel
        server = channel.server
        feeds = self.feeds.get(channel.id, {})
        name = name.lower()
        if name in feeds:
            await self.bot.say('This feed already exists.')
            return

        # create the default role
        role_name = self.library_name(channel) + ' ' + name
        role = await self.bot.create_role(server, name=role_name, permissions=discord.Permissions.none())
        feeds[name] = role.id
        await self.feeds.put(channel.id, feeds)
        await self.bot.say('The feed has been created!')
项目:PaddoCogs    作者:PaddoInWonderland    | 项目源码 | 文件源码
def server_add_role(self, server, role, color):
        if re.search(r'^(?:[0-9a-fA-F]{3}){1,2}$', color):
            color = discord.Color(int(color, 16))
            try:
                if not await self.server_has_role(server, role):
                    await self.bot.create_role(server, name=role, color=color, permissions=discord.Permissions(permissions=0), hoist=False)
                    if server.id not in self.roles:
                        self.roles[server.id] = {}
                    self.roles[server.id][role] = {}
                    await self.save_role_data()
                    return 0
                else:
                    return 3
            except discord.Forbidden:
                return 2
        else:
            return 1
项目:litecord-reference    作者:lnmds    | 项目源码 | 文件源码
def _update(self, guild, raw):
        rg = raw.get
        self.name = raw.get('name') or '@everyone'
        self.guild = guild
        self.is_default = self.guild.id == self.id

        # specific role data
        self.color = rg('color', 0)
        self.hoist = rg('hoisted', False)
        self.position = rg('position', 0)

        self.permissions = Permissions(rg('permissions', 0))
        self.perms = self.permissions

        self.managed = rg('managed', False)
        self.mentionable = rg('mentionable', False)
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def invite(self, ctx):
        """Outputs a url you can use to invite me to your server."""
        myInvite = discord.utils.oauth_url(self.bot.user.id, permissions=discord.Permissions(permissions=8))
        await self.bot.send_message(ctx.message.channel, 'Invite me to *your* server with this link: \n\n{}'.format(myInvite))
项目:Sparcli    作者:4Kaylum    | 项目源码 | 文件源码
def setcolour(self, ctx, colour:str, user:Member=None):
        '''
        Creates a new role with a given colour, and assigns it to a user
        '''

        # Fix up some variables
        server = ctx.message.server
        user = ctx.message.author if not user else user

        # Fix the colour string
        colour = colourFixer(colour)
        colourObj = Colour(int(colour, 16))
        # permissions=Permissions(permissions=0)

        # Find the role
        tempRoleFinder = [i for i in server.roles if user.id in i.name]
        if len(tempRoleFinder) > 0:
            role = tempRoleFinder[0]
            await self.sparcli.edit_role(server, role, colour=colourObj)
            created = False
        else:
            role = await self.sparcli.create_role(server, name='SPARCLI - {}'.format(user.id), colour=colourObj)
            await self.sparcli.add_roles(user, role)
            created = True

        # Print out to user
        await self.sparcli.say(
            'This role has been successfully {}. \n'
            'You may need to move the positions of other roles to make it work properly.'.format({True:'created',False:'edited'}[created])
        )
项目:Sparcli    作者:4Kaylum    | 项目源码 | 文件源码
def asetcolour(self, ctx, colour:str):
        '''
        Creates a new role with a given colour, and assigns it to yourself
        Requires enabling
        '''

        # Fix up some variables
        server = ctx.message.server
        user = ctx.message.author

        # Fix the colour string
        colour = colourFixer(colour)
        colourObj = Colour(int(colour, 16))
        # permissions=Permissions(permissions=0)

        # Find the role
        tempRoleFinder = [i for i in server.roles if user.id in i.name]
        if len(tempRoleFinder) > 0:
            role = tempRoleFinder[0]
            await self.sparcli.edit_role(server, role, colour=colourObj)
            created = False
        else:
            role = await self.sparcli.create_role(server, name='SPARCLI - {}'.format(user.id), colour=colourObj)
            await self.sparcli.add_roles(user, role)
            created = True

        # Print out to user
        await self.sparcli.say(
            'This role has been successfully {}. \n'
            'You may need to move the positions of other roles to make it work properly.'.format({True:'created',False:'edited'}[created])
        )
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def oauth_url(self):
        perms = discord.Permissions()
        perms.update(manage_roles=True,
                     manage_messages=True,
                     read_messages=True,
                     read_message_history=True,
                     send_messages=True,
                     embed_links=True,
                     change_nickname=True,
                     add_reactions=True)
        return discord.utils.oauth_url(self.bot.app.id, permissions=perms)
项目:Excalibot    作者:endreman0    | 项目源码 | 文件源码
def permission_list(self, ctx):
        """Lists all Discord permissions."""
        per_page = 9
        pages = math.ceil(len(perm_bits) / per_page)
        embeds = [discord.Embed(type='rich', title='Permissions List', color=blurple) for _ in range(pages)]
        for i, (name, bit) in enumerate(sorted(perm_bits.items(), key=operator.itemgetter(1))):
            embeds[i // per_page].add_field(name=prettify(name), value=bit)
        await react.paginate(ctx, embeds)
项目:Excalibot    作者:endreman0    | 项目源码 | 文件源码
def construct(self, ctx, *names):
        """Constructs the bit flags for the given permissions."""
        e = discord.Embed(type='rich', title='Permissions Construction', color=blurple)
        sum_ = 0
        for name, bit in sorted([(name, perm_bits[name]) for name in names], key=operator.itemgetter(1)):
            e.add_field(name=prettify(name), value=bit)
            sum_ += bit
        e.add_field(name='Sum', value=sum_, inline=False)
        await ctx.send(embed=e)
项目:Excalibot    作者:endreman0    | 项目源码 | 文件源码
def destruct(self, ctx, value : int):
        """Shows each permission in the given bit flags."""
        e = discord.Embed(type='rich', title='Permissions Deconstruction', color=blurple)
        perms = discord.Permissions(value)
        e.add_field(name='Value', value='%d (%s)' % (value, hex(value)))
        e.add_field(name='Permissions', value='```%s```' % '\n'.join(prettify(name) for name, has in perms if has), inline=False)
        await ctx.send(embed=e)
项目:Excalibot    作者:endreman0    | 项目源码 | 文件源码
def audit(self, ctx, *names):
        """Shows all roles with the given permission(s). Useful for ensuring users don't have permissions they shouldn't."""
        names = names or danger_perms
        embeds = [discord.Embed(color=blurple, title='Permissions Audit') for name in names]
        for name, e in zip(names, embeds):
            e.add_field(name=prettify(name),
                    value='```%s```' % ('\n'.join(role.name for role in ctx.guild.role_hierarchy if getattr(role.permissions, name)) or 'None'),
                    inline=False)
        await react.paginate(ctx, embeds)
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def vanity(self, ctx, name: str, color: discord.Color = None, assign_to: discord.Member = None):
        """
        Creates a vanity role.

        A vanity role is defined as a role with no permissions.
        """
        role = await ctx.guild.create_role(name=name, permissions=discord.Permissions.none(),
                                           color=color or discord.Color.default())
        if assign_to:
            try:
                await assign_to.add_roles(role)
            except discord.HTTPException:
                return await ctx.send(f"{ctx.red_tick} Couldn't give {role.name} to that person.")

        await ctx.send(f'{ctx.green_tick} Created vanity role {describe(role, quote=True)}.')
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def empty_out(self, ctx, *, role: discord.Role):
        """
        Empties out a role's permissions.

        This effectively turn it into a vanity role.
        """
        if role > ctx.guild.me.top_role:
            return await ctx.send('My position on the role hierarchy is lower than that role, so I can\'t edit it.')

        try:
            await role.edit(permissions=discord.Permissions(permissions=0))
            await ctx.ok()
        except discord.Forbidden:
            await ctx.send('I can\'t do that.')
项目:palmtree5-cogs    作者:palmtree5    | 项目源码 | 文件源码
def addnewschannel(self, ctx, channel_prefix: str=None):
        """Adds news functionality for a channel. Channel prefix is
        any part of the channel name that should not be included in
        the name of the role to be created for notifications"""
        channel = ctx.message.channel
        server = ctx.message.server
        if server.id not in self.settings:
            self.settings[server.id] = {}
        if channel.id not in self.settings[server.id]:
            self.settings[server.id][channel.id] = {}
        if channel_prefix:
            new_role_name = channel.name.replace(channel_prefix, "") +\
                " news"
        else:
            new_role_name = channel.name
        try:
            new_role = await self.bot.create_role(server, name=new_role_name,
                                                  permissions=discord.Permissions(permissions=0))
        except discord.Forbidden:
            await self.bot.say("I cannot create roles!")
            return
        except discord.HTTPException:
            await self.bot.say("Something went wrong!")
            return
        await self.bot.say("Role created!")
        self.settings[server.id][channel.id]["role_id"] = new_role.id
        self.settings[server.id][channel.id]["joined"] = []
        dataIO.save_json("data/newsannouncer/settings.json", self.settings)
项目:Bonfire    作者:Phxntxm    | 项目源码 | 文件源码
def custom_perms(**perms):
    def predicate(ctx):
        # Return true if this is a private channel, we'll handle that in the registering of the command
        if ctx.message.channel.is_private:
            return True

        # Get the member permissions so that we can compare
        member_perms = ctx.message.author.permissions_in(ctx.message.channel)
        # Next, set the default permissions if one is not used, based on what was passed
        # This will be overriden later, if we have custom permissions
        required_perm = discord.Permissions.none()
        for perm, setting in perms.items():
            setattr(required_perm, perm, setting)

        try:
            server_settings = config.cache.get('server_settings').values
            required_perm_value = [x for x in server_settings if x['server_id'] == ctx.message.server.id][0]['permissions'][ctx.command.qualified_name]
            required_perm = discord.Permissions(required_perm_value)
        except (TypeError, IndexError, KeyError):
            pass

        # Now just check if the person running the command has these permissions
        return member_perms >= required_perm

    predicate.perms = perms
    return commands.check(predicate)
项目:snake    作者:AnonymousDapper    | 项目源码 | 文件源码
def get_invite(self, ctx):
        permissions = discord.Permissions(permissions=70634561)
        await self.bot.say(f"Invite me with this link!\n{discord.utils.oauth_url('181584771510566922', permissions=permissions)}")
项目:PoiBot    作者:link2110    | 项目源码 | 文件源码
def url():
    """Generates an invite link to bring Yuudachi to your server"""
    oauth_url = discord.utils.oauth_url("181157059130163207", permissions=discord.Permissions.all())
    msg = "Please use this link to add me to your server, Poi~ \n{}".format(oauth_url)
    await bot.say(msg)
项目:PoiBot    作者:link2110    | 项目源码 | 文件源码
def on_server_join(server):
    """Create the Admin role, Muted role, and then add Muted perms to every channel, given correct perms."""
    await bot.create_role(server, name="Poi's Admiral")
    muted = await bot.create_role(server, name="Muted", permissions=discord.Permissions(permissions=1115136))
    await make_muted_perms(server, muted)
    await bot.send_message(server, "Hello! I'm a bot invited to the server to make your life a little easier and more fun! Please move the `Yuudachi Kai` role to underneath your Admin role and then move the `Muted` role underneath that so that I can mute people properly! Everything else has been set up already if you gave me the `Administrator` permission. Thanks!")
项目:ModTools    作者:MattBSG    | 项目源码 | 文件源码
def cmd_slowmode(self, message, author, server, channel_id, time_between, reason=None):
        """
        Usage: {command_prefix}slowmode #channel <time between messages> ["reason"]
        Puts the channel mentioned into a slowmode where users can only send messages every x seconds.
        To turn slow mode off, set the time between messages to "0"
        """
        if await self.has_roles(message.channel, author, server, command='slowmode'):
            if channel_id in self.server_index[message.server.id][12]:
                raise CommandError('ERROR: Channel ID is ignored. Unignore the channel before setting to slow mode')
            try:
                time_between = int(time_between)
            except:
                raise CommandError('ERROR: The time limit between messages isn\'t a number, please specify a real number')
            try:
                if channel_id in self.slow_mode_dict.keys():
                    if time_between == 0:
                        await self.delete_role(server, self.slow_mode_dict[channel_id]['channel_muted_role'])
                        del self.slow_mode_dict[channel_id]
                        await self.safe_send_message(discord.Object(channel_id), 'This channel is no longer in slow mode!')
                    else:
                        self.slow_mode_dict[channel_id]['time_between'] = time_between
                        await self.safe_send_message(discord.Object(channel_id), 'The delay between allowed messages is now **%s seconds**!' % time_between)
                else:
                    slowed_channel = discord.utils.get(server.channels, id=channel_id)
                    channel_muted_role = await self.create_role(server,
                                                                name=slowed_channel.name + 'SLOWROLE',
                                                                permissions=discord.Permissions(permissions=66560))
                    overwrite = discord.PermissionOverwrite()
                    overwrite.read_messages = True
                    overwrite.send_messages = False
                    await self.edit_channel_permissions(slowed_channel, channel_muted_role, overwrite)
                    await self.safe_send_message(discord.Object(channel_id), 'This channel is now in slow mode with a delay of **%s seconds**!' % time_between)
                    self.slow_mode_dict[channel_id] = {'time_between': time_between,
                                                       'channel_muted_role': channel_muted_role}
                await self.write_to_modlog(message, author, server, reason)
            except:
                raise CommandError('ERROR: Please make sure the syntax is correct and resubmit the command!')
项目:ModTools    作者:MattBSG    | 项目源码 | 文件源码
def cmd_url(self):
        """
        blahblahblah
        """
        return Response('Here is my OAuth URL!:\n<{}>'
                        ''.format(discord.utils.oauth_url(BOT_USER_ACCOUNT, permissions=discord.Permissions.all())),
                        reply=True)
项目:ModTools    作者:MattBSG    | 项目源码 | 文件源码
def cmd_joinserver(self):
        """
        Usage {command_prefix}joinserver [Server Link]
        Asks the bot to join a server.
        """
        return Response('I am quite happy you would like me to join one of your servers! Just remember that to function properly, I must have **administrator** permissions. Here is my invite link:\n<{}>'
                        ''.format(discord.utils.oauth_url(BOT_USER_ACCOUNT, permissions=discord.Permissions.all())),
                        reply=True)
项目:Squid-Plugins    作者:tekulvw    | 项目源码 | 文件源码
def initial_linker(self, master, slave):
        master = discord.utils.get(self.bot.servers, id=master)
        slave = discord.utils.get(self.bot.servers, id=slave)
        if master is None or slave is None:
            return

        my_role = discord.utils.find(lambda r: r.name.lower() == "squid",
                                     slave.roles)
        if my_role is None:
            role_dict = {}
            role_dict['permissions'] = \
                discord.Permissions(permissions=36826127)
            role_dict['name'] = "Squid"
            my_server_role = await self.bot.create_role(slave, **role_dict)
            await self.bot.add_roles(slave.me, my_server_role)

        log.debug('Slave roles:\n\t{}'.format(
            [role.name for role in slave.roles]))

        await self._delete_all_roles(slave)

        log.debug('Slave roles:\n\t{}'.format(
            [role.name for role in slave.roles]))

        await self._create_all_roles(slave, master)

        # We only really care about the online people, this way we *hopefully*
        # don't get ourselves rate-limited on large servers.

        online_master_members = [m for m in master.members
                                 if m.status == discord.Status.online]
        omm_withrole = [m for m in online_master_members if len(m.roles) > 1]
        ommwr_in_slave = [m for m in omm_withrole if m in slave.members]

        log.debug('members to give role to RN:\n\t{}'.format(
            [m.name for m in ommwr_in_slave]))

        for m in ommwr_in_slave:
            slave_member = discord.utils.get(slave.members, id=m.id)
            to_add = []
            for mrole in m.roles:
                if mrole.name.lower() == "@everyone" \
                        or mrole.name.lower() == "squid":
                    continue
                log.debug(self._matching_role(slave, mrole))
                to_add.append(self._matching_role(slave, mrole))
            log.debug('adding roles to {0.name} on {1.id}:\n\t{2}'.format(
                slave_member, slave, [r.name for r in to_add]))
            discord.compat.create_task(
                self.bot.add_roles(slave_member, *to_add))
项目:Bonfire    作者:Phxntxm    | 项目源码 | 文件源码
def perms(self, ctx, *, command: str = None):
        """This command can be used to print the current allowed permissions on a specific command
        This supports groups as well as subcommands; pass no argument to print a list of available permissions
        EXAMPLE: !perms help RESULT: Hopefully a result saying you just need send_messages permissions; otherwise lol
        this server's admin doesn't like me """
        if command is None:
            await self.bot.say(
                "Valid permissions are: ```\n{}```".format("\n".join("{}".format(i) for i in valid_perms)))
            return

        cmd = utils.find_command(self.bot, command)

        if cmd is None:
            await self.bot.say("That is not a valid command!")
            return

        server_settings = await utils.get_content('server_settings', ctx.message.server.id)
        try:
            server_perms = server_settings['permissions']
        except (TypeError, IndexError, KeyError):
            server_perms = {}

        perms_value = server_perms.get(cmd.qualified_name)
        if perms_value is None:
            # If we don't find custom permissions, get the required permission for a command
            # based on what we set in utils.custom_perms, if custom_perms isn't found, we'll get an IndexError
            try:
                custom_perms = [func for func in cmd.checks if "custom_perms" in func.__qualname__][0]
            except IndexError:
                # Loop through and check if there is a check called is_owner
                # If we loop through and don't find one, this means that the only other choice is to be
                # Able to manage the server (for the utils on perm commands)
                for func in cmd.checks:
                    if "is_owner" in func.__qualname__:
                        await self.bot.say("You need to own the bot to run this command")
                        return
                await self.bot.say(
                    "You are required to have `manage_server` permissions to run `{}`".format(cmd.qualified_name))
                return

            # Perms will be an attribute if custom_perms is found no matter what, so no need to check this
            perms = "\n".join(attribute for attribute, setting in custom_perms.perms.items() if setting)
            await self.bot.say(
                "You are required to have `{}` permissions to run `{}`".format(perms, cmd.qualified_name))
        else:
            # Permissions are saved as bit values, so create an object based on that value
            # Then check which permission is true, that is our required permission
            # There's no need to check for errors here, as we ensure a permission is valid when adding it
            permissions = discord.Permissions(perms_value)
            needed_perm = [perm[0] for perm in permissions if perm[1]][0]
            await self.bot.say("You need to have the permission `{}` "
                               "to use the command `{}` in this server".format(needed_perm, command))
项目:Bonfire    作者:Phxntxm    | 项目源码 | 文件源码
def add_perms(self, ctx, *msg: str):
        """Sets up custom permissions on the provided command
        Format must be 'perms add <command> <permission>'
        If you want to open the command to everyone, provide 'none' as the permission
        EXAMPLE: !perms add skip ban_members
        RESULT: No more random people voting to skip a song"""

        # Since subcommands exist, base the last word in the list as the permission, and the rest of it as the command
        command = " ".join(msg[0:len(msg) - 1])
        try:
            permissions = msg[len(msg) - 1]
        except IndexError:
            await self.bot.say("Please provide the permissions you want to setup, the format for this must be in:\n"
                               "`perms add <command> <permission>`")
            return

        cmd = utils.find_command(self.bot, command)

        if cmd is None:
            await self.bot.say(
                "That command does not exist! You can't have custom permissions on a non-existant command....")
            return

        # If a user can run a command, they have to have send_messages permissions; so use this as the base
        if permissions.lower() == "none":
            permissions = "send_messages"

        # Convert the string to an int value of the permissions object, based on the required permission
        # If we hit an attribute error, that means the permission given was not correct
        perm_obj = discord.Permissions.none()
        try:
            setattr(perm_obj, permissions, True)
        except AttributeError:
            await self.bot.say("{} does not appear to be a valid permission! Valid permissions are: ```\n{}```"
                               .format(permissions, "\n".join(valid_perms)))
            return
        perm_value = perm_obj.value

        # Two cases I use should never have custom permissions setup on them, is_owner for obvious reasons
        # The other case is if I'm using the default has_permissions case
        # Which means I do not want to check custom permissions at all
        # Currently the second case is only on adding and removing permissions, to avoid abuse on these
        for check in cmd.checks:
            if "is_owner" == check.__name__ or "has_permissions" in str(check):
                await self.bot.say("This command cannot have custom permissions setup!")
                return

        key = ctx.message.server.id
        entry = {'server_id': key,
                 'permissions': {cmd.qualified_name: perm_value}}

        if not await utils.update_content('server_settings', entry, key):
            await utils.add_content('server_settings', entry)

        await self.bot.say("I have just added your custom permissions; "
                           "you now need to have `{}` permissions to use the command `{}`".format(permissions, command))