def can_read(channel: discord.TextChannel, base_role: discord.Role): if channel.overwrites_for( base_role).read_messages is True or channel.overwrites_for( base_role).read_messages is None: return True return False
async def silence_channel(self, channel: discord.TextChannel): if channel.overwrites_for( channel.guild.default_role).send_messages is False: await self.modlog.log_message( "Channel already silenced", f"Channel <#{channel.id}> already silenced", channel.guild.me) return False if channel.category and channel.category.id in config( )["restricted_categories"]: await self.modlog.log_message( "Channel not silenced", f"Channel <#{channel.id}> in a restricted category", channel.guild.me) return False self.overwrite_restore[channel.id] = \ channel.overwrites_for(channel.guild.default_role).send_messages perms: discord.PermissionOverwrite = channel.overwrites_for( channel.guild.default_role) perms.update(send_messages=False) await channel.set_permissions(channel.guild.default_role, overwrite=perms) perms: discord.PermissionOverwrite = channel.overwrites_for(self.staff) perms.update(send_messages=True) await channel.set_permissions(self.staff, overwrite=perms) return True
async def unlock(self, ctx, channel: discord.TextChannel = None): channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) if overwrite.send_messages == True: embed = discord.Embed( title="Invalid usage", description="This channel is already unlocked", color=0xff000) embed.set_image( url= "https://media1.tenor.com/images/7cb7b5cc74e9a63d11e474a3e135d617/tenor.gif" ) embed.set_footer( text=f'Requested By: {ctx.author.name}', icon_url=f'{ctx.author.avatar_url}') await ctx.send(embed=embed) else: channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = True await channel.set_permissions( ctx.guild.default_role, overwrite=overwrite) embed = discord.Embed( title="Channel Unlocked", description="This channel is now unlocked", color=0xff000) embed.set_footer( text=f'Requested By: {ctx.author.name}', icon_url=f'{ctx.author.avatar_url}') await ctx.send(embed=embed)
async def unlock(self, ctx, channel: discord.TextChannel = None): channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) if overwrite.send_messages == True: embed = discord.Embed( title="Invalid usage", description="This channel is already unlocked", color=0xFF000, ) embed.set_footer( text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}", ) await ctx.send(embed=embed) else: channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = True await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) embed = discord.Embed( title="Channel Unlocked", description="This channel is now unlocked", color=0xFF000, ) embed.set_footer( text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}", ) await ctx.send(embed=embed)
def can_add_reaction(channel: discord.TextChannel, base_role: discord.Role): if channel.overwrites_for( base_role).add_reactions is True or channel.overwrites_for( base_role).add_reactions is None: return True return False
async def wait_for_response(member: Member, channel: TextChannel, seconds: int, handle_permission: bool = False) -> Optional[str]: """ Wait for the response of the member in the channel :param member: Member to wait for response :param channel: Channel to wait for response :param seconds: How long to wait for response :param handle_permission: Whether to add send_message permission for the member during the waiting :return: The response of the member """ if handle_permission: overwrite: PermissionOverwrite = channel.overwrites_for(member) overwrite.update(send_messages=True) await channel.set_permissions(member, overwrite=overwrite) # Delete old waiting for responses @connection def delete_waiting_reponses(_c: Cursor): _c.execute( 'DELETE FROM waiting_for_responses WHERE user_id=? AND channel_ID=?', (member.id, channel.id)) delete_waiting_reponses() # Insert into database waiting_id = insert.waiting_for_reponse(member.id, channel.id, channel.guild.id) response = None # Look for response for _ in range(seconds): # Wait a second await asyncio.sleep(1) # Check whether there is a response try: waiting_response: WaitingResponse = select.WaitingResponse( id=waiting_id) except DatabaseEntryError: # Return None if the database entry was deleted return None if waiting_response.response: response = waiting_response.response break if handle_permission: overwrite: PermissionOverwrite = channel.overwrites_for(member) overwrite.update(send_messages=False) await channel.set_permissions(member, overwrite=overwrite) # Delete entry and return the response delete.waiting_for_response(id) return response
def is_helper_viewable(channel: TextChannel) -> bool: """Check if helpers can view a specific channel.""" guild = channel.guild helper_role = guild.get_role(constants.Roles.helpers) # check channel overwrites for both the Helper role and @everyone and # return True for channels that they have permissions to view. helper_overwrites = channel.overwrites_for(helper_role) default_overwrites = channel.overwrites_for(guild.default_role) return default_overwrites.view_channel is None or helper_overwrites.view_channel is True
async def lock(self, ctx, chnnel: discord.TextChannel = None): try: everyone = ctx.guild.default_role if chnnel is None: if ctx.channel.overwrites_for(everyone).send_messages in [ None, True ]: currentperms = ctx.channel.overwrites_for(everyone) currentperms.send_messages = False await ctx.channel.set_permissions( everyone, overwrite=currentperms, reason=(f"Channel lock by {str(ctx.author)}")) await ctx.channel.send( f"🔒 `#{ctx.channel.name} was locked`") return elif ctx.channel.overwrites_for(everyone).send_messages in [ False ]: newperms = ctx.channel.overwrites_for(everyone) newperms.send_messages = None await ctx.channel.set_permissions( everyone, overwrite=newperms, reason=(f"Channel lock by {str(ctx.author)}")) await ctx.channel.send( f"🔒 `#{ctx.channel.name} was unlocked`") return else: if chnnel.overwrites_for(everyone).send_messages in [ None, True ]: currentperms = chnnel.overwrites_for(everyone) currentperms.send_messages = False await chnnel.set_permissions( everyone, overwrite=currentperms, reason=(f"Channel unlock by {str(ctx.author)}")) await chnnel.send(f"🔓 `#{chnnel.name} was unlocked`") return elif chnnel.overwrites_for(everyone).send_messages in [False]: newperms = chnnel.overwrites_for(everyone) newperms.send_messages = None await chnnel.set_permissions( everyone, overwrite=newperms, reason=(f"Channel unlock by {str(ctx.author)}")) await chnnel.send(f"🔓 `#{chnnel.name} was unlocked`") return except Exception as e: await ctx.send(f"`Something went wrong: {e}`")
def is_staff_channel(channel: discord.TextChannel) -> bool: """True if `channel` is considered a staff channel.""" guild = bot.instance.get_guild(constants.Guild.id) if channel.type is discord.ChannelType.category: return False # Channel is staff-only if staff have explicit read allow perms # and @everyone has explicit read deny perms return any( channel.overwrites_for(guild.get_role(staff_role)).read_messages is True and channel.overwrites_for(guild.default_role).read_messages is False for staff_role in constants.STAFF_ROLES )
async def lock(ctx, channel : discord.TextChannel=None): if channel == None: channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = False await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) await ctx.send('Channel locked.') await channel.send(f"This channel has been locked by {ctx.author. mention}") else: channel = channel or ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = False await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) await ctx.send('Channel locked.') await channel.send(f"This channel has been locked by {ctx.author. mention}")
async def lock(self, ctx, channel: discord.TextChannel = None): """Locks down the channel mentioned. Moderators+ Sets the channel permissions as @everyone can't send messages. If no channel was mentioned, it locks the channel the command was used in""" if not channel: channel = ctx.channel if channel.overwrites_for( ctx.guild.default_role).send_messages is False: await ctx.send( f"🔒 {channel.mention} is already locked down. Use `{ctx.prefix}unlock` to unlock." ) return await channel.set_permissions(ctx.guild.default_role, send_messages=False, add_reactions=False) await channel.send(f"🔒 {channel.mention} is now locked.") # Define Safe Name so we don't mess this up (again) safe_name = await commands.clean_content().convert( ctx, str(ctx.author)) log_message = f"🔒 **Lockdown** in {ctx.channel.mention} by {ctx.author.mention} | {safe_name}" if "log_channel" in ctx.guild_config: try: log_channel = self.bot.get_channel( ctx.guild_config["log_channel"]) await log_channel.send(log_message) except: pass
async def unlock(self, ctx, channel: TextChannel = None): channel = channel or ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = True await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) await ctx.send("Channel unlocked")
def _get_effective_permission(granted_perms: discord.Permissions, channel: discord.TextChannel, channel_overwrite, me_override=None): # check for overrides by 'channel' if channel_overwrite: # the list holds lowest permission at first index # apply channel-role from low-high onto the granted permissions # result after iteration is effective permissions for that channel if me_override: me = me_override else: me = channel.guild.me # first check overrides for user # as they have the lowest priority role_list = [me] + me.roles for role in role_list: # role can be a user_obj aswell ovr = channel.overwrites_for(role) allow, deny = ovr.pair() # all values with '1' need to be 0 in granted, values with '0' should stay # -> (y & (~x)) achieves this logic granted_perms.value = granted_perms.value & (~deny.value) # simple or enough to allow granted_perms.value = granted_perms.value | allow.value return granted_perms
async def channelinfo(self, ctx, channel: discord.TextChannel = None): """Shows info on a channel.""" async with ctx.typing(): channel = channel or ctx.channel td = { True: "<:nsfw:730852009032286288>", False: "<:text_channel:703726554018086912>", } if channel.overwrites_for( ctx.guild.default_role).read_messages is False: url = "<:text_locked:730929388832686090>" else: if channel.is_news(): url = "<:news:730866149109137520>" else: url = td[channel.is_nsfw()] embed = discord.Embed(colour=self.bot.colour) embed.title = f"{url} {channel.name} | {channel.id}" last_message = await channel.fetch_message(channel.last_message_id) pins = await channel.pins() embed.description = ( f"{channel.topic or ''}\n{f'<:category:716057680548200468> **{channel.category}**' if channel.category else ''} " f"<:member:731190477927219231> **{len(channel.members):,}** " f"{f'<:pin:735989723591344208> **{len(pins)}**' if pins else ''} <:msg:735993207317594215> [Last Message]({last_message.jump_url})" ) embed.description = f"{channel.topic or ''}\n{f'<:category:716057680548200468> **{channel.category}**' if channel.category else ''} <:member:731190477927219231> **{len(channel.members):,}** {f'<:pin:735989723591344208> **{len([*await channel.pins()])}**' if await channel.pins() else ''} <:msg:735993207317594215> [Last Message]({last_message.jump_url})" embed.set_footer( text=f'Channel created {nt(dt.utcnow() - channel.created_at)}') await ctx.send(embed=embed)
async def remove(self, ctx: Context, *, channel: TextChannel = None): """ Remove a channel from the list of channels unconfirmed users can access. Parameters: - [optional] channel: The channel to remove from the list, identified by mention, ID, or name. Defaults to the current channel. """ if not channel: channel = ctx.channel if not channel.guild.id == ctx.guild.id: await ctx.send('The provided channel is not on this server.') return db_channel = ctx.session.query(NewbieChannel).get(channel.id) if not db_channel: await ctx.send( 'The provided channel is not visible to unconfirmed members.') return everyone_role = ctx.guild.default_role everyone_overwrite = channel.overwrites_for(everyone_role) everyone_overwrite.update(read_messages=None, read_message_history=None) await channel.set_permissions(everyone_role, overwrite=everyone_overwrite) ctx.session.delete(db_channel) logger.info( f'Removed channel {channel} from visble channels for {ctx.guild}.') await ctx.send( f'{channel.mention} is now invisible to unconfirmed users.')
async def hunlock(self, ctx, channel: discord.TextChannel = None): """Hard unlocks the channel mentioned. Admin only. If no channel was mentioned, it unlocks the channel the command was used in""" if not channel: channel = ctx.channel if channel.overwrites_for( ctx.guild.default_role).read_messages is None: await ctx.send(f"🔓 {channel.mention} is already unlocked.") return await channel.set_permissions(ctx.guild.default_role, read_messages=None) await channel.send(f"🔓 {channel.mention} is now unlocked.") # Define Safe Name so we don't mess this up (again) safe_name = await commands.clean_content().convert( ctx, str(ctx.author)) log_message = f"🔓 **Hard Unlock** in {ctx.channel.mention} by {ctx.author.mention} | {safe_name}" if "log_channel" in ctx.guild_config: try: log_channel = self.bot.get_channel( ctx.guild_config["log_channel"]) await log_channel.send(log_message) except: pass
async def hlock(self, ctx, channel: discord.TextChannel = None): """Hard locks a channel. Admin only. Sets the channel permissions as @everyone can't speak or see the channel. If no channel was mentioned, it hard locks the channel the command was used in.""" if not channel: channel = ctx.channel if channel.overwrites_for( ctx.guild.default_role).read_messages is False: await ctx.send( f"🔒 {channel.mention} is already hard locked. Use `{ctx.prefix}hard-unlock` to unlock the channel." ) return await channel.set_permissions(ctx.guild.default_role, read_messages=False) await channel.send(f"🔒 {channel.mention} is now hard locked.") # Define Safe Name so we don't mess this up (again) safe_name = await commands.clean_content().convert( ctx, str(ctx.author)) log_message = f"🔒 **Hard Lockdown** in {ctx.channel.mention} by {ctx.author.mention} | {safe_name}" if "log_channel" in ctx.guild_config: try: log_channel = self.bot.get_channel( ctx.guild_config["log_channel"]) await log_channel.send(log_message) except: pass
async def unlock(ctx, channel: discord.TextChannel = None, Reason=None): channel = channel or ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = None await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) embedAAAAA = discord.Embed(title="Channel unlocked.🔓", color=0x3A56D4) await ctx.send(embed=embedAAAAA)
async def _silence(self, channel: TextChannel, persistent: bool, duration: Optional[int]) -> bool: """ Silence `channel` for `self._verified_role`. If `persistent` is `True` add `channel` to notifier. `duration` is only used for logging; if None is passed `persistent` should be True to not log None. Return `True` if channel permissions were changed, `False` otherwise. """ current_overwrite = channel.overwrites_for(self._verified_role) if current_overwrite.send_messages is False: log.info( f"Tried to silence channel #{channel} ({channel.id}) but the channel was already silenced." ) return False await channel.set_permissions( self._verified_role, **dict(current_overwrite, send_messages=False)) self.muted_channels.add(channel) if persistent: log.info(f"Silenced #{channel} ({channel.id}) indefinitely.") self.notifier.add_channel(channel) return True log.info( f"Silenced #{channel} ({channel.id}) for {duration} minute(s).") return True
async def unhide(ctx, channel: discord.TextChannel = None, *, Reason=None): channel = channel or ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.view_channel = None await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) embedAAAAB = discord.Embed(title="Channel Unhidden.👁️", color=0x3A56D4) await ctx.send(embed=embedAAAAB)
async def mute_user(*reason, channel: discord.TextChannel = None, guild: discord.Guild = None, member: discord.member = None, data=None, ctx=None, time=None): overwrite = channel.overwrites_for(member) or discord.PermissionOverwrite() # noinspection PyDunderSlots,PyUnresolvedReferences overwrite.send_messages = False # noinspection PyDunderSlots,PyUnresolvedReferences overwrite.send_tts_messages = False # noinspection PyDunderSlots,PyUnresolvedReferences overwrite.speak = False await channel.set_permissions(member, overwrite=overwrite) if not data: saved = read_messages_per_channel(channel, member.mention) if saved: saved.escalate = min(6, saved.escalate + 1) saved.muted = 1 else: saved = UserData(guild=guild.id, channel=channel.id, uid=member.mention, escalate=1, muted=1, expire=0, messages=0, m1='', m2='', m3='', m4='', m5='') data = saved if not time: time = escalate[data.escalate] data.expire = int(datetime.datetime.utcnow().timestamp()) + time write_database(data) # if not ctx: # ctx = channel if not ctx: ctx = type('dummy ctx', (), {'channel': channel, 'guild': guild}) await log_action(ctx, Action.Mute, member.mention, reason, where=channel, time=time) if hasattr(ctx, 'message'): issuer = ctx.message.author.mention else: issuer = bot.user.name await channel.send( f'{member.mention} you have been muted here for {expire_str(time)} by {issuer}' )
async def lock(self, ctx, channel : discord.TextChannel=None): """Locks a channel.""" overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = False await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) await ctx.send('Channel locked.')
async def channelunmute(self, ctx, channel: discord.TextChannel = None): if channel is None: channel = ctx.message.channel prevPerms = channel.overwrites_for(ctx.guild.default_role) prevPerms.send_messages = self.everyoneStatus[str(channel.id)] await channel.set_permissions(ctx.guild.default_role, overwrite=prevPerms) for role in ctx.guild.roles: perms = channel.overwrites_for(role) if role.id in self.editList[str(channel.id)]: perms.send_messages = True await channel.set_permissions(role, overwrite=perms) await ctx.send(embed=discord.Embed( description= f"<a:check:771786758442188871> {channel.mention} has been unlocked.", color=discord.Color.green())) self.editList.pop(str(channel.id))
async def copyrole(self, ctx, role: discord.Role, src_channel: discord.TextChannel, des_channels: commands.Greedy[discord.TextChannel]): """Copy role permission from a channel to channels""" perms = src_channel.overwrites_for(role) for c in des_channels: await c.set_permissions(role, overwrite=perms) await ctx.send("Changed permissions successfully")
def everyone_can_read(self, channel: discord.TextChannel): everyone = channel.guild.default_role overwritten = channel.overwrites_for(everyone).read_messages if overwritten is None: return everyone.permissions.read_messages else: return overwritten
async def unlock(self, ctx, channel: discord.TextChannel = None): channel = channel or ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = True await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) await ctx.send(embed=discord.Embed( description='🔓 | channel unlock {}'.format(channel.mention), color=discord.Colour.green() ))
async def hide(self, ctx, channel: discord.TextChannel = None): channel = channel or ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.read_messages = False await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) await ctx.send(embed=discord.Embed( description='👤 | channel has been Hide {}'.format(channel.mention), color=discord.Colour.green() ))
async def hide(ctx, channel: discord.TextChannel = None, *, Reason=None): channel = channel or ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.view_channel = False await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) embedAAAAB = discord.Embed(title="Channel Hidden.➖", description=f"Reason: ```md\n{Reason}```", color=0x3A56D4) await ctx.send(embed=embedAAAAB)
async def _unsilence_wrapper(self, channel: TextChannel) -> None: """Unsilence `channel` and send a success/failure message.""" if not await self._unsilence(channel): overwrite = channel.overwrites_for(self._verified_role) if overwrite.send_messages is False or overwrite.add_reactions is False: await channel.send(MSG_UNSILENCE_MANUAL) else: await channel.send(MSG_UNSILENCE_FAIL) else: await channel.send(MSG_UNSILENCE_SUCCESS)
async def unlock(self, ctx, channel: discord.TextChannel = None): channel = channel or ctx.channel # Overwrites user permssions overwrite = channel.overwrites_for(ctx.guild.default_role) overwrite.send_messages = True await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite) await ctx.send('Channel Unlocked.')