def __init__(self, ctx, *, entries, per_page=12, show_entry_count=True, embed_color=discord.Color.blurple(), title=None, thumbnail=None, footericon=None, footertext=None, author=None, delete_after=None): self.bot = ctx.bot self.entries = entries self.message = ctx.message self.channel = ctx.channel self.author = author if author else ctx.author self.thumbnail = thumbnail self.footericon = footericon self.footertext = footertext self.title = title self.delete_after = delete_after self.per_page = per_page pages, left_over = divmod(len(self.entries), self.per_page) if left_over: pages += 1 self.maximum_pages = pages self.embed = discord.Embed(colour=embed_color) self.paginating = len(entries) > per_page self.show_entry_count = show_entry_count self.reaction_emojis = [ ('\U000023ee\U0000fe0f', self.first_page), ('\N{BLACK LEFT-POINTING TRIANGLE}', self.previous_page), ('\U000023f9', self.stop_pages), ('\N{BLACK RIGHT-POINTING TRIANGLE}', self.next_page), ('\U000023ed\U0000fe0f', self.last_page) ] if ctx.guild is not None: self.permissions = self.channel.permissions_for(ctx.guild.me) else: self.permissions = self.channel.permissions_for(ctx.bot.user) if not self.permissions.embed_links: raise commands.BotMissingPermissions( 'I do not have permissions to embed links.') if not self.permissions.send_messages: raise commands.BotMissingPermissions('Bot cannot send messages.') if self.paginating: # verify we can actually use the pagination session if not self.permissions.add_reactions: raise commands.BotMissingPermissions( 'I do not have permissions to add reactions.') if not self.permissions.read_message_history: raise commands.BotMissingPermissions( 'I do not have permissions to Read Message History.')
def __init__(self, ctx, **kwargs): self.bot = ctx.bot self.message = ctx.message self.channel = ctx.channel self.context = ctx self.entries = kwargs.get('entries') self.per_page = kwargs.get('per_page', 2) self.show_entry_count = kwargs.get('show_entry_count', True) self.paginating = True self.author = kwargs.get("author", ctx.author) self.embed_colour = kwargs.get('colour', discord.Colour.blue()) self.title = kwargs.get('title', None) self.thumbnail = kwargs.get('thumbnail', None) self.embed_author = kwargs.get('author', None) self.footericon = kwargs.get('footericon', None) self.footertext = kwargs.get('footertext', None) self.delete_after = kwargs.get('delete_after', 300) pages, left_over = divmod(len(self.entries), self.per_page) if left_over: pages += 1 self.maximum_pages = pages self.embed = discord.Embed(colour=self.embed_colour) self.reaction_emojis = [('⏮️', self.first_page), ('◀️', self.previous_page), ('⏹️', self.stop_pages), ('▶️', self.next_page), ('⏭️', self.last_page)] if ctx.guild is not None: self.permissions = self.channel.permissions_for(ctx.guild.me) else: self.permissions = self.channel.permissions_for(ctx.bot.user) if not self.permissions.embed_links: raise commands.BotMissingPermissions(['embed_links']) if not self.permissions.send_messages: raise commands.BotMissingPermissions('Bot cannot send messages.') if self.paginating: if not self.permissions.add_reactions: raise commands.BotMissingPermissions( 'I do not have permissions to add reactions.') if not self.permissions.read_message_history: raise commands.BotMissingPermissions( 'I do not have permissions to Read Message History.')
async def cog_check(self, ctx): if not ctx.guild: raise commands.NoPrivateMessage player = self.bot.lavalink.player_manager.create( ctx.guild.id, endpoint=ctx.guild.region.value) should_connect = ctx.command.name in [ "play", "playskip", "nowplaying", "seek", "skip", "stop", "pause", "volume", "disconnect", "queue", "remove", "musicplayer", ] does_not_require_user_connect = ctx.command.name in [ "nowplaying", "queue", "musicplayer" ] if (ctx.author.voice is None or ctx.author.voice.channel is None ) and not does_not_require_user_connect: if not (player.is_connected and await ctx.bot.is_owner(ctx.author)): raise UserNotInVC if not player.is_connected: if not should_connect: raise BotNotInVC permissions = ctx.author.voice.channel.permissions_for(ctx.me) if not permissions.connect: raise commands.BotMissingPermissions(["connect"]) if not permissions.speak: raise commands.BotMissingPermissions(["speak"]) player.store("channel", ctx.channel.id) await self.connect_to(ctx.guild.id, str(ctx.author.voice.channel.id)) if ctx.author.voice and player.is_connected and int( player.channel_id) != ctx.author.voice.channel.id: raise UserInWrongVC return True
def __init__(self, ctx, *, entries, per_page=12, show_entry_count=True, embed_color=discord.Color.blurple(), title=None, thumbnail=None, footericon=None, footertext=None, author=None, delete_after=None, embed_author=None, home=None): self.bot = ctx.bot self.entries = entries self.message = ctx.message self.channel = ctx.channel self.context = ctx self.author = author if author else ctx.author self.thumbnail = thumbnail self.footericon = footericon self.footertext = footertext self.home = home self.title = title self.embed_author = embed_author self.delete_after = 300 self.per_page = per_page pages, left_over = divmod(len(self.entries), self.per_page) if left_over: pages += 1 self.maximum_pages = pages self.embed = discord.Embed(colour=embed_color) self.paginating = True self.show_entry_count = show_entry_count self.reaction_emojis = [ ('<:arrowleft:820332901559173150>', self.first_page), ('<:arrleft:820332933893586985>', self.previous_page), ('<:stop:820332883470319637>', self.stop_pages), ('<:arrright:820332951518445619>', self.next_page), ('<:arrowright:820332915795034123>', self.last_page), ('\U0001f3d8', self.main_help) # ('<:python:682881809649762358>', self.show_help) ] if ctx.guild is not None: self.permissions = self.channel.permissions_for(ctx.guild.me) else: self.permissions = self.channel.permissions_for(ctx.bot.user) if not self.permissions.embed_links: raise commands.BotMissingPermissions(['embed_links']) if not self.permissions.send_messages: raise commands.BotMissingPermissions('Bot cannot send messages.') if self.paginating: # verify we can actually use the pagination session if not (self.permissions.add_reactions or self.permissions.use_external_emojis): raise commands.BotMissingPermissions('I do not have permissions to add reactions.') if not self.permissions.read_message_history: raise commands.BotMissingPermissions('I do not have permissions to Read Message History.')
async def global_check(ctx: custom.Context) -> Literal[True]: user_config = await ctx.bot.user_manager.get_config(ctx.author.id) if user_config.blacklisted is True: raise exceptions.EmbedError( colour=colours.RED, description=f"You are blacklisted from using this bot.\n\n" f"*If you would like to appeal this please join my [support server]({values.SUPPORT_LINK}).*", ) current = dict(ctx.channel.permissions_for(ctx.me)) if not ctx.guild: current["read_messages"] = True needed = { permission: value for permission, value in values.PERMISSIONS if value is True } if missing := [ permission for permission, value in needed.items() if current[permission] != value ]: raise commands.BotMissingPermissions(missing)
async def kill(self, ctx, member: Member, *args): Grund = " ".join(args) if Grund.rstrip() == "": Grund = "Leer" VoiceState = member.voice if VoiceState: if VoiceState.channel.permissions_for(ctx.author).move_members: if VoiceState.channel.permissions_for( ctx.guild.get_member(self.bot.user.id)).move_members: if ctx.author.roles[-1] >= member.roles[-1]: await member.edit( voice_channel=None, reason="Von Moderator " + ctx.author.name + "#" + ctx.author.discriminator + " angefordert: " + Grund) raise SuccessMessage("Benutzer Getötet", fields=[("Betroffener", member.mention), ("Grund", Grund)]) raise ErrorMessage( message= "Deine Rolle ist nicht höher als oder gleich wie die des Benutzers, den du töten wolltest!" ) raise commands.BotMissingPermissions([]) raise commands.MissingPermissions([]) raise ErrorMessage( message="Der Benutzer befindet sich nicht in einem Sprachkanal.")
async def webhook_edit( self, ctx: cmd.Context, channel: converter.Never, webhook: converter.WebhookConverter, new_name: str = None, ): """Edits an existing webhook If webhook names contains spaces, it must be in quotes. To edit the avatar, attach a image file with the message. """ channel_perms = webhook.channel.permissions_for(ctx.me) if not channel_perms.view_channel or not channel_perms.manage_webhooks: raise commands.BotMissingPermissions(["manage_webhooks"]) edit_kwargs = {} if new_name: edit_kwargs["name"] = new_name if len(ctx.message.attachments) > 0: edit_kwargs["avatar"] = await ctx.message.attachments[0].read() if len(edit_kwargs.keys()) <= 0: raise commands.UserInputError("No new name or avatar was given") await webhook.edit(**edit_kwargs) webhook = await self.bot.fetch_webhook(webhook.id) await ctx.prompt(embed=self.get_webhook_embed( ctx, webhook, message="Webhook edited"))
async def webhook_url( self, ctx: cmd.Context, channel: converter.Never, *, webhook: converter.WebhookConverter, ): """Obtains the URL for a given webhook""" channel_perms = webhook.channel.permissions_for(ctx.me) if not channel_perms.view_channel or not channel_perms.manage_webhooks: raise commands.BotMissingPermissions(["manage_webhooks"]) try: await ctx.author.send( embed=self.get_webhook_embed(ctx, webhook, show_url=True)) await ctx.channel.send(embed=discord.Embed( title="Webhook URL sent", description= "Because the URL should be kept secret, a message has been sent to your DMs.", )) except discord.Forbidden: await ctx.channel.send(embed=discord.Embed( title="Forbidden", description= "Could not send DM, check server privacy settings or unblock me.", ))
async def set(self, ctx, channel: discord.TextChannel): """ Sets the current starboard channel, if none was set before, this command also enables the starboard """ embed = discord.Embed() # Checking if we have enough permissions in order to operate the starboard on the designated channel required_perms = discord.Permissions().none() required_perms.update(send_messages=True, manage_messages=True, read_messages=True) if (not required_perms.is_subset(channel.permissions_for(ctx.guild.me))): raise commands.BotMissingPermissions(["send_messages", "manage_messages", "read_messages"]) self.bot.logger.info(f"Starboard set to channel {channel.id} for server named {ctx.guild.name}") self.bot.database.session.query(Server).\ filter(Server.discord_id == ctx.guild.id).\ update({Server.starboard_channel_id : channel.id}) self.bot.database.session.commit() embed.title = await ctx.bot.get_translation(ctx, "success_title") embed.description = f"{await ctx.bot.get_translation(ctx, 'success_starboard_set')}: {channel.mention}" embed.colour = discord.Color.green() await ctx.send(embed=embed)
async def prepare_help_command(self, ctx: commands.Context, command: commands.Command): """Prepares the help command. Desinged for internal call only. Args: ctx (commands.Context): The context help was invoked in. command (commands.Command): The command help was invoked for. Raises: commands.BotMissingPermissions: The bot is missing permissions needed to run the paginator. """ if ctx.guild is not None: perms = ctx.channel.permissions_for(ctx.guild.me) missing: List[str] = [] if not perms.embed_links: missing.append("Embed Links") if not perms.read_message_history: missing.append("Read Message History") if not perms.add_reactions: missing.append("Add Reactions") if missing: raise commands.BotMissingPermissions(missing) self.paginator.clear() self.paginator.ending_note = self.get_ending_note() await super().prepare_help_command(ctx, command)
async def ban(self, actor, target, reason, duration=None): if not self.guild.me.guild_permissions.ban_members: raise commands.BotMissingPermissions(["ban_members"]) if isinstance(target, discord.Member): if (target.top_role.position >= actor.top_role.position or self.guild.owner == target) and actor != self.guild.owner: raise AccessDenied() await self.guild.ban(target, reason=f"{actor}: {reason}", delete_message_days=self.ban_purge_days) case = await self.insert(actor, target, "ban", reason) log = await LoggingHandler.new(self.bot, self.guild) if duration is not None: await self.timer("ban", target, case, duration) await log.dispatch("MEMBER_TEMPBAN", target, target=target, actor=actor, duration=time_since(seconds=duration), reason=reason, case=case) else: await log.dispatch("MEMBER_BAN", target, target=target, actor=actor, reason=reason, case=case) return case
async def connect_(self, ctx, *, channel: VoiceChannel = None): """PFXconnect <channel>""" try: await ctx.message.delete() except discord.HTTPException: pass if not channel: try: channel = ctx.author.voice.channel except AttributeError: raise commands.UserInputError( 'No channel to join. Please either specify a valid channel or join one.' ) player = self.bot.wavelink.get_player(ctx.guild.id, cls=Player) cperms = self.bot.getperms(ctx.guild.me, channel) if 'connect' in cperms and 'speak' in cperms: do = 'nothing' else: raise commands.BotMissingPermissions(['connect', 'speak']) try: if player.is_connected: if ctx.author.voice.channel and ctx.guild.me.voice.channel: if ctx.author.voice.channel == ctx.guild.me.voice.channel: return except AttributeError: await player.connect(channel.id) player.cmdchannel_id = ctx.channel.id await player.connect(channel.id) player.cmdchannel_id = ctx.channel.id
async def movehere(self, ctx, member: Member): if member.voice: if ctx.author.voice: if member.voice.channel.permissions_for( ctx.author).move_members: if member.voice.channel.permissions_for( ctx.guild.get_member( self.bot.user.id)).move_members: await member.edit( voice_channel=ctx.author.voice.channel, reason="Von Moderator " + ctx.author.name + "#" + ctx.author.discriminator + " angefordert.") await ctx.sendEmbed( title="Hierhin bewegt", color=self.color, fields=[("Betroffener", member.mention), ("Kanal", ctx.author.voice.channel.name)]) else: raise commands.BotMissingPermissions([]) else: raise commands.MissingPermissions([]) else: raise commands.BadArgument( message="Du befindest sich nicht in einem Sprachkanal.") else: raise commands.BadArgument( message="Der Benutzer befindet sich nicht in einem Sprachkanal." )
async def kill(self, ctx, member: Member): Grund = ctx.getargs() if Grund.rstrip() == "": Grund = "Leer" VoiceState = member.voice if VoiceState: if VoiceState.channel.permissions_for(ctx.author).move_members: if VoiceState.channel.permissions_for( ctx.guild.get_member(self.bot.user.id)).move_members: if ctx.author.roles[-1] >= member.roles[-1]: await member.edit( voice_channel=None, reason="Von Moderator " + ctx.author.name + "#" + ctx.author.discriminator + " angefordert: " + Grund) await ctx.sendEmbed(title="Benutzer Getötet", color=self.color, fields=[("Betroffener", member.mention), ("Grund", Grund)]) else: raise commands.BadArgument( message= "Deine Rolle ist nicht höher als oder gleich wie die des Benutzers, den du töten wolltest!" ) else: raise commands.BotMissingPermissions([]) else: raise commands.MissingPermissions([]) else: raise commands.BadArgument( message="Der Benutzer befindet sich nicht in einem Sprachkanal." )
async def webhook_list(self, ctx: cmd.Context, channel: discord.TextChannel = None): """Lists webhooks for the server or a given channel""" if channel: channel_perms = channel.permissions_for(ctx.me) if not channel_perms.view_channel or not channel_perms.manage_webhooks: raise commands.BotMissingPermissions(["manage_webhooks"]) embed = discord.Embed( title="Webhooks", description=f"Use {get_command_signature(ctx, self.webhook_get)}" " to get more info on a webhook.", ) embed.set_footer( text="Page {current_page}/{total_pages}, " "showing webhook {first_field}..{last_field}/{total_fields}." ) paginator = menus.FieldPaginator(self.bot, base_embed=embed) for webhook in await ctx.guild.webhooks(): if webhook.type != discord.WebhookType.incoming: continue if channel and webhook.channel_id != channel.id: continue paginator.add_field( name=webhook.name, value=f"Channel: {webhook.channel.mention}\nID: {webhook.id}", ) await paginator.send(ctx)
async def webhook_new( self, ctx: cmd.Context, channel: discord.TextChannel, *, name: str ): """Creates a new webhook for a given channel""" channel_perms = channel.permissions_for(ctx.me) if not channel_perms.view_channel or not channel_perms.manage_webhooks: raise commands.BotMissingPermissions(["manage_webhooks"]) if len(name) > 80: await ctx.prompt( embed=discord.Embed( title="Webhook name too long", description="Webhook names can only be up to 80 characters long", ) ) return avatar_file = ( await ctx.message.attachments[0].read() if len(ctx.message.attachments) > 0 else None ) webhook = await channel.create_webhook(name=name, avatar=avatar_file) await ctx.prompt( embed=self.get_webhook_embed(ctx, webhook, message="New webhook created") )
def predicate(ctx): if ctx.guild: permissions = ctx.me.guild_permissions missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] if not missing: return True raise commands.BotMissingPermissions(missing) return True
def guild_and_admin(ctx): if not isinstance(ctx.channel, discord.abc.GuildChannel): raise commands.NoPrivateMessage() if not ctx.channel.permissions_for(ctx.author).administrator: raise commands.MissingPermissions(["administrator"]) if not ctx.channel.permissions_for(ctx.me).administrator: raise commands.BotMissingPermissions(["administrator"]) return True
def _help_error(ctx, missing_perms): old_send = ctx.send async def new_send(content, **kwargs): content += ' You can also turn on DMs if you wish.' await old_send(content, **kwargs) ctx.send = new_send raise commands.BotMissingPermissions(missing_perms)
def check_bot_permissions(channel, bot, **permissions): """ Check if the bot has the permissions for the channel """ channel_permissions = channel.permissions_for(bot) missing_permissions = [p for p, v in permissions.items() if getattr(channel_permissions, p, None) != v] if missing_permissions: raise commands.BotMissingPermissions(missing_permissions) return True
def predicate(ctx): permissions = ctx.author.voice.channel.permissions_for(ctx.guild.me) missing = [ perm for perm, value in perms.items() if getattr(permissions, perm) != value ] if missing: raise commands.BotMissingPermissions(missing) return True