Python discord.PermissionOverwrite() Examples

The following are 17 code examples of discord.PermissionOverwrite(). 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: temproom.py    From apex-sigma-core with GNU General Public License v3.0 8 votes vote down vote up
def temproom(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    room_name = ' '.join(pld.args) or f'{pld.msg.author.display_name}\'s Room'
    room_name = f'[Σ] {room_name}'
    reason = f'Temporary voice channel by {pld.msg.author.name}#{pld.msg.author.discriminator}.'
    temp_vc_cat = await get_category(cmd, pld.msg.guild)
    if pld.msg.guild.me.permissions_in(temp_vc_cat).manage_channels:
        perms = {'manage_channels': True, 'manage_roles': True, 'read_messages': True, 'connect': True, 'speak': True}
        overwrites = {pld.msg.author: discord.PermissionOverwrite(**perms)}
        await pld.msg.guild.create_voice_channel(room_name, reason=reason, overwrites=overwrites, category=temp_vc_cat)
        response = ok(f'{room_name} created.')
    else:
        response = error('I can\'t create channels in that category.')
    await pld.msg.channel.send(embed=response) 
Example #2
Source File: infochannel.py    From Fox-V3 with GNU Affero General Public License v3.0 7 votes vote down vote up
def make_infochannel(self, guild: discord.Guild):
        botcount = await self.config.guild(guild).bot_count()
        onlinecount = await self.config.guild(guild).online_count()
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(connect=False),
            guild.me: discord.PermissionOverwrite(manage_channels=True, connect=True),
        }

        channel = await guild.create_voice_channel(
            "Placeholder", reason="InfoChannel make", overwrites=overwrites
        )
        await self.config.guild(guild).channel_id.set(channel.id)

        if botcount:
            botchannel = await guild.create_voice_channel(
                "Placeholder", reason="InfoChannel botcount", overwrites=overwrites
            )
            await self.config.guild(guild).botchannel_id.set(botchannel.id)
        if onlinecount:
            onlinechannel = await guild.create_voice_channel(
                "Placeholder", reason="InfoChannel onlinecount", overwrites=overwrites
            )
            await self.config.guild(guild).onlinechannel_id.set(onlinechannel.id)

        await self.update_infochannel(guild) 
Example #3
Source File: roomhost.py    From discord-roombot with GNU General Public License v3.0 6 votes vote down vote up
def voice_channel(self, ctx, *args):
        c = self.get_context(ctx, args)
        if c.voice_channel:
            await c.voice_channel.delete()
            await ctx.send(c.settings.get_text('deleted_voice_channel'))
        else:
            category = await get_rooms_category(ctx.guild, c.settings)
            voice_channel = await ctx.guild.create_voice_channel(
                c.room.activity,
                category=category,
                position=0,
                bitrate=c.settings.bitrate * 1000, 
                overwrites={
                    ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
                    ctx.guild.me: discord.PermissionOverwrite(move_members=True),
                    c.role: discord.PermissionOverwrite(read_messages=True) })
            c.room.update('voice_channel_id', voice_channel.id)
            await ctx.send(c.settings.get_text('new_voice_channel').format(voice_channel.name)) 
Example #4
Source File: backups.py    From xenon with GNU General Public License v3.0 6 votes vote down vote up
def _overwrites_from_json(self, json):
        overwrites = {}
        for union_id, overwrite in json.items():
            try:
                union = await self.guild.fetch_member(int(union_id))
            except discord.NotFound:
                roles = list(
                    filter(lambda r: r.id == self.id_translator.get(union_id), self.guild.roles))
                if len(roles) == 0:
                    continue

                union = roles[0]

            overwrites[union] = discord.PermissionOverwrite(**overwrite)

        return overwrites 
Example #5
Source File: configuration.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, bot):
        self.bot = bot
        self.role_permission = discord.PermissionOverwrite(
            read_messages=True,
            read_message_history=True,
            send_messages=True,
            embed_links=True,
            attach_files=True,
            add_reactions=True,
        )
        self.default_role_permission = discord.PermissionOverwrite(read_messages=False) 
Example #6
Source File: punish.py    From calebj-cogs with GNU General Public License v3.0 5 votes vote down vote up
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 #7
Source File: Moderation.py    From NotSoBot with MIT License 5 votes vote down vote up
def mute(self, ctx, *users:discord.User):
		"""Mute a User"""
		if ctx.message.server.me.permissions_in(ctx.message.channel).manage_channels == False:
			await self.bot.say("Sorry, I do not have the manage_channels permission\n**Aborting**")
			return
		for user in users:
			if ctx.message.author.permissions_in(ctx.message.channel).administrator:
				await self.bot.say(':no_entry: `{0}` cannot be muted.'.format(user))
				continue
			if ctx.message.server in self.muted_users:
				if user in self.muted_users[ctx.message.server]:
					await self.bot.say('`{0}` is already muted!'.format(user))
					continue
			count = 0
			for channel in ctx.message.server.channels:
				perms = user.permissions_in(channel)
				if perms.read_messages == False:
					continue
				overwrite = discord.PermissionOverwrite()
				overwrite.send_messages = False
				try:
					await self.bot.edit_channel_permissions(channel, user, overwrite)
					await asyncio.sleep(0.21)
					count += 1
				except:
					if count == 0:
						await self.bot.say(":no_entry: Bot does not have permission")
						return
					continue
			if ctx.message.server.id not in self.muted_users:
				self.muted_users[ctx.message.server] = [user]
			else:
				self.muted_users[ctx.message.server] += user
			await self.bot.say("ok, muted `{0}`".format(user)) 
Example #8
Source File: channelmanager.py    From SML-Cogs with MIT License 5 votes vote down vote up
def create_user(self, ctx, name, user: discord.Member, after: discord.Channel = None):
        """User specific channel.

        Everyone can read but only one person can write.
        """
        server = ctx.message.server
        channel = await self.bot.create_channel(
            server,
            name,
            discord.ChannelPermissions(
                target=server.default_role,
                overwrite=discord.PermissionOverwrite(
                    read_messages=True,
                    send_messages=False
                )
            ),
            discord.ChannelPermissions(
                target=user,
                overwrite=discord.PermissionOverwrite(
                    send_messages=True
                )
            ),
            type=discord.ChannelType.text
        )

        await self.bot.say("Channel created: {}".format(channel)) 
Example #9
Source File: mod.py    From Discord-SelfBot with MIT License 5 votes vote down vote up
def mute(self, ctx, mem: str):
        """Mute a Member."""
        member = getUser(ctx, mem)
        if member:
            if not utils.find(lambda r: "mute" in r.name.lower(), ctx.message.guild.roles):
                if not utils.find(lambda r: "Muted" == r.name, ctx.message.guild.roles):
                    perms = utils.find(lambda r: "@everyone" == r.name, ctx.message.guild.roles).permissions
                    role = await ctx.guild.create_role(name="Muted", permissions=perms)
                    log.info('Created role: Muted')
                    for channel in ctx.guild.text_channels:
                        await channel.set_permissions(role, overwrite=discord.PermissionOverwrite(send_messages=False, add_reactions=False))
                    for channel in ctx.guild.voice_channels:
                        await channel.set_permissions(role, overwrite=discord.PermissionOverwrite(speak=False))
                    log.info('Prepared Mute role for mutes in channels')
                role = utils.find(lambda r: "Muted" == r.name, ctx.message.guild.roles)
            else:
                role = utils.find(lambda r: "mute" in r.name.lower(), ctx.message.guild.roles)

            if role not in member.roles:
                roles = member.roles
                roles.append(role)
                asyncio.sleep(0.5)
                await member.edit(roles=roles)
                log.info(f'Muted {member}')

                e = discord.Embed(color=embedColor(self))
                e.set_author(name="\N{SPEAKER WITH CANCELLATION STROKE} Muted " + str(member))
                await edit(ctx, embed=e)
            else:
                await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Already muted", ttl=5)

    # Mute a Member 
Example #10
Source File: test_silence.py    From bot with MIT License 5 votes vote down vote up
def test_silence_private_preserves_permissions(self):
        """Previous permissions were preserved when channel was silenced."""
        channel = MockTextChannel()
        # Set up mock channel permission state.
        mock_permissions = PermissionOverwrite()
        mock_permissions_dict = dict(mock_permissions)
        channel.overwrites_for.return_value = mock_permissions
        await self.cog._silence(channel, False, None)
        new_permissions = channel.set_permissions.call_args.kwargs
        # Remove 'send_messages' key because it got changed in the method.
        del new_permissions['send_messages']
        del mock_permissions_dict['send_messages']
        self.assertDictEqual(mock_permissions_dict, new_permissions) 
Example #11
Source File: bot.py    From modmailbotkenng with MIT License 5 votes vote down vote up
def overwrites(self, ctx, modrole=None):
        '''Permision overwrites for the guild.'''
        overwrites = {
            ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False)
        }

        if modrole:
            overwrites[modrole] = discord.PermissionOverwrite(read_messages=True)
        else:
            for role in self.guess_modroles(ctx):
                overwrites[role] = discord.PermissionOverwrite(read_messages=True)

        return overwrites 
Example #12
Source File: mod.py    From Discord-Selfbot with GNU General Public License v3.0 5 votes vote down vote up
def are_overwrites_empty(self, overwrites):
        """There is currently no cleaner way to check if a
        PermissionOverwrite object is empty"""
        original = [p for p in iter(overwrites)]
        empty = [p for p in iter(discord.PermissionOverwrite())]
        return original == empty 
Example #13
Source File: punish.py    From refactored-cogs with Mozilla Public License 2.0 5 votes vote down vote up
def new_channel(self, c):
        if 'Punished' in [r.name for r in c.server.roles]:
            if c.type.name == 'text':
                perms = discord.PermissionOverwrite()
                perms.send_messages = False
                r = discord.utils.get(c.server.roles, name='Punished')
                await self.bot.edit_channel_permissions(c, r, perms)
                log.debug('Punished role created on channel: {}'.format(c.id)) 
Example #14
Source File: events.py    From spirit with MIT License 5 votes vote down vote up
def get_events_channel(self, guild):
        """Return the events channel if it exists, otherwise create one and return it"""
        for channel in guild.channels:
            if channel.name == "upcoming-events":
                return channel

        # Need to make sure the bot can still send messages in the events channel
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(send_messages=False, add_reactions=True),
            guild.me: discord.PermissionOverwrite(send_messages=True, add_reactions=True)
        }
        return await guild.create_text_channel("upcoming-events", overwrites=overwrites) 
Example #15
Source File: test_silence.py    From bot with MIT License 5 votes vote down vote up
def test_unsilence_private_preserves_permissions(self, _):
        """Previous permissions were preserved when channel was unsilenced."""
        channel = MockTextChannel()
        # Set up mock channel permission state.
        mock_permissions = PermissionOverwrite(send_messages=False)
        mock_permissions_dict = dict(mock_permissions)
        channel.overwrites_for.return_value = mock_permissions
        await self.cog._unsilence(channel)
        new_permissions = channel.set_permissions.call_args.kwargs
        # Remove 'send_messages' key because it got changed in the method.
        del new_permissions['send_messages']
        del mock_permissions_dict['send_messages']
        self.assertDictEqual(mock_permissions_dict, new_permissions) 
Example #16
Source File: tracking.py    From NabBot with Apache License 2.0 4 votes vote down vote up
def watchlist_create(self, ctx: NabCtx, *, name):
        """Creates a watchlist channel.

        Creates a new text channel for the watchlist to be posted.

        The watch list shows which characters from it are online. Entire guilds can be added too.

        The channel can be renamed at anytime. If the channel is deleted, all its entries are deleted too.
        """
        if WATCHLIST_SEPARATOR in name:
            await ctx.error(f"Channel name cannot contain the special character **{WATCHLIST_SEPARATOR}**")
            return

        if not ctx.bot_permissions.manage_channels:
            return await ctx.error(f"I need `Manage Channels` permission in the server to use this command.")

        message = await ctx.send(f"Do you want to create a new watchlist named `{name}`?")
        confirm = await ctx.react_confirm(message, delete_after=True)
        if not confirm:
            return

        try:
            overwrites = {
                ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False, read_messages=True),
                ctx.guild.me: discord.PermissionOverwrite(send_messages=True, read_messages=True, manage_channels=True)
            }
            channel = await ctx.guild.create_text_channel(name, overwrites=overwrites, category=ctx.channel.category)
        except discord.Forbidden:
            await ctx.error(f"Sorry, I don't have permissions to create channels.")
        except discord.HTTPException:
            await ctx.error(f"Something went wrong, the channel name you chose is probably invalid.")
        else:
            log.info(f"Watchlist created (Channel ID: {channel.id}, Guild ID: {channel.guild.id})")
            await ctx.success(f"Channel created successfully: {channel.mention}\n")
            await channel.send("This is where I will post a list of online watched characters.\n"
                               "Edit this channel's permissions to allow the roles you want.\n"
                               "This channel can be renamed freely.\n"
                               "Anyone with `Manage Channel` permission here can add entries.\n"
                               f"Example: {ctx.clean_prefix}{ctx.command.full_parent_name} add {channel.mention} "
                               f"Galarzaa Fidera\n"
                               "If this channel is deleted, all related entries will be lost.\n"
                               "**It is important to not allow anyone to write in here**\n"
                               "*This message can be deleted now.*")
            watchlist = await Watchlist.insert(ctx.pool, ctx.guild.id, channel.id, ctx.author.id)
            log.debug(f"{self.tag} Watchlist created | {watchlist}") 
Example #17
Source File: Verification.py    From NotSoBot with MIT License 4 votes vote down vote up
def on_member_join(self, member):
		try:
			if member.bot:
				return
			server = member.server
			sql = 'SELECT * FROM `verification` WHERE server={0}'
			sql = sql.format(server.id)
			result = self.cursor.execute(sql).fetchall()
			if len(result) == 0:
				return
			channel = server.get_channel(str(result[0]['channel']))
			if channel is None:
				raise discord.errors.NotFound
			perms = server.me.permissions_in(channel)
			if perms.manage_roles is False or perms.manage_channels is False:
				if perms.administrator is False:
					await self.remove_verification(server)
					return
			sql = "INSERT INTO `verification_queue` (`user`, `server`, `id`) VALUES (%s, %s, %s)"
			rand = random.randint(0, 99999)
			self.cursor.execute(sql, (member.id, server.id, rand))
			self.cursor.commit()
			role = discord.utils.get(server.roles, name='Awaiting Approval')
			await self.bot.add_roles(member, role)
			for s in server.channels:
				perms = member.permissions_in(s)
				if perms.read_messages is False:
					continue
				overwrite = discord.PermissionOverwrite()
				overwrite.send_messages = False
				overwrite.read_messages = False
				await self.bot.edit_channel_permissions(s, role, overwrite)
			msg = ''
			if result[0]['mentions']:
				for x in result[0]['mentions'].split(' '):
					if 'everyone' in x or 'here' in x:
						msg += '{0} '.format(x)
					else:
						msg += '<@{0}> '.format(x)
				msg += '\n'
			msg += ':warning: `{0}` has joined the server and is awaiting approval\n\nRun `verify {1} or mention` to approve, kick user to remove from the queue.'.format(member, rand)
			await self.bot.send_message(channel, msg, replace_everyone=False, replace_mentions=False)
			join_msg = "You've been placed in the approval queue for `{0}`, please be patient and wait until a staff member approves your join!\n\nIf you'd like to expedite approval (and have a steam account), place **{1}** in your steam name and then run `.verify check <stean_url/id/vanity>`.".format(server.name, rand)
			await self.bot.send_message(member, join_msg)
		except (discord.errors.Forbidden, discord.errors.InvalidArgument, discord.errors.NotFound):
			await self.remove_verification(server)