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