我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用discord.PermissionOverwrite()。
def invite_user_to_raid(channel, user): """Invites a user to the raid channel.""" global should_refresh_active_raids # don't invite bots and webhooks if user.bot: return # refresh active raids in future should_refresh_active_raids = True # adds an overwrite for the user perms = discord.PermissionOverwrite(read_messages=True) await client.edit_channel_permissions(channel, user, perms) # invite user to role role = get_raid_role(channel) if role: await client.add_roles(user, role) # sends a message to the raid channel the user was added await client.send_message(channel, "{}, you are now a member of this raid group.".format(user.mention), embed=get_success_embed('{} has joined the raid!'.format(user.display_name)))
def mute(self, ctx, *, user:discord.Member): """Mute un utilisateur Requiert la permission de kick""" await self.bot.delete_message(ctx.message) if ctx.message.author.server_permissions.kick_members == True: overwrite = ctx.message.channel.overwrites_for(user) or discord.PermissionOverwrite() overwrite.send_messages = False await self.bot.edit_channel_permissions(ctx.message.channel, user, overwrite) tmp = await self.bot.send_message(ctx.message.channel, "{} is now muted here !".format(user.mention)) await asyncio.sleep(5) await self.bot.delete_message(tmp) else: tmp = await self.bot.say("```\nVous n'avez pas la permission d'utiliser cette commande\n```") await asyncio.sleep(5) await self.bot.delete_message(tmp)
def unmute(self, ctx, *, user:discord.Member): """Unute un utilisateur Requiert la permission de kick""" await self.bot.delete_message(ctx.message) if ctx.message.author.server_permissions.kick_members == True: overwrite = ctx.message.channel.overwrites_for(user) or discord.PermissionOverwrite() overwrite.send_messages = True await self.bot.edit_channel_permissions(ctx.message.channel, user, overwrite) tmp = await self.bot.send_message(ctx.message.channel, "{} is no longer muted here! He/she can speak now!".format(user.mention)) await asyncio.sleep(5) await self.bot.delete_message(tmp) else: tmp = await self.bot.say("```\nVous n'avez pas la permission d'utiliser cette commande\n```") await asyncio.sleep(5) await self.bot.delete_message(tmp)
def mute(self, ctx, *, member: discord.Member): """Mute someone on voice and text chat. Usage: mute [person's name]""" or_check_perms(ctx, ['mute_members', 'manage_roles', 'manage_channels', 'manage_messages']) status = await ctx.send('Muting... ??') pg_task = self.loop.create_task(asyncio.wait_for(self.progress(status, 'Muting'), timeout=30, loop=self.loop)) try: ch_perms = discord.PermissionOverwrite(**{p: False for p in muted_perms}) for channel in ctx.guild.channels: await channel.set_permissions(member, ch_perms) await member.__redit(mute=True, deafen=None, reason='Mute command was used on user') pg_task.cancel() await status.delete(reason='Deleting progress/status message') await ctx.send('Successfully muted **%s**!' % str(member)) except (discord.Forbidden, discord.HTTPException): pg_task.cancel() await status.delete(reason='Deleting progress/status message') await ctx.send('**I don\'t have enough permissions to do that!**')
def unmute(self, ctx, *, member: discord.Member): """Unmute someone on voice and text chat. Usage: unmute [person's name]""" or_check_perms(ctx, ('mute_members', 'manage_roles', 'manage_channels', 'manage_messages')) status = await ctx.send('Unmuting... ??') pg_task = self.loop.create_task(asyncio.wait_for(self.progress(status, 'Unmuting'), timeout=30, loop=self.loop)) role_map = {r.name: r for r in member.roles} try: if 'Muted' in role_map: await member.remove_roles(role_map['Muted'], reason='Unmute command was used on user') ch_perms = discord.PermissionOverwrite(**{p: None for p in muted_perms}) for channel in ctx.guild.channels: await channel.set_permissions(member, ch_perms) await member.__redit(mute=False, deafen=None, reason='Unmute command was used on user') pg_task.cancel() await status.delete(reason='Deleting progress/status message') await ctx.send('Successfully unmuted **%s**!' % str(member)) except (discord.Forbidden, discord.HTTPException): pg_task.cancel() await status.delete(reason='Deleting progress/status message') await ctx.send('**I don\'t have enough permissions to do that!**')
def create(self, ctx, *channel_name): """Create a new voice channel with Supervisor permission.""" guild = ctx.guild channel_name = " ".join(channel_name) for channel in guild.voice_channels: if channel.name == channel_name: await self.bot_reply(ctx, 'Channel **{}** already exists, {}'.format(channel_name, ctx.author.mention)) return False supervisor_role = None for role in guild.roles: if role.name == 'Supervisors': supervisor_role = role break if supervisor_role is None: return False perms = { supervisor_role: discord.PermissionOverwrite(manage_roles=True) } await guild.create_voice_channel(channel_name, overwrites=perms)
def create(self, ctx, *channel_name): """Create a new text channel with Supervisor permission.""" guild = ctx.guild channel_name = " ".join(channel_name) for channel in guild.text_channels: if channel.name == channel_name: await self.bot_reply(ctx, 'Channel **{}** already exists, {}'.format(channel_name, ctx.author.mention)) return False supervisor_role = None for role in guild.roles: if role.name == 'Supervisors': supervisor_role = role break if supervisor_role is None: return False perms = { guild.default_role: discord.PermissionOverwrite(read_messages=False), supervisor_role: discord.PermissionOverwrite(read_messages=True, manage_roles=True) } await guild.create_text_channel(channel_name, overwrites=perms)
def make_private_room(race_private_info, discord_member): # Define permissions deny_read = discord.PermissionOverwrite(read_messages=False) permit_read = discord.PermissionOverwrite(read_messages=True) # Make a channel for the room # noinspection PyUnresolvedReferences race_channel = await server.client.create_channel( server.server, get_raceroom_name(race_private_info.race_info), discord.ChannelPermissions(target=server.server.default_role, overwrite=deny_read), discord.ChannelPermissions(target=server.server.me, overwrite=permit_read), discord.ChannelPermissions(target=discord_member, overwrite=permit_read), type=discord.ChannelType.text ) if race_channel is not None: new_room = PrivateRaceRoom( race_discord_channel=race_channel, race_private_info=race_private_info, admin_as_member=discord_member) await new_room.initialize() Necrobot().register_bot_channel(race_channel, new_room) return race_channel
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)
def on_member_join(self, member): if (member.server.id in self.settings) and not ("bots" in member.server.name.lower()): try: temp = self.settings[member.server.id]['joined'] except KeyError: self.settings[member.server.id]['joined'] = 0 try: self.settings[member.server.id]['joined'] += 1 self.save_settings() if self.settings[member.server.id]['members'] != 0: if (self.settings[member.server.id]['joined'] >= self.settings[member.server.id]['members']) and not (self.settings[member.server.id]['protected']): self.settings[member.server.id]['protected'] = True self.save_settings() for channel in member.server.channels: if (channel.id == self.settings[member.server.id]['channel']) and (self.settings[member.server.id]['channel'] != None): await self.bot.send_message(channel, "Raid protect has been turned on, more than {} people joined within 8 seconds.".format(self.settings[member.server.id]['members'])) await asyncio.sleep(8) self.settings[member.server.id]['joined'] = 0 self.save_settings() except KeyError: pass try: if self.settings[member.server.id]['protected']: for channel in member.server.channels: if channel.id != self.settings[member.server.id]['channel']: perms = discord.PermissionOverwrite() perms.read_messages = False perms.send_messages = False await self.bot.edit_channel_permissions(channel, member, perms) else: await self.bot.send_message(channel, "{}, you have been muted in every channel because raidprotect is on, if you are not here to raid just wait patiently and your permissions will be restored.".format(member.mention)) except KeyError: return
def mute(self, member, minutes:int): for channel in member.server.channels: perms = discord.PermissionOverwrite() perms.send_messages = False await self.bot.edit_channel_permissions(channel, member, perms) await asyncio.sleep(minutes * 60) for channel in member.server.channels: perms = discord.PermissionOverwrite() perms.send_messages = None await self.bot.edit_channel_permissions(channel, member, perms)
def makestarboard(self, ctx): ''' Make a channel that works with the starboard setup ''' serverSettings = getServerJson(ctx.message.server.id) serverSettings['Toggles']['Starboard'] = True c = PermissionOverwrite(send_messages=False, add_reactions=False) d = PermissionOverwrite(send_messages=True, add_reactions=True) v = await self.sparcli.create_channel(ctx.message.server, 'starboard', (ctx.message.server.default_role, c), (ctx.message.server.me, d)) serverSettings['Channels']['Starboard'] = v.id saveServerJson(ctx.message.server.id, serverSettings) await self.sparcli.say('Done!')
def setup_channel(self, channel, role): perms = discord.PermissionOverwrite() if channel.type == discord.ChannelType.text: perms.send_messages = False perms.send_tts_messages = False elif channel.type == discord.ChannelType.voice: perms.speak = False await self.bot.edit_channel_permissions(channel, role, overwrite=perms)
def suspend(message: discord.Message, channel: discord.Channel=Annotate.Self): """ Suspends a channel by removing send permission for the server's default role. This function acts like a toggle. """ send = channel.overwrites_for(message.server.default_role).send_messages print(send, False if send is None else not send) overwrite = discord.PermissionOverwrite(send_messages=False if send is None else not send) await client.edit_channel_permissions(channel, message.server.default_role, overwrite) try: if overwrite.send_messages: await client.say(message, "{} is no longer suspended.".format(channel.mention)) else: await client.say(message, "Suspended {}.".format(channel.mention)) except discord.Forbidden: # ... await client.send_message(message.author, "You just removed my send permission in {}.".format(channel.mention))
def mute(ctx, user, message): """ Command for muting users. :param ctx: :param user: :param message: :return: """ if user is None: await ctx.send_message(message.channel, "**Error**: User not mentioned." "\nUsage: `;;mute @user`") return overwrite = discord.PermissionOverwrite() overwrite.send_messages = False try: # TODO maybe change this to use Roles instead? for channel in message.server.channels: await ctx.edit_channel_permissions(channel, user, overwrite) await ctx.send_message(message.channel, "**Success**: `Muted {}`".format(user.name)) await ctx.send_message(user, "You are now muted in the server **{}**\n" "For more details, talk to the Server Admins / Moderators\n\n" "*I am a bot. Please don't reply to this message.*".format(message.server.name)) return except Exception as e: if error_messages.error_message(e, "mute"): await ctx.send_message(message.channel, "**Error**: `{}`".format(error_messages.error_message(e, "mute"))) return else: print(e)
def propagateMute(self, ctx): if self.bot.Henry(ctx): for role in ctx.message.server.roles: if role.id == '338575090847580160': MUTED_ROLE = role overwrite = discord.PermissionOverwrite() setattr(overwrite, 'send_messages', False) setattr(overwrite, 'manage_messages', False) setattr(overwrite, 'manage_channels', False) setattr(overwrite, 'manage_server', False) setattr(overwrite, 'manage_nicknames', False) setattr(overwrite, 'manage_roles', False) for channel in ctx.message.server.channels: if channel.id not in AVOID: await self.bot.edit_channel_permissions(channel, MUTED_ROLE, overwrite) # @commands.command(pass_context=True) # async def lock(self, ctx): # """Locks the current channel.""" # for role in ctx.message.server.roles: # if role.id == '338575090847580160': # MUTED_ROLE = role # if role.id == '296466915235332106': # BOTS_ROLE = role # if self.minion(ctx): # everyone = [] # for user in ctx.message.server.members: # if ctx.message.channel.permissions_for(user).send_messages and BOTS_ROLE not in user.roles: #don't mute bots # everyone.append(user) # for user in everyone: # await self.bot.add_roles(user, MUTED_ROLE) # await self.bot.say("Locking Channel") # else: # await self.bot.say("You ain't no mod, shoo!")
def ch_perms(self, channel, user, value): """Helper function""" overwrite = discord.PermissionOverwrite() overwrite.send_messages = value await self.bot.edit_channel_permissions(channel, user, overwrite)
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
def mute(ctx, user, message): """ Command for muting users. :param ctx: :param user: :param message: :return: """ if user is None: await ctx.send_message(message.channel, "**Error**: User not mentioned." "\nUsage: `?mute @user`") return overwrite = discord.PermissionOverwrite() overwrite.send_messages = False try: # TODO maybe change this to use Roles instead? for channel in message.server.channels: await ctx.edit_channel_permissions(channel, user, overwrite) await ctx.send_message(message.channel, "**Success**: `Muted {}`".format(user.name)) await ctx.send_message(user, "You are now muted in the server **{}**\n" "For more details, talk to the Server Admins / Moderators\n\n" "*I am a bot. Please don't reply to this message.*".format(message.server.name)) return except Exception as e: if error_messages.error_message(e, "mute"): await ctx.send_message(message.channel, "**Error**: `{}`".format(error_messages.error_message(e, "mute"))) return else: print(e)
def mutechannel(self, ctx): perms = discord.PermissionOverwrite() perms.send_messages = False await self.bot.edit_channel_permissions(ctx.message.channel, ctx.message.server.default_role ,perms) todelete = await self.bot.say("Done :+1:") await asyncio.sleep(5) await self.bot.delete_message(todelete)
def unmutechannel(self, ctx): perms = discord.PermissionOverwrite() perms.send_messages = True await self.bot.edit_channel_permissions(ctx.message.channel, ctx.message.server.default_role ,perms) todelete = await self.bot.say("Done :+1:") await asyncio.sleep(5) await self.bot.delete_message(todelete)
def muteperms(self, ctx): """Adds Muted permissions to channel used in""" overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.embed_links = False overwrite.attach_files = False overwrite.create_instant_invite = False overwrite.manage_messages = False overwrite.send_tts_messages = False overwrite.mention_everyone = False overwrite.speak = False overwrite.use_voice_activation = False await self.bot.edit_channel_permissions(ctx.message.channel, discord.utils.get(ctx.message.server.roles, name="Muted"), overwrite) await self.bot.say("Set up Muted permissions for this channel")
def make_muted_perms(server, muted): """This adds muted perms to every channel, easier than getting admins to do it manually""" overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.embed_links = False overwrite.attach_files = False overwrite.create_instant_invite = False overwrite.manage_messages = False overwrite.send_tts_messages = False overwrite.mention_everyone = False overwrite.speak = False overwrite.use_voice_activation = False for channel in server.channels: await bot.edit_channel_permissions(channel, muted, overwrite)
def cmd_slowmode(self, message, author, server, channel_id, time_between, reason=None): """ Usage: {command_prefix}slowmode #channel <time between messages> ["reason"] Puts the channel mentioned into a slowmode where users can only send messages every x seconds. To turn slow mode off, set the time between messages to "0" """ if await self.has_roles(message.channel, author, server, command='slowmode'): if channel_id in self.server_index[message.server.id][12]: raise CommandError('ERROR: Channel ID is ignored. Unignore the channel before setting to slow mode') try: time_between = int(time_between) except: raise CommandError('ERROR: The time limit between messages isn\'t a number, please specify a real number') try: if channel_id in self.slow_mode_dict.keys(): if time_between == 0: await self.delete_role(server, self.slow_mode_dict[channel_id]['channel_muted_role']) del self.slow_mode_dict[channel_id] await self.safe_send_message(discord.Object(channel_id), 'This channel is no longer in slow mode!') else: self.slow_mode_dict[channel_id]['time_between'] = time_between await self.safe_send_message(discord.Object(channel_id), 'The delay between allowed messages is now **%s seconds**!' % time_between) else: slowed_channel = discord.utils.get(server.channels, id=channel_id) channel_muted_role = await self.create_role(server, name=slowed_channel.name + 'SLOWROLE', permissions=discord.Permissions(permissions=66560)) overwrite = discord.PermissionOverwrite() overwrite.read_messages = True overwrite.send_messages = False await self.edit_channel_permissions(slowed_channel, channel_muted_role, overwrite) await self.safe_send_message(discord.Object(channel_id), 'This channel is now in slow mode with a delay of **%s seconds**!' % time_between) self.slow_mode_dict[channel_id] = {'time_between': time_between, 'channel_muted_role': channel_muted_role} await self.write_to_modlog(message, author, server, reason) except: raise CommandError('ERROR: Please make sure the syntax is correct and resubmit the command!')
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
def ne_process(self, ev: NecroEvent): if ev.event_type == 'rtmp_name_change': for row in await matchdb.get_channeled_matches_raw_data(): if int(row[2]) == ev.user.user_id or int(row[3]) == ev.user.user_id: channel_id = int(row[13]) channel = server.find_channel(channel_id=channel_id) if channel is not None: read_perms = discord.PermissionOverwrite(read_messages=True) await server.client.edit_channel_permissions( channel=channel, target=ev.user.member, overwrite=read_perms )
def allow(self, member_or_role): read_permit = discord.PermissionOverwrite() read_permit.read_messages = True await self.client.edit_channel_permissions(self.channel, member_or_role, read_permit) # Restrict the member from seeing the necrobot
def deny(self, member_or_role): read_deny = discord.PermissionOverwrite() read_deny.read_messages = False await self.client.edit_channel_permissions(self.channel, member_or_role, read_deny) # True if the user has admin permissions for this race
def mute(ctx, *, member : discord.Member): if not ctx.message.author.server_permissions.mute_members: return print(Fore.RED + "Command Failed To Execute |\n Command Ran In:[" + ctx.message.server.id + "]\n User:[" + ctx.message.author.id + "]\n Channel:[" + ctx.message.channel.id + "]\n Reason: " + Fore.YELLOW + "Insufficient Permissions! Both user and member need Mute Members permission!") overwrite = discord.PermissionOverwrite() overwrite.send_messages = False await client.edit_channel_permissions(ctx.message.channel, member, overwrite) await client.say("**%s** has been muted!"%member.mention) print(Fore.CYAN + "Command Successfully Executed |\n Command Ran In:[" + ctx.message.server.id + "]\n User:[" + ctx.message.author.id + "]\n Channel:[" + ctx.message.channel.id + "]")
def unmute(ctx, *, member : discord.Member): if not ctx.message.author.server_permissions.mute_members: return print(Fore.RED + "Command Failed To Execute |\n Command Ran In:[" + ctx.message.server.id + "]\n User:[" + ctx.message.author.id + "]\n Channel:[" + ctx.message.channel.id + "]\n Reason: " + Fore.YELLOW + "Insufficient Permissions! Both user and bot need Mute Members permission!") overwrite = discord.PermissionOverwrite() overwrite.send_messages = True await client.edit_channel_permissions(ctx.message.channel, member, overwrite) await client.say("**%s** has been unmuted!"%member.mention) print(Fore.CYAN + "Command Successfully Executed |\n Command Ran In:[" + ctx.message.server.id + "]\n User:[" + ctx.message.author.id + "]\n Channel:[" + ctx.message.channel.id + "]")
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))
def start_raid_group(user, message, description): """Starts a new raid group.""" global should_refresh_active_raids # get the server, use the message because user might be a webhook with no server server = message.server # find an available raid channel channel = get_available_raid_channel(server) if channel: # lock the channel locked_channels.add(channel) # purge all messages await client.purge_from(channel) try: # set the topic await client.edit_channel(channel, topic=encode_message(user, message)) # create a role with the same name as this channel role = await client.create_role(server, name=channel.name, mentionable=True) # calculate expiration time expiration_dt = adjusted_datetime(get_raid_expiration(message.timestamp)) summary_message = await client.send_message(channel, embed=get_raid_summary_embed(user, channel.name, expiration_dt, description)) # add shortcut reactions for commands await client.add_reaction(summary_message, get_leave_emoji()) # set channel permissions to make raid viewers see the raid. perms = discord.PermissionOverwrite(read_messages=True) role = await get_raid_viewer_role(server) if role is not None: await client.edit_channel_permissions(channel, role, perms) finally: # unlock the channel locked_channels.remove(channel) # refresh active raids in future should_refresh_active_raids = True return channel
def moonboard(self, ctx, *, name: str = 'moonboard'): """Sets up the starboard for this server. This creates a new channel with the specified name and makes it into the server's "starboard". If no name is passed in then it defaults to "starboard". If the channel is deleted then the starboard is deleted as well. You must have Administrator permissions to use this command or the Bot Admin role. """ server = ctx.message.server stars = self.stars.get(server.id, {}) old_starboard = self.bot.get_channel(stars.get('channel')) if old_starboard is not None: fmt = 'This channel already has a moonboard ({.mention})' await self.bot.say(fmt.format(old_starboard)) return # an old channel might have been deleted and thus we should clear all its star data stars = {} my_permissions = ctx.message.channel.permissions_for(server.me) args = [server, name] if my_permissions.manage_roles: mine = discord.PermissionOverwrite(read_messages=True, send_messages=True) everyone = discord.PermissionOverwrite(send_messages=False, embed_links=False) args.append((server.me, mine)) args.append((server.default_role, everyone)) try: channel = await self.bot.create_channel(*args) except discord.Forbidden: await self.bot.say('**Error!** I do not have permissions to create a channel.') except discord.HTTPException: await self.bot.say('**Error!** This channel name is bad or an unknown error happened.') else: stars['channel'] = channel.id await self.stars.put(server.id, stars) await self.bot.say('**Done!** Moonboard created at ' + channel.mention)
def starboard(self, ctx, channel_name: str): """Create a starboard channel. If the name specifies a NSFW channel, the starboard gets marked as NSFW. NSFW starboards allow messages from NSFW channels to be starred without any censoring. If your starboard gets marked as a SFW starboard, messages from NSFW channels get completly ignored. """ guild = ctx.guild config = await self.get_starconfig(guild.id) if config is not None: await ctx.send("You already have a starboard. If you want" " to detach josé from it, use the " "`stardetach` command") return po = discord.PermissionOverwrite overwrites = { guild.default_role: po(read_messages=True, send_messages=False), guild.me: po(read_messages=True, send_messages=True), } try: starboard_chan = await guild.create_text_channel( channel_name, overwrites=overwrites, reason='Created starboard channel') except discord.Forbidden: return await ctx.send('No permissions to make a channel.') except discord.HTTPException as err: log.exception('Got HTTP error from starboard create') return await ctx.send(f'**SHIT!!!!**: {err!r}') log.info(f'[starboard] Init starboard @ {guild.name}[{guild.id}]') # create config here config = empty_starconfig(guild) config['starboard_id'] = starboard_chan.id res = await self.starconfig_coll.insert_one(config) if not res.acknowledged: raise self.SayException('Failed to create starboard config (no ack)') await ctx.send('All done, I guess!')
def starboard(self, ctx, *, name: str = 'starboard'): """Sets up the starboard for this server. This creates a new channel with the specified name and makes it into the server's "starboard". If no name is passed in then it defaults to "starboard". If the channel is deleted then the starboard is deleted as well. You must have Administrator permissions to use this command or the Bot Admin role. """ server = ctx.message.server stars = self.stars.get(server.id, {}) old_starboard = self.bot.get_channel(stars.get('channel')) if old_starboard is not None: fmt = 'This server already has a starboard ({.mention})' await self.bot.say(fmt.format(old_starboard)) return # an old channel might have been deleted and thus we should clear all its star data stars = {} my_permissions = ctx.message.channel.permissions_for(server.me) args = [server, name] if my_permissions.manage_roles: mine = discord.PermissionOverwrite(send_messages=True, manage_messages=True, embed_links=True) everyone = discord.PermissionOverwrite(read_messages=True, send_messages=False, read_message_history=True) args.append((server.me, mine)) args.append((server.default_role, everyone)) try: channel = await self.bot.create_channel(*args) except discord.Forbidden: await self.bot.say('\N{NO ENTRY SIGN} I do not have permissions to create a channel.') except discord.HTTPException: await self.bot.say('\N{PISTOL} This channel name is bad or an unknown error happened.') else: stars['channel'] = channel.id await self.stars.put(server.id, stars) await self.bot.say('\N{GLOWING STAR} Starboard created at ' + channel.mention)
def starboard(self, ctx, *, name='starboard'): """Sets up the starboard for this server. This creates a new channel with the specified name and makes it into the server's "starboard". If no name is passed in then it defaults to "starboard". You must have Manage Server permission to use this. """ # bypass the cache just in case someone used the star # reaction earlier before having it set up, or they # decided to use the ?star command self.get_starboard.invalidate(self, ctx.guild.id) starboard = await self.get_starboard(ctx.guild.id, connection=ctx.db) if starboard.channel is not None: return await ctx.send(f'This server already has a starboard ({starboard.channel.mention}).') perms = ctx.channel.permissions_for(ctx.me) if not perms.manage_roles or not perms.manage_channels: return await ctx.send('\N{NO ENTRY SIGN} I do not have proper permissions (Manage Roles and Manage Channel)') overwrites = { ctx.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True, embed_links=True, read_message_history=True), ctx.guild.default_role: discord.PermissionOverwrite(read_messages=True, send_messages=False, read_message_history=True) } reason = f'{ctx.author} (ID: {ctx.author.id}) has created the starboard channel.' try: channel = await ctx.guild.create_text_channel(name=name, overwrites=overwrites, reason=reason) except discord.Forbidden: return await ctx.send('\N{NO ENTRY SIGN} I do not have permissions to create a channel.') except discord.HTTPException: return await ctx.send('\N{NO ENTRY SIGN} This channel name is bad or an unknown error happened.') query = "INSERT INTO starboard (id, channel_id) VALUES ($1, $2);" try: await ctx.db.execute(query, ctx.guild.id, channel.id) except: await channel.delete(reason='Failure to commit to create the ') await ctx.send('Could not create the channel due to an internal error. Join the bot support server for help.') else: self.get_starboard.invalidate(self, ctx.guild.id) await ctx.send(f'\N{GLOWING STAR} Starboard created at {channel.mention}.')