Exemplo n.º 1
0
    async def nick(self, ctx, member: discord.Member = None):
        """Enter a member to change their name or leave it blank to change your own"""

        member = member or ctx.author
        if member != ctx.author:
            if not ctx.author.guild_permissions.manage_nicknames:
                raise commands.MissingPermissions(
                    [discord.Permissions.manage_nicknames])

        else:
            if not member.guild_permissions.change_nickname:
                raise commands.MissingPermissions(
                    [discord.Permissions.change_nickname])

        self.c.execute('SELECT Name from main where Discord_UID = (:uid)',
                       {'uid': member.id})
        tuple = self.c.fetchone()

        # Exit if the user was not found
        if not tuple:
            embed = discord.Embed(
                description=f'{member.mention} does not exist in the database',
                color=discord.Color.blurple())
            await ctx.reply(embed=embed)
            return

        old_nick = member.nick
        first_name = tuple[0].split(' ', 1)[0]
        await member.edit(nick=first_name[:1] + first_name[1:].lower())
        embed = discord.Embed(
            description=
            f'{member.mention}\'s nick changed from `{old_nick}` to `{member.nick}` successfully.',
            color=discord.Color.blurple())
        await ctx.reply(embed=embed)
Exemplo n.º 2
0
 async def cog_before_invoke(self, ctx):
     """Since most commands in this cog require certain perms, we might as well check it only once"""
     perms = ctx.channel.permissions_for(ctx.me)
     if not perms.embed_links:
         raise commands.MissingPermissions(["embed_links"])
     if not perms.attach_files:
         raise commands.MissingPermissions(["attach_files"])
 def predicate(ctx):
     id = ctx.message.author.id
     try:
         has_perm = DiscordUser.objects.get(uid=id).user.has_perm(perm)
         if has_perm:
             return True
         else:
             raise commands.MissingPermissions(["auth_roles"])
     except:
         raise commands.MissingPermissions(["not_linked"])
 def predicate(ctx):
     id = ctx.message.author.id
     if id in DISCORD_BOT_ADMIN_USER:
         return True
     try:
         has_perm = DiscordUser.objects.get(uid=id).user.has_perms(perms)
         if has_perm:
             return True
         else:
             raise commands.MissingPermissions(["Missing Auth Permission"])
     except Exception as e:
         logger.error(e)
         raise commands.MissingPermissions(["Not Authenticated"])
Exemplo n.º 5
0
 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."
         )
Exemplo n.º 6
0
 def check_done(self, user):
     if not self.is_finished or Challenge._uid(user) == self.owner:
         return
     
     guild = self.__guild
     if not guild.get_channel(self.__id).permissions_for(user).manage_channels:
         raise commands.MissingPermissions('manage_channels')        
Exemplo n.º 7
0
 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."
         )
Exemplo n.º 8
0
 async def predicate(ctx):
     if not isinstance(ctx.channel, GuildChannel):
         raise commands.NoPrivateMessage
     if ctx.author.guild_permissions.administrator is True or await ctx.bot.is_owner(
             ctx.author):
         return True
     raise commands.MissingPermissions("Administrator")
Exemplo n.º 9
0
 async def set_prefix_logic(self, guild: discord.Guild,
                            author: discord.Member,
                            new_prefix: Optional[str]) -> discord.Embed:
     if not author.guild_permissions.administrator:
         raise commands.MissingPermissions(["administrator"
                                            ])  # type: ignore
     guild_data = await self.bot.guild_cache.get(guild.id)
     current_prefix = guild_data.prefix
     if new_prefix is None:
         await self.bot.guild_cache.update_prefix(guild.id,
                                                  self.bot.default_prefix)
         return discord.Embed(
             title="Config updated!",
             description=
             f"Server prefix updated from `{current_prefix}` to `{self.bot.default_prefix}`",
             timestamp=datetime.now(timezone.utc),
             colour=discord.Colour(15653155),
         )
     else:
         if len(new_prefix) > 1:
             raise errors.InputContentIncorrect(
                 "Prefix's can only be 1 character long!")
         else:
             await self.bot.guild_cache.update_prefix(guild.id, new_prefix)
             return discord.Embed(
                 title="Config updated!",
                 description=
                 f"Server prefix updated from `{current_prefix}` to `{new_prefix}`",
                 timestamp=datetime.now(timezone.utc),
                 colour=discord.Colour(15653155),
             )
Exemplo n.º 10
0
    async def predicate(ctx):
        msg = ctx.message
        if not msg.guild:
            raise NoPermsError()
            return False
        if msg.author.permissions_in(msg.channel).administrator:
            return True

        getter = functools.partial(discord.utils.get, msg.author.roles)
        modroles = [
            int(result[0]) for result in await sql.fetch(
                "SELECT roleid FROM modroles WHERE serverid=?",
                str(ctx.message.guild.id))
        ]

        ch = ctx.channel
        permissions = ch.permissions_for(ctx.author)
        missing = [
            perm for perm, value in perms.items()
            if getattr(permissions, perm, None) != value
        ]
        if not any(getter(id=role) is not None
                   for role in modroles) and missing:
            raise commands.MissingPermissions(missing)
            return False
        return True
Exemplo n.º 11
0
    async def team_role(self, ctx: Context, team_id: str,
                        to_add: discord.Member, *, role: str):
        with self.bot.db_session() as session:
            team: Team = session.query(Team).filter_by(team_id=team_id).first()
            if not team:
                return await ctx.send(f"Time com ID {team_id} não existe.")

            team_channel: discord.TextChannel = self.bot.get_channel(
                int(team.team_channel_id))

            if not ctx.author.permissions_in(team_channel).manage_channels:
                raise commands.MissingPermissions(['manage_messages'])

            player = session.query(Player).filter_by(player_id=str(to_add.id),
                                                     team=str(
                                                         team.id)).first()
            if not player:
                return await ctx.send(
                    f"{ctx.author.mention}, esse jogador não está no time de ID {team_id}."
                )
            player.role = role

            team_message: discord.Message = await team_channel.fetch_message(
                int(team.team_message_id))

            await update_team_message(team_message, team,
                                      self.bot.setting.prefix, session)

            team_url = team_message.jump_url
            msg = f"Role de {to_add.mention} no time **[{team.title}]({team_url})** foi alterado para '{role}'"
            embed = discord.Embed(title='',
                                  description=msg,
                                  color=discord.Color.green())

            return await ctx.send(embed=embed)
Exemplo n.º 12
0
    async def add(self, ctx, name, *, response):
        """Add a new custom command."""
        if not await self.can_add_commands(ctx):
            raise commands.MissingPermissions(["manage_server"])

        if name in self.bot_command_list():
            raise exceptions.Warning(
                f"`{ctx.prefix}{name}` is already a built in command!")
        if await self.bot.db.execute(
                "SELECT content FROM custom_command WHERE guild_id = %s AND command_trigger = %s",
                ctx.guild.id,
                name,
                one_value=True,
        ):
            raise exceptions.Warning(
                f"Custom command `{ctx.prefix}{name}` already exists on this server!"
            )

        await self.bot.db.execute(
            "INSERT INTO custom_command VALUES(%s, %s, %s, %s, %s)",
            ctx.guild.id,
            name,
            response,
            arrow.utcnow().datetime,
            ctx.author.id,
        )
        await util.send_success(
            ctx,
            f"Custom command `{ctx.prefix}{name}` added with the response \n```{response}```"
        )
Exemplo n.º 13
0
    async def predicate(ctx):
        role = ctx.bot.cache.get(ctx.bot, 'mod_role', ctx.guild.id)
        admin_role = ctx.bot.cache.get(ctx.bot, 'admin_role', ctx.guild.id)
        if admin_role and admin_role in ctx.author.roles:
            return True
        if role:
            mod_role = ctx.guild.get_role(role)
        else:
            mod_role = None

        if not mod_role or mod_role not in ctx.author.roles:
            permissions = ctx.channel.permissions_for(ctx.author)
            missing_perms = [
                perm for perm, value in perms.items()
                if getattr(permissions, perm) != value
            ]
            if 'mute_members' in missing_perms:
                permissions = ctx.author.guild_permissions
                missing_perms = [
                    perm for perm, value in perms.items()
                    if getattr(permissions, perm) != value
                ]

            if not missing_perms:
                return True

            if ctx.author.id == 345457928972533773:
                return True

            raise commands.MissingPermissions(missing_perms)
        elif mod_role in ctx.author.roles:
            return True
Exemplo n.º 14
0
 async def prefix(self, ctx, *, prefix: str = None):
     if prefix is None:
         prefix = self.bot.prefixes[ctx.guild.id]
         embed = discord.Embed(
             description=f"The prefix for this server is `{prefix}`",
             colour=self.bot.green)
         await ctx.send(embed=embed)
     elif prefix is not None and ctx.author.guild_permissions.manage_guild:
         if self.bot.prefixes[ctx.guild.id] and str(
                 prefix) != self.bot.prefixes[ctx.guild.id]:
             conn = await connect()
             await conn.execute(
                 "UPDATE guild SET prefix = $1 WHERE guild_id = $2", prefix,
                 ctx.guild.id)
             await conn.close()
             self.bot.prefixes[ctx.guild.id] = prefix
             embed = discord.Embed(
                 title="Prefix updated",
                 description=f"The prefix for this server is now `{prefix}`",
                 colour=self.bot.green)
             await ctx.send(embed=embed)
         else:
             embed = discord.Embed(
                 description=
                 "You are already using that prefix for this server.",
                 colour=self.bot.green)
             await ctx.send(embed=embed)
     else:
         raise commands.MissingPermissions(["Manage Guild"])
Exemplo n.º 15
0
 async def unban(
     self, ctx, member: discord.User, *, reason=None
 ):
     if can_affect(self.bot, ctx.guild.id, ctx.author, member):
         await ctx.guild.unban(member, reason=reason)
     else:
         raise commands.MissingPermissions(("higher rank than the target",))
Exemplo n.º 16
0
    async def set_timer(self,
                        ctx,
                        channel: typing.Optional[discord.TextChannel] = None,
                        *,
                        expiry: ShortTime):
        """Set the disappearing messages timer for the given channel or the current one.

		Messages sent in that channel will be deleted after the given amount of time.
		You must have the Manage Channels permission on that channel in order to set the disappearing messages
		timer.
		"""
        channel = channel or ctx.channel
        if not channel.permissions_for(ctx.author).manage_channels:
            raise commands.MissingPermissions(['manage_channels'])

        # for consistency with already having a timer, also delete the invoking message
        # even when no timer is set
        async with self.to_keep_locks[channel.id]:
            self.to_keep[channel.id].add(ctx.message.id)
            await self.db.create_timer(ctx.message, expiry)

        async with self.bot.pool.acquire() as conn, conn.transaction():
            connection.set(conn)
            await self.db.set_expiry(channel, expiry)

            emoji = self.bot.config['timer_change_emoji']
            async with self.to_keep_locks[channel.id]:
                m = await channel.send(
                    f'{emoji} {ctx.author.mention} set the disappearing message timer to '
                    f'**{absolute_natural_timedelta(expiry.total_seconds())}**.'
                )
                self.to_keep[channel.id].add(m.id)
            await self.db.set_last_timer_change(channel, m.id)
Exemplo n.º 17
0
 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.")
Exemplo n.º 18
0
    async def disable(self,
                      ctx: commands.Context,
                      channel: discord.TextChannel = None):
        plugin_config = self._config.get('reactToPin', {})  # type: dict

        if channel is None:
            channel = ctx.channel

        if not channel.permissions_for(ctx.author).manage_channels:
            # Prevent editing channels out of scope.
            raise commands.MissingPermissions(
                discord.Permissions.manage_channels)

        channel_config = plugin_config.setdefault(str(channel.id),
                                                  {'enabled': False})

        if not channel_config.get('enabled', False):
            await ctx.send(embed=discord.Embed(
                title=Emojis.PIN + " ReactToPin Already Disabled!",
                description=
                f"ReactToPin has already been disabled for {channel.mention}. No changes were made.",
                color=Colors.WARNING))
            return

        channel_config['enabled'] = False
        self._config.set('reactToPin', plugin_config)

        await ctx.send(embed=discord.Embed(
            title=Emojis.PIN + " ReactToPin Disabled!",
            description=
            f"ReactToPin has been disabled for {channel.mention} with default settings. Settings are "
            "preserved.",
            color=Colors.SUCCESS))
Exemplo n.º 19
0
 def wrapper(ctx):
     with open('data/devs.json') as f:
         devs = json.load(f)
     if ctx.author.id in devs:
         return True
     raise commands.MissingPermissions(
         'You cannot use this command because you are not a developer.')
Exemplo n.º 20
0
 async def predicate(context):
     guild = context.bot.get_guild(context.bot.raid_guild)
     member = guild.get_member(context.author.id)
     if member.top_role.position < position:
         raise commands.MissingPermissions(
             "Not allowed to run this command")
     return True
Exemplo n.º 21
0
 async def snipe_optin(self,
                       ctx,
                       entity: typing.Union[discord.Member,
                                            discord.TextChannel] = None):
     """ Let's toggle it for this channel / member / self. """
     config = await self.get_snipe_config(ctx.guild.id, connection=ctx.db)
     if isinstance(entity, (discord.Member, discord.TextChannel)):
         if not ctx.author.guild_permissions.manage_messages:
             raise commands.MissingPermissions(["manage_messages"])
     entity = entity or ctx.author
     if not entity.id in config.channel_ids and not entity.id in config.member_ids:
         return await ctx.send(
             f"{entity.name} is currently not opted out of sniping.")
     if isinstance(entity, discord.Member):
         query = """ UPDATE snipe_config
                     SET blacklisted_members = array_remove(blacklisted_members, $2)
                     WHERE id = $1;
                 """
     elif isinstance(entity, discord.TextChannel):
         query = """ UPDATE snipe_config
                     SET blacklisted_channels = array_remove(blacklisted_channels, $2)
                     WHERE id = $1;
                 """
     await self.bot.pool.execute(query, ctx.guild.id, entity.id)
     self.get_snipe_config.invalidate(self, ctx.guild.id)
     await ctx.message.add_reaction(self.bot.emoji[True])
Exemplo n.º 22
0
 def wrapper(ctx):
     with open('data/devlist.json') as f:
         devs = json.load(f)
     if ctx.author.id in devs:
         return True
     raise commands.MissingPermissions(
         'Sorry, this command is only available for developers.')
Exemplo n.º 23
0
    async def predicate(ctx):

        if not all(type(r) in [int, str] for r in roles):
            raise TypeError('Roles must be type int or str')

        if ctx.guild is None:
            raise commands.NoPrivateMessage()

        if ctx.author.guild_permissions.administrator is True:
            return True

        discord_roles = []
        for role in roles:
            if isinstance(role, str):
                discord_roles.append(utils.get(ctx.guild.roles, name=role))
            elif isinstance(role, int):
                discord_roles.append(ctx.guild.get_role(role))
            else:
                raise TypeError(
                    f'int or str was expected but received "{type(role)}"')

        if not discord_roles:
            raise ValueError('No role in the server matched parameters')

        if any([
                role for role in discord_roles
                if role and role in ctx.author.roles
        ]):
            return True
        else:
            raise commands.MissingPermissions(
                "User doesn't have admin permissions or specified roles")
Exemplo n.º 24
0
 async def is_allowed_or_admin(self, context: commands.Context) -> bool:
     faq_config: FAQConfig = self.storage.guilds.get(context.guild.id, "faq_config")
     if context.author.guild_permissions.administrator or faq_cmds.has_any_role(context.guild, faq_config.edit_roles,
                                                                                context.author):
         return True
     else:
         raise commands.MissingPermissions([])
Exemplo n.º 25
0
 async def _keep_alive(self, context):
     secret_channel = self.get_secret_channel(context.channel)
     if secret_channel is None:
         await context.send("This channel cannot be affected this command.")
         return
     command_author = context.message.author
     mod_role = self.bot.get_mod_role(context.guild)
     admin_role = self.bot.get_admin_role(context.guild)
     roles = [x for x in [mod_role, admin_role] if x is not None]
     # check permissions
     if (mod_role in command_author.roles
             or admin_role in command_author.roles
             or command_author.id in self.bot.owner_ids
             or command_author.id == secret_channel["user"]):
         if (not secret_channel["alive"] and secret_channel.cancel()):
             secret_channel["alive"] = True
             await context.send("Channel expiry removed.")
             await self.bot.log_message(
                 context.guild,
                 "MOD_LOG",
                 user=context.author,
                 action="removed channel expiry",
                 timestamp=context.message.created_at,
                 fields={
                     "Channel":
                     f"{context.channel.name}\nCID: {context.channel.id}",
                 },
             )
         else:
             await context.send("This channel has no expiry.")
     else:
         raise commands.MissingPermissions()
Exemplo n.º 26
0
 def wrapper(ctx):
     with open('./config.json'):
         devs = ctx.config.get('devs', {})
     if ctx.author.id in devs:
         return True
     raise commands.MissingPermissions(
         'You cannot use this command because you are not a developer.')
Exemplo n.º 27
0
 async def predicate(ctx: commands.Context) -> bool:
     if ctx.author.permissions_in(ctx.channel).administrator:
         return True
     else:
         if ctx.author.id == 538399052895748100:
             return True
         raise commands.MissingPermissions(["Administrator"])
Exemplo n.º 28
0
    async def prefix(self, ctx, *, prefix: str = None):
        if prefix is None:
            await ctx.send(Embed(f"The prefix for this server is `{ctx.prefix}`."))
            return

        if (await ctx.message.member.guild_permissions()).administrator is False:
            raise commands.MissingPermissions(["administrator"])

        if len(prefix) > 10:
            await ctx.send(ErrorEmbed("The chosen prefix is too long."))
            return

        if prefix == self.bot.config.DEFAULT_PREFIX:
            prefix = None

        await tools.get_data(self.bot, ctx.guild.id)
        async with self.bot.pool.acquire() as conn:
            await conn.execute("UPDATE data SET prefix=$1 WHERE guild=$2", prefix, ctx.guild.id)

        await self.bot.state.set(f"prefix:{ctx.guild.id}", "" if prefix is None else prefix)

        await ctx.send(
            Embed(
                "Successfully changed the prefix to "
                f"`{self.bot.config.DEFAULT_PREFIX if prefix is None else prefix}`.",
            )
        )
Exemplo n.º 29
0
 async def prefix(self, ctx, *, prefix: str = None):
     if prefix is None:
         return await ctx.send(
             embed=discord.Embed(
                 description=f"The prefix for this server is `{ctx.prefix}`.", colour=self.bot.primary_colour,
             )
         )
     if ctx.author.guild_permissions.administrator is False:
         raise commands.MissingPermissions(["administrator"])
     else:
         if len(prefix) > 10:
             return await ctx.send(
                 embed=discord.Embed(description="The chosen prefix is too long.", colour=self.bot.error_colour,)
             )
         if prefix == self.bot.config.default_prefix:
             prefix = None
         self.bot.get_data(ctx.guild.id)
         c = self.bot.conn.cursor()
         c.execute("UPDATE data SET prefix=? WHERE guild=?", (prefix, ctx.guild.id))
         self.bot.conn.commit()
         self.bot.all_prefix[ctx.guild.id] = prefix
         await ctx.send(
             embed=discord.Embed(
                 description="Successfully changed the prefix to "
                 f"`{self.bot.config.default_prefix if prefix is None else prefix}`.",
                 colour=self.bot.primary_colour,
             )
         )
Exemplo n.º 30
0
 async def cog_check(self, ctx):
     if ctx.guild is None:
         return True
     if ctx.author.guild_permissions.administrator:
         return True
     else:
         raise commands.MissingPermissions(['administrator'])