Python discord.Permissions() Examples
The following are 25
code examples of discord.Permissions().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
discord
, or try the search function
.
Example #1
Source File: bot.py From Firetail with MIT License | 7 votes |
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())
Example #2
Source File: base.py From bot with MIT License | 6 votes |
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)
Example #3
Source File: helpers.py From bot with MIT License | 6 votes |
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}'
Example #4
Source File: _utils.py From Dozer with GNU General Public License v3.0 | 5 votes |
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
Example #5
Source File: _utils.py From Dozer with GNU General Public License v3.0 | 5 votes |
def required_permissions(self): """Required permissions handler""" if self._required_permissions is None: self._required_permissions = discord.Permissions() return self._required_permissions
Example #6
Source File: general.py From Dozer with GNU General Public License v3.0 | 5 votes |
def invite(self, ctx): """ Display the bot's invite link. The generated link gives all permissions the bot requires. If permissions are removed, some commands will be unusable. """ perms = 0 for cmd in ctx.bot.walk_commands(): perms |= cmd.required_permissions.value await ctx.send('<{}>'.format(discord.utils.oauth_url(ctx.me.id, discord.Permissions(perms))))
Example #7
Source File: roles.py From Dozer with GNU General Public License v3.0 | 5 votes |
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)
Example #8
Source File: bot.py From MusicBot with MIT License | 5 votes |
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)
Example #9
Source File: serverstats.py From Trusty-cogs with MIT License | 5 votes |
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
Example #10
Source File: admin.py From NabBot with Apache License 2.0 | 5 votes |
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
Example #11
Source File: context.py From NabBot with Apache License 2.0 | 5 votes |
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)
Example #12
Source File: context.py From NabBot with Apache License 2.0 | 5 votes |
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)
Example #13
Source File: bot.py From rhinobot_heroku with MIT License | 5 votes |
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)
Example #14
Source File: meta.py From EmoteCollector with GNU Affero General Public License v3.0 | 5 votes |
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
Example #15
Source File: punish.py From calebj-cogs with GNU General Public License v3.0 | 5 votes |
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)
Example #16
Source File: bot.py From xenon with GNU General Public License v3.0 | 5 votes |
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
Example #17
Source File: backups.py From xenon with GNU General Public License v3.0 | 5 votes |
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)
Example #18
Source File: backups.py From xenon with GNU General Public License v3.0 | 5 votes |
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
Example #19
Source File: test_roles.py From bot with MIT License | 5 votes |
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
Example #20
Source File: hublinker.py From Squid-Plugins with MIT License | 4 votes |
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))
Example #21
Source File: punish.py From calebj-cogs with GNU General Public License v3.0 | 4 votes |
def get_role(self, server, quiet=False, create=False): default_name = DEFAULT_ROLE_NAME role_id = self.json.get(server.id, {}).get('ROLE_ID') if role_id: role = discord.utils.get(server.roles, id=role_id) else: role = discord.utils.get(server.roles, name=default_name) if create and not role: perms = server.me.server_permissions if not perms.manage_roles and perms.manage_channels: await self.bot.say("The Manage Roles and Manage Channels permissions are required to use this command.") return else: msg = "The %s role doesn't exist; Creating it now..." % default_name msgobj = None if not quiet: msgobj = await self.bot.reply(msg) log.debug('Creating punish role in %s' % server.name) perms = discord.Permissions.none() role = await self.bot.create_role(server, name=default_name, permissions=perms) await self.bot.move_role(server, role, server.me.top_role.position - 1) if not quiet: msgobj = await self.bot.edit_message(msgobj, msgobj.content + 'configuring channels... ') for channel in server.channels: await self.setup_channel(channel, role) if not quiet: await self.bot.edit_message(msgobj, msgobj.content + 'done.') if role and role.id != role_id: if server.id not in self.json: self.json[server.id] = {} self.json[server.id]['ROLE_ID'] = role.id self.save() return role # Legacy command stubs
Example #22
Source File: punish.py From calebj-cogs with GNU General Public License v3.0 | 4 votes |
def punishset_setup(self, ctx): """ (Re)configures the punish role and channel overrides """ server = ctx.message.server default_name = DEFAULT_ROLE_NAME role_id = self.json.get(server.id, {}).get('ROLE_ID') if role_id: role = discord.utils.get(server.roles, id=role_id) else: role = discord.utils.get(server.roles, name=default_name) perms = server.me.server_permissions if not (perms.manage_roles and perms.manage_channels): await self.bot.say("I need the Manage Roles and Manage Channels permissions for that command to work.") return if not role: msg = "The %s role doesn't exist; Creating it now... " % default_name msgobj = await self.bot.say(msg) perms = discord.Permissions.none() role = await self.bot.create_role(server, name=default_name, permissions=perms) else: msgobj = await self.bot.say('%s role exists... ' % role.name) if role.position != (server.me.top_role.position - 1): if role < server.me.top_role: msgobj = await self.bot.edit_message(msgobj, msgobj.content + 'moving role to higher position... ') await self.bot.move_role(server, role, server.me.top_role.position - 1) else: await self.bot.edit_message(msgobj, msgobj.content + 'role is too high to manage.' ' Please move it to below my highest role.') return msgobj = await self.bot.edit_message(msgobj, msgobj.content + '(re)configuring channels... ') for channel in server.channels: await self.setup_channel(channel, role) await self.bot.edit_message(msgobj, msgobj.content + 'done.') if role and role.id != role_id: if server.id not in self.json: self.json[server.id] = {} self.json[server.id]['ROLE_ID'] = role.id self.save()
Example #23
Source File: reportspin.py From Trusty-cogs with MIT License | 4 votes |
def discover_guild( self, author: discord.User, *, mod: bool = False, permissions: Union[discord.Permissions, dict] = None, prompt: str = "", ): """ discovers which of shared guilds between the bot and provided user based on conditions (mod or permissions is an or) prompt is for providing a user prompt for selection """ shared_guilds = [] if permissions is None: perms = discord.Permissions() elif isinstance(permissions, discord.Permissions): perms = permissions else: perms = discord.Permissions(**permissions) for guild in self.bot.guilds: x = guild.get_member(author.id) if x is not None: if await self.internal_filter(x, mod, perms): shared_guilds.append(guild) if len(shared_guilds) == 0: raise ValueError("No Qualifying Shared Guilds") if len(shared_guilds) == 1: return shared_guilds[0] output = "" guilds = sorted(shared_guilds, key=lambda g: g.name) for i, guild in enumerate(guilds, 1): output += "{}: {}\n".format(i, guild.name) output += "\n{}".format(prompt) for page in pagify(output, delims=["\n"]): await author.send(box(page)) try: message = await self.bot.wait_for( "message", check=MessagePredicate.same_context(channel=author.dm_channel, user=author), timeout=45, ) except asyncio.TimeoutError: await author.send(_("You took too long to select. Try again later.")) return None try: message = int(message.content.strip()) guild = guilds[message - 1] except (ValueError, IndexError): await author.send(_("That wasn't a valid choice.")) return None else: return guild
Example #24
Source File: punish.py From calebj-cogs with GNU General Public License v3.0 | 4 votes |
def permissions_for_roles(channel: discord.Channel, *roles: discord.Role): """ Calculates the effective permissions for a role or combination of roles. Naturally, if no roles are given, the default role's permissions are used """ default = channel.server.default_role base = discord.Permissions(default.permissions.value) # Apply all role values for role in roles: base.value |= role.permissions.value # Server-wide Administrator -> True for everything # Bypass all channel-specific overrides if base.administrator: return discord.Permissions.all() role_ids = set(map(lambda r: r.id, roles)) denies = 0 allows = 0 # Apply channel specific role permission overwrites # noinspection PyProtectedMember for overwrite in channel._permission_overwrites: # Handle default role first, if present if overwrite.id == default.id: base.handle_overwrite(allow=overwrite.allow, deny=overwrite.deny) if overwrite.type == 'role' and overwrite.id in role_ids: denies |= overwrite.deny allows |= overwrite.allow base.handle_overwrite(allow=allows, deny=denies) # default channels can always be read if channel.is_default: base.read_messages = True # if you can't send a message in a channel then you can't have certain # permissions as well if not base.send_messages: base.send_tts_messages = False base.mention_everyone = False base.embed_links = False base.attach_files = False # if you can't read a channel then you have no permissions there if not base.read_messages: denied = discord.Permissions.all_channel() base.value &= ~denied.value # text channels do not have voice related permissions if channel.type is discord.ChannelType.text: denied = discord.Permissions.voice() base.value &= ~denied.value return base
Example #25
Source File: test_information.py From bot with MIT License | 4 votes |
def test_role_info_command(self): """Tests the `role info` command.""" dummy_role = helpers.MockRole( name="Dummy", id=112233445566778899, colour=discord.Colour.blurple(), position=10, members=[self.ctx.author], permissions=discord.Permissions(0) ) admin_role = helpers.MockRole( name="Admins", id=998877665544332211, colour=discord.Colour.red(), position=3, members=[self.ctx.author], permissions=discord.Permissions(0), ) self.ctx.guild.roles.append([dummy_role, admin_role]) self.cog.role_info.can_run = unittest.mock.AsyncMock() self.cog.role_info.can_run.return_value = True coroutine = self.cog.role_info.callback(self.cog, self.ctx, dummy_role, admin_role) self.assertIsNone(asyncio.run(coroutine)) self.assertEqual(self.ctx.send.call_count, 2) (_, dummy_kwargs), (_, admin_kwargs) = self.ctx.send.call_args_list dummy_embed = dummy_kwargs["embed"] admin_embed = admin_kwargs["embed"] self.assertEqual(dummy_embed.title, "Dummy info") self.assertEqual(dummy_embed.colour, discord.Colour.blurple()) self.assertEqual(dummy_embed.fields[0].value, str(dummy_role.id)) self.assertEqual(dummy_embed.fields[1].value, f"#{dummy_role.colour.value:0>6x}") self.assertEqual(dummy_embed.fields[2].value, "0.63 0.48 218") self.assertEqual(dummy_embed.fields[3].value, "1") self.assertEqual(dummy_embed.fields[4].value, "10") self.assertEqual(dummy_embed.fields[5].value, "0") self.assertEqual(admin_embed.title, "Admins info") self.assertEqual(admin_embed.colour, discord.Colour.red())