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


Python discord.Permissions方法代码示例

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


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

示例1: __init__

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def __init__(self, **kwargs) -> None:
        default_kwargs = {
            'id': next(self.discord_id),
            'name': 'role',
            'position': 1,
            'colour': discord.Colour(0xdeadbf),
            'permissions': discord.Permissions(),
        }
        super().__init__(**collections.ChainMap(kwargs, default_kwargs))

        if isinstance(self.colour, int):
            self.colour = discord.Colour(self.colour)

        if isinstance(self.permissions, int):
            self.permissions = discord.Permissions(self.permissions)

        if 'mention' not in kwargs:
            self.mention = f'&{self.name}' 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:helpers.py

示例2: assertHasPermissionsCheck

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def assertHasPermissionsCheck(  # noqa: N802
        self,
        cmd: commands.Command,
        permissions: Dict[str, bool],
    ) -> None:
        """
        Test that `cmd` raises a `MissingPermissions` exception if author lacks `permissions`.

        Every permission in `permissions` is expected to be reported as missing. In other words, do
        not include permissions which should not raise an exception along with those which should.
        """
        # Invert permission values because it's more intuitive to pass to this assertion the same
        # permissions as those given to the check decorator.
        permissions = {k: not v for k, v in permissions.items()}

        ctx = helpers.MockContext()
        ctx.channel.permissions_for.return_value = discord.Permissions(**permissions)

        with self.assertRaises(commands.MissingPermissions) as cm:
            await cmd.can_run(ctx)

        self.assertCountEqual(permissions.keys(), cm.exception.missing_perms) 
开发者ID:python-discord,项目名称:bot,代码行数:24,代码来源:base.py

示例3: invite

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def invite(self, context):
		"""Gives you a link to add me to your server."""
		# these are the same as the attributes of discord.Permissions
		permission_names = (
			'read_messages',
			'send_messages',
			'read_message_history',
			'external_emojis',
			'add_reactions',
			'manage_messages',
			'embed_links')
		permissions = discord.Permissions()
		permissions.update(**dict.fromkeys(permission_names, True))
		# XXX technically this will fail if the bot's client ID is not the same as its user ID
		# but fuck old apps just make a new one
		await context.send('<%s>' % discord.utils.oauth_url(self.bot.user.id, permissions))

	# heavily based on code provided by Rapptz, © 2015 Rapptz
	# https://github.com/Rapptz/RoboDanny/blob/8919ec0a455f957848ef77b479fe3494e76f0aa7/cogs/meta.py#L162-L190 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:21,代码来源:meta.py

示例4: __init__

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def __init__(self, **kwargs):
        self.default_prefix = config.bot_prefix
        self.owner = config.bot_master
        self._shutdown_mode = ExitCodes.CRITICAL
        self.counter = Counter()
        self.core_dir = os.path.dirname(os.path.realpath(__file__))
        self.config = config
        self.default_prefix = config.bot_prefix[0]
        self.prefixes = {}
        self.bot_users = []
        self.repeat_offender = []
        self.last_command = None
        self.token = config.bot_token
        self.req_perms = discord.Permissions(config.bot_permissions)
        self.co_owners = config.bot_coowners
        self.preload_ext = config.preload_extensions
        kwargs["command_prefix"] = prefix_manager
        kwargs["pm_help"] = True
        # kwargs["command_prefix"] = self.db.prefix_manager
        kwargs["owner_id"] = self.owner
        super().__init__(**kwargs)
        self.session = aiohttp.ClientSession(loop=self.loop)
        self.esi_data = ESI(self.session)
        self.loop.create_task(self.load_db()) 
开发者ID:shibdib,项目名称:Firetail,代码行数:26,代码来源:bot.py

示例5: get_guild

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def get_guild(*roles):
        """Fixture to return a guild object with the given roles."""
        guild = helpers.MockGuild()
        guild.roles = []

        for role in roles:
            mock_role = helpers.MockRole(**role)
            mock_role.colour = discord.Colour(role["colour"])
            mock_role.permissions = discord.Permissions(role["permissions"])
            guild.roles.append(mock_role)

        return guild 
开发者ID:python-discord,项目名称:bot,代码行数:14,代码来源:test_roles.py

示例6: _load_roles

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def _load_roles(self):
        log.debug(f"Loading roles on {self.guild.id}")
        existing_roles = list(reversed(list(filter(
            lambda r: not r.managed and not r.is_default()
                      and self.guild.me.top_role.position > r.position,
            self.guild.roles
        ))))
        for role in reversed(self.data["roles"]):
            try:
                if role["default"]:
                    await self.guild.default_role.edit(
                        permissions=discord.Permissions(role["permissions"])
                    )
                    new_role = self.guild.default_role
                else:
                    kwargs = {
                        "name": role["name"],
                        "hoist": role["hoist"],
                        "mentionable": role["mentionable"],
                        "color": discord.Color(role["color"]),
                        "permissions": discord.Permissions.none(),
                        "reason": self.reason
                    }

                    if len(existing_roles) == 0:
                        try:
                            new_role = await asyncio.wait_for(self.guild.create_role(**kwargs), 10)
                        except asyncio.TimeoutError:
                            # Probably hit the 24h rate limit. Just skip roles
                            break
                    else:
                        new_role = existing_roles.pop(0)
                        await new_role.edit(**kwargs)

                self.id_translator[role["id"]] = new_role.id
            except Exception:
                pass 
开发者ID:Xenon-Bot,项目名称:xenon,代码行数:39,代码来源:backups.py

示例7: _load_role_permissions

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def _load_role_permissions(self):
        tasks = []
        for role in self.data["roles"]:
            to_edit = self.guild.get_role(self.id_translator.get(role["id"]))
            if to_edit:
                tasks.append(to_edit.edit(permissions=discord.Permissions(role["permissions"])))

        await self.run_tasks(tasks) 
开发者ID:Xenon-Bot,项目名称:xenon,代码行数:10,代码来源:backups.py

示例8: invite

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def invite(self):
        invite = self.config.invite_url
        if not invite:
            invite = discord.utils.oauth_url(
                client_id=self.user.id,
                permissions=discord.Permissions(8)
            )

        return invite 
开发者ID:Xenon-Bot,项目名称:xenon,代码行数:11,代码来源:bot.py

示例9: overwrite_from_dict

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def overwrite_from_dict(data):
    allow = discord.Permissions(data.get('allow', 0))
    deny = discord.Permissions(data.get('deny', 0))
    return discord.PermissionOverwrite.from_pair(allow, deny) 
开发者ID:calebj,项目名称:calebj-cogs,代码行数:6,代码来源:punish.py

示例10: generate_invite_link

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def generate_invite_link(self, *, permissions=discord.Permissions(70380544), guild=None):
        return discord.utils.oauth_url(self.cached_app_info.id, permissions=permissions, guild=guild) 
开发者ID:helionmusic,项目名称:rhinobot_heroku,代码行数:4,代码来源:bot.py

示例11: author_permissions

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def author_permissions(self) -> discord.Permissions:
        """Shortcut to check the command author's permission to the current channel.

        :return: The permissions for the author in the current channel.
        """
        return self.channel.permissions_for(self.author) 
开发者ID:NabDev,项目名称:NabBot,代码行数:8,代码来源:context.py

示例12: bot_permissions

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def bot_permissions(self) -> discord.Permissions:
        """Shortcut to check the bot's permission to the current channel.

        :return: The permissions for the author in the current channel."""
        return self.channel.permissions_for(self.me) 
开发者ID:NabDev,项目名称:NabBot,代码行数:7,代码来源:context.py

示例13: get_current_channel

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def get_current_channel(ctx: NabCtx, current_channel_id, *, pm_fallback=False, default_name=None):
        """Displays information about the current stored channel.

        :param ctx: The command context where this is called from.
        :param current_channel_id: The currently saved id.
        :param pm_fallback: Whether this falls back to PMs if the channel is invalid.
        :param default_name: Whether this falls back to a channel with a certain name.
        :return: A string representing the current state.
        """
        top_channel = ctx.bot.get_top_channel(ctx.guild)
        current_channel = ctx.guild.get_channel(current_channel_id)
        if current_channel:
            perms = current_channel.permissions_for(ctx.me)
        else:
            perms = discord.Permissions()
        if current_channel_id is None and pm_fallback:
            return "Private Messages"
        elif current_channel_id == 0:
            return "Disabled."
        elif current_channel_id is None:
            current_value = "None."
        elif current_channel is None:
            current_value = "None, previous channel was deleted."
        elif not perms.read_messages or not perms.send_messages:
            current_value = f"{current_channel.mention}, but I can't use the channel."
        else:
            return f"{current_channel.mention}"

        if pm_fallback:
            current_value += " I will send direct messages meanwhile."
        # This condition should be impossible to meet, because if the bot can't send messages on any channel,
        # it wouldn't be able to reply to this command in the first place ¯\_(ツ)_/¯
        elif top_channel is None:
            current_value += " I have no channel to use."
        elif default_name:
            current_value += f" By default I will use any channel named {default_name}."
        else:
            current_value += f" I will use {top_channel.mention} meanwhile."
        return current_value 
开发者ID:NabDev,项目名称:NabBot,代码行数:41,代码来源:admin.py

示例14: get_guild_invite

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def get_guild_invite(guild: discord.Guild, max_age: int = 86400) -> None:
        """Handles the reinvite logic for getting an invite
        to send the newly unbanned user
        :returns: :class:`Invite`

        https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/cogs/mod/mod.py#L771
        """
        my_perms: discord.Permissions = guild.me.guild_permissions
        if my_perms.manage_guild or my_perms.administrator:
            if "VANITY_URL" in guild.features:
                # guild has a vanity url so use it as the one to send
                return await guild.vanity_invite()
            invites = await guild.invites()
        else:
            invites = []
        for inv in invites:  # Loop through the invites for the guild
            if not (inv.max_uses or inv.max_age or inv.temporary):
                # Invite is for the guild's default channel,
                # has unlimited uses, doesn't expire, and
                # doesn't grant temporary membership
                # (i.e. they won't be kicked on disconnect)
                return inv
        else:  # No existing invite found that is valid
            channels_and_perms = zip(
                guild.text_channels, map(guild.me.permissions_in, guild.text_channels)
            )
            channel = next(
                (channel for channel, perms in channels_and_perms if perms.create_instant_invite),
                None,
            )
            if channel is None:
                return
            try:
                # Create invite that expires after max_age
                return await channel.create_invite(max_age=max_age)
            except discord.HTTPException:
                return 
开发者ID:TrustyJAID,项目名称:Trusty-cogs,代码行数:39,代码来源:serverstats.py

示例15: on_member_join

# 需要导入模块: import discord [as 别名]
# 或者: from discord import Permissions [as 别名]
def on_member_join(self, member):
        """Restores a member's roles when they join if they have joined before."""
        me = member.guild.me
        top_restorable = me.top_role.position if me.guild_permissions.manage_roles else 0
        restore = await MissingRole.get_by(guild_id=member.guild.id, member_id=member.id)
        if len(restore) == 0:
            return  # New member - nothing to restore

        valid, cant_give, missing = set(), set(), set()
        for missing_role in restore:
            role = member.guild.get_role(missing_role.role_id)
            if role is None:  # Role with that ID does not exist
                missing.add(missing_role.role_name)
            elif role.position > top_restorable:
                cant_give.add(role.name)
            else:
                valid.add(role)
        for entry in restore:
            # Not missing anymore - remove the record to free up the primary key
            await MissingRole.delete(role_id=entry.role_id, member_id=entry.member_id)

        await member.add_roles(*valid)
        if not missing and not cant_give:
            return

        e = discord.Embed(title='Welcome back to the {} server, {}!'.format(member.guild.name, member),
                          color=discord.Color.blue())
        if missing:
            e.add_field(name='I couldn\'t restore these roles, as they don\'t exist.', value='\n'.join(sorted(missing)))
        if cant_give:
            e.add_field(name='I couldn\'t restore these roles, as I don\'t have permission.',
                        value='\n'.join(sorted(cant_give)))

        send_perms = discord.Permissions()
        send_perms.update(send_messages=True, embed_links=True)
        try:
            dest = next(channel for channel in member.guild.text_channels if channel.permissions_for(me) >= send_perms)
        except StopIteration:
            dest = await member.guild.owner.create_dm()

        await dest.send(embed=e) 
开发者ID:FRCDiscord,项目名称:Dozer,代码行数:43,代码来源:roles.py


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