Exemple #1
0
    async def whitelist_add_role(self, ctx, *, role: discord.Role):
        """ Add a channel to automod whitelist """
        automod = cm.get(self.bot, 'automod', ctx.guild.id)
        check = cm.get(self.bot, 'roles_whitelist', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))

        if not check:
            await self.bot.db.execute(
                "INSERT INTO whitelist(guild_id, type, _id) VALUES($1, $2, $3)",
                ctx.guild.id, 2, role.id)
            self.bot.roles_whitelist[ctx.guild.id] = [role.id]
            await ctx.send(
                _("{0} Added {1} to the roles whitelist.").format(
                    self.bot.settings['emojis']['misc']['white-mark'],
                    role.mention))
        elif check:
            if role.id in check:
                raise commands.BadArgument(
                    _("Role **{0}** is already added to the whitelist.").
                    format(role))

            await self.bot.db.execute(
                "INSERT INTO whitelist(guild_id, type, _id) VALUES($1, $2, $3)",
                ctx.guild.id, 2, role.id)
            self.bot.roles_whitelist[ctx.guild.id].append(channel.id)
            await ctx.send(
                _("{0} Added {1} to the roles whitelist.").format(
                    self.bot.settings['emojis']['misc']['white-mark'],
                    role.mention))
Exemple #2
0
 async def temp_mute(self):
     try:
         for result in self.bot.temp_mutes:
             check = cm.get(self.bot, 'temp_mutes', result)
             if check:
                 now = datetime.utcnow()
                 the_time = check['time']
                 seconds = (the_time - now).total_seconds()
                 if the_time and seconds <= 0:
                     user = await self.bot.try_user(
                         int(result.split(', ')[0]))
                     guild = self.bot.get_guild(int(result.split(', ')[1]))
                     mod = await self.bot.try_user(int(check['moderator']))
                     to_disp = cm.get(self.bot, 'to_dispatch', guild.id)
                     if not to_disp:
                         self.bot.to_dispatch[guild.id] = {
                             'users': [],
                             'mod': mod
                         }
                     await default.execute_untemporary(self, 1, user, guild)
                     role = guild.get_role(int(check['role']))
                     if role:
                         member = guild.get_member(user.id)
                         await member.remove_roles(role,
                                                   reason='Auto Unmute')
                     self.bot.to_dispatch[guild.id]['users'].append(member)
     except Exception as e:
         pass
Exemple #3
0
    async def anti_links(self, message):
        link = LINKS.findall(message.content)
        invites = INVITE.search(message.content)
        current = message.created_at.replace(tzinfo=timezone.utc).timestamp()
        reason = _('Spamming links')
        automod = cm.get(self.bot, 'automod', message.guild.id)
        antilinks = cm.get(self.bot, 'links', message.guild.id)

        if not antilinks:
            return

        if invites:  # invites and links are different things
            return

        if link:
            # was unable to figure out how to add links without multiplying.
            # if link_whitelist:
            #     for li in link_whitelist:
            #         if li in link:
            #             return
            #         else:
            #             pass
            content_bucket = self.link_cooldown.get_bucket(message)
            retry = content_bucket.update_rate_limit(current)
            if automod['delete_messages'] and message.channel.permissions_for(message.guild.me).manage_messages:
                await message.delete(silent=True)

            if retry:
                content_bucket.reset()
                await self.execute_punishment(antilinks['level'], message, reason, btime.FutureTime(antilinks['time']))
Exemple #4
0
    async def raid_mode_dm(self, ctx):
        """ Toggle if new members should get a DM from bot when getting kicked or banned """
        automod = cm.get(self.bot, 'automod', ctx.guild.id)
        raidmode = cm.get(self.bot, 'raidmode', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))
        if not raidmode:
            raise commands.BadArgument(
                _("Raid mode is disabled in this server, enable it by using `{0}raid-mode toggle` command"
                  ).format(ctx.prefix))

        if raidmode['dm']:
            await self.bot.db.execute(
                "UPDATE raidmode SET dm = $1 WHERE guild_id = $2", False,
                ctx.guild.id)
            self.bot.raidmode[ctx.guild.id]['dm'] = False
            return await ctx.send(
                _("{0} I will not be DMing people when kicking or banning them anymore on raid."
                  ).format(self.bot.settings['emojis']['misc']['white-mark']))
        else:
            await self.bot.db.execute(
                "UPDATE raidmode SET dm = $1 WHERE guild_id = $2", True,
                ctx.guild.id)
            self.bot.raidmode[ctx.guild.id]['dm'] = True
            return await ctx.send(
                _("{0} I will now be DMing people when kicking or banning them on raid."
                  ).format(self.bot.settings['emojis']['misc']['white-mark']))
Exemple #5
0
    async def dev_rank_remove(self, ctx, user: discord.User, rank: str):
        """ Remove a rank from an user """

        ranks = {
            "staff": "admins",
            "booster": "boosters",
            "donator": 256,
            "bot_admin": 2
        }

        if rank not in ranks:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} Rank doesn't exist!")

        check = CM.get(self.bot, ranks[rank], user.id)

        if not check:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} Looks like user is not a {rank}")
        else:
            await self.bot.db.execute(f"DELETE FROM {ranks[rank]} WHERE user_id = $1", user.id)
            attr = getattr(self.bot, ranks[rank])
            attr.pop(user.id)
            rank = 'donator' if ranks[rank] == 'boosters' else 'bot_admin'
            badge = ctx.bot.settings['emojis']['ranks'][rank]
            badges = CM.get(self.bot, 'badges', user.id)
            await self.bot.db.execute("UPDATE badges SET flags = flags - $1 WHERE _id = $2", ranks[rank], user.id)
            self.bot.badges[user.id] -= ranks[rank]
            try:
                dm_message = f"Hey {user}! Just letting you know your rank was updated and you're not a **{rank}** anymore!"
                await user.send(dm_message)
                conf_msg = ' Sent them a DM as well.'
            except Exception:
                conf_msg = ' Was unable to send them a DM.'
                pass
            await ctx.send(f"{badge} **{user}**'s rank was updated and is not a {rank} anymore.{conf_msg} *Also remove their role*")
Exemple #6
0
async def is_guild_disabled(ctx, command):
    if ctx.guild:
        try:
            if command.parent:
                if CM.get(ctx.bot, 'guild_disabled',
                          f"{str(command.parent)}, {ctx.guild.id}"):
                    return True
                elif CM.get(
                        ctx.bot, 'guild_disabled',
                        f"{str(f'{command.parent} {command.name}')}, {ctx.guild.id}"
                ):
                    return True
                else:
                    return False
            elif not command.parent:
                if CM.get(ctx.bot, 'guild_disabled',
                          f"{str(command.name)}, {ctx.guild.id}"):
                    return True
                else:
                    return False
        except Exception as e:
            print(e)
            if CM.get(ctx.bot, 'guild_commands',
                      f"{str(command.name)}, {ctx.guild.id}"):
                return True
Exemple #7
0
    async def afk_status(self, message):
        await self.bot.wait_until_ready()

        if message.author.bot:
            return

        if not message.guild:
            return

        afks = CM.get(self.bot, 'afk',
                      f'{str(message.guild.id)}, {str(message.author.id)}')
        afks2 = CM.get(self.bot, 'afk', f'{str(message.author.id)}')
        if afks:
            await message.channel.send(_(
                "Welcome back {0}! You were away for **{1}**. Your AFK state has been removed."
            ).format(message.author.mention,
                     btime.human_timedelta(afks['time'], suffix=None)),
                                       allowed_mentions=discord.
                                       AllowedMentions(users=True))
            await self.bot.db.execute(
                "DELETE FROM afk WHERE user_id = $1 AND guild_id = $2",
                message.author.id, message.guild.id)
            self.bot.afk.pop(
                f'{str(message.guild.id)}, {str(message.author.id)}')
        elif afks2:
            await message.channel.send(_(
                "Welcome back {0}! You were away for **{1}**. Your AFK state has been removed."
            ).format(message.author.mention,
                     btime.human_timedelta(afks2['time'], suffix=None)),
                                       allowed_mentions=discord.
                                       AllowedMentions(users=True))
            await self.bot.db.execute("DELETE FROM afk WHERE user_id = $1",
                                      message.author.id)
            self.bot.afk.pop(f'{str(message.author.id)}')

        to_send = ''
        for user in message.mentions:
            check = CM.get(self.bot, 'afk',
                           f'{str(message.guild.id)}, {str(user.id)}')
            check2 = CM.get(self.bot, 'afk', f'{str(user.id)}')
            if check or check2:
                check = check if check else check2
                afkmsg = check['note']
                afkmsg = afkmsg.strip()
                member = message.guild.get_member(user.id)
                to_send += (_("Hey! **{0}** has been AFK for **{1}**"
                              " for - **{2}**.").format(
                                  member.display_name,
                                  btime.human_timedelta(check['time'],
                                                        suffix=None), afkmsg))
                try:
                    await message.reply(
                        f"{to_send}",
                        allowed_mentions=discord.AllowedMentions(
                            replied_user=True))
                except Exception:
                    try:
                        await message.author.send(to_send)
                    except Exception:
                        return
Exemple #8
0
    async def automod_mass_caps(self,
                                ctx,
                                value: AutomodValues,
                                percentage: int = None):
        """" Set the automod value for anti mass caps and set the caps percentege limit """

        automod = cm.get(self.bot, 'automod', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))

        if value['action'] != 0:
            raise commands.MissingRequiredArgument(
                self.automod_mass_caps.params['percentage'])

        if percentage and not 25 < percentage < 100:
            raise commands.BadArgument(
                _("Percentage limit must be between 25 and 100"))

        anticaps = cm.get(self.bot, 'masscaps', ctx.guild.id)
        if not anticaps and value['action'] != 0:
            await self.bot.db.execute(
                "INSERT INTO masscaps(guild_id, level, percentage, time) VALUES($1, $2, $3, $4)",
                ctx.guild.id, value['action'], percentage, value['time'])
            self.bot.masscaps[ctx.guild.id] = {
                'level': value['action'],
                'time': value['time'],
                'percentage': percentage
            }
        elif anticaps and value['action'] != 0:
            await self.bot.db.execute(
                "UPDATE masscaps SET level = $1, time = $2, percentage = $3 WHERE guild_id = $4",
                value['action'], value['time'], percentage, ctx.guild.id)
            self.bot.masscaps[ctx.guild.id] = {
                'level': value['action'],
                'time': value['time'],
                'percentage': percentage
            }
        elif anticaps and value['action'] == 0:
            await self.bot.db.execute(
                "DELETE FROM masscaps WHERE guild_id = $1", ctx.guild.id)
            self.bot.masscaps.pop(ctx.guild.id)
            return await ctx.send(
                _("{0} Successfuly disabled anti mass caps in this server").
                format(self.bot.settings['emojis']['misc']['white-mark']))
        elif not anticaps and value['action'] == 0:
            raise commands.BadArgument(
                _("Anti caps are already disabled in this server."))

        the_value = value['action']
        await ctx.send(
            _("{0} Successfully set anti mass caps punishment type to **{1}** members. Percentage set to - `{2}`.{3}"
              ).format(
                  self.bot.settings['emojis']['misc']['white-mark'],
                  automod_values(the_value), percentage,
                  _(" They will be muted/banned for 12 hours by default.")
                  if value['action'] in [5, 2] else ''))
Exemple #9
0
    async def automod_mass_mention(self,
                                   ctx,
                                   value: AutomodValues,
                                   count: int = None):
        """" Set the automod value for anti mass mention and set the mentions limit """

        automod = cm.get(self.bot, 'automod', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))

        # if value['action'] != 0:
        #     raise commands.MissingRequiredArgument(self.automod_mass_mention.params['count'])

        if count and not 1 < count < 16:
            raise commands.BadArgument(
                _("Mentions limit must be between 2 and 15"))

        antimentions = cm.get(self.bot, 'massmention', ctx.guild.id)
        if not antimentions and value['action'] != 0:
            await self.bot.db.execute(
                "INSERT INTO massmention(guild_id, level, mentions_limit, time) VALUES($1, $2, $3, $4)",
                ctx.guild.id, value['action'], count, value['time'])
            self.bot.massmention[ctx.guild.id] = {
                'level': value['action'],
                'time': value['time'],
                'limit': count
            }
        elif antimentions and value['action'] != 0:
            await self.bot.db.execute(
                "UPDATE massmention SET level = $1, time = $2, mentions_limit = $3 WHERE guild_id = $4",
                value['action'], value['time'], count, ctx.guild.id)
            self.bot.massmention[ctx.guild.id] = {
                'level': value['action'],
                'time': value['time'],
                'limit': count
            }
        elif antimentions and value['action'] == 0:
            await self.bot.db.execute(
                "DELETE FROM massmention WHERE guild_id = $1", ctx.guild.id)
            self.bot.massmention.pop(ctx.guild.id)
            return await ctx.send(
                _("{0} Successfuly disabled anti mass mention in this server").
                format(self.bot.settings['emojis']['misc']['white-mark']))
        elif not antimentions and value['action'] == 0:
            raise commands.BadArgument(
                _("Anti mass mentions are already disabled in this server."))

        the_value = value['action']
        await ctx.send(
            _("{0} Successfully set anti mass mentions punishment type to **{1}** members. Mentions limit - `{2}`.{3}"
              ).format(
                  self.bot.settings['emojis']['misc']['white-mark'],
                  automod_values(the_value), count,
                  _(" They will be muted/banned for 12 hours by default.")
                  if value['action'] in [5, 2] else ''))
Exemple #10
0
    async def reminder_remove(self, ctx, reminder: str):
        """ Remove an unwanted reminder """
        check_reminders = CM.get(self.bot, 'reminders', ctx.author.id)

        if not check_reminders:
            return await ctx.send(
                _("{0} You have no reminders.").format(
                    self.bot.settings['emojis']['misc']['warn']))

        if not reminder.isdigit():
            return await ctx.send(
                _("{0} That is not a valid id.").format(
                    self.bot.settings['emojis']['misc']['warn']))
        elif reminder not in [t for t in check_reminders]:
            return await ctx.send(
                _("{0} There is no reminder with an id of **{1}** in your reminders list."
                  ).format(self.bot.settings['emojis']['misc']['warn'],
                           reminder))

        else:
            the_reminder = check_reminders[reminder]['content']
            the_time = check_reminders[reminder]['time']
            self.bot.reminders[ctx.author.id].pop(reminder)
            await self.bot.db.execute(
                "DELETE FROM reminders WHERE user_id = $1 AND reminder = $2 AND time = $3",
                ctx.author.id, the_reminder, the_time)
            await LC.reminders(self.bot)
            await ctx.send(
                _("{0} Removed reminder from your reminders list: {1}").format(
                    self.bot.settings['emojis']['misc']['white-mark'],
                    the_reminder))
Exemple #11
0
    async def remind_list(self, ctx):
        """ Check your reminders list """
        check_reminders = CM.get(self.bot, 'reminders', ctx.author.id)

        if not check_reminders:
            return await ctx.send(
                _("{0} You have no reminders.").format(
                    self.bot.settings['emojis']['misc']['warn']))

        reminders = []
        for result in check_reminders:
            when = btime.human_timedelta(check_reminders[result]['time'],
                                         source=ctx.message.created_at)
            content = check_reminders[result]['content']
            reminders.append(
                _("`[{0}]` Reminding in **{1}**\n{2}\n").format(
                    result, when,
                    content[:150] + '...' if len(content) > 150 else content))

        paginator = Pages(
            ctx,
            entries=reminders,
            thumbnail=None,
            per_page=10,
            embed_color=ctx.bot.settings['colors']['embed_color'],
            embed_author=_("{0}'s Reminders").format(ctx.author),
            show_entry_count=True)
        await paginator.paginate()
Exemple #12
0
    async def create_reminder(self, ctx, content: str, time):
        await self.bot.db.execute(
            "INSERT INTO reminders(user_id, channel_id, message_id, time, reminder) VALUES($1, $2, $3, $4, $5)",
            ctx.author.id, ctx.channel.id, ctx.message.id, time, content)

        check_reminders = CM.get(self.bot, 'reminders', ctx.author.id)

        if not check_reminders:
            self.bot.reminders[ctx.author.id] = {
                '1': {
                    'time': time,
                    'content': content,
                    'channel': ctx.channel.id,
                    'message': ctx.message.id
                }
            }
        else:
            self.bot.reminders[ctx.author.id][str(len(check_reminders) +
                                                  1)] = {
                                                      'time': time,
                                                      'content': content,
                                                      'channel':
                                                      ctx.channel.id,
                                                      'message': ctx.message.id
                                                  }
Exemple #13
0
    async def on_raw_reaction_remove(self, payload):
        try:
            check = CM.get(self.bot, 'rr', payload.message_id)
            if not check:
                return

            with suppress(Exception):
                if str(payload.emoji) not in check['dict']:
                    the_emoji = self.bot.get_emoji(payload.emoji.id)
                    if the_emoji.animated:
                        payload.emoji = f"<a:{payload.emoji.name}:{payload.emoji.id}>"
                        if str(payload.emoji) not in check['dict']:
                            return
                else:
                    pass

            guild = self.bot.get_guild(payload.guild_id)
            member = guild.get_member(payload.user_id)

            for item in check['dict']:
                if str(payload.emoji) == item:
                    await member.remove_roles(
                        discord.Object(id=check['dict'][item]),
                        reason='Reaction Roles')
        except Exception as e:
            await default.background_error(
                self, '`raw reaction remove`', e,
                self.bot.get_guild(payload.guild_id),
                self.bot.get_channel(payload))
Exemple #14
0
    async def setafk(self,
                     ctx,
                     *,
                     note: commands.clean_content = "I'm currently AFK"):
        check = CM.get(self.bot, 'afk',
                       f"{str(ctx.guild.id)}, {str(ctx.author.id)}")

        if len(note) > 500:
            note = note[:500]
            note += '...'

        if check is not None:
            await self.bot.db.execute(
                "UPDATE afk SET message = $1 WHERE user_id = $2 AND guild_id = $3",
                note, ctx.author.id, ctx.guild.id)
            self.bot.afk[f"{str(ctx.guild.id)}, {str(ctx.author.id)}"][
                'note'] = note
            await ctx.send(
                _("{0} **Changed your AFK state to -** {1}").format(
                    self.bot.settings['emojis']['misc']['white-mark'],
                    escape_markdown(note, as_needed=False)))
        elif check is None:
            await self.bot.db.execute(
                "INSERT INTO afk(user_id, guild_id, message, time) VALUES($1, $2, $3, $4)",
                ctx.author.id, ctx.guild.id, note, datetime.now())
            self.bot.afk[f"{str(ctx.guild.id)}, {str(ctx.author.id)}"] = {
                'note': note,
                'time': datetime.now()
            }
            await ctx.send(
                _("{0} ** Set your AFK state to -** {1}").format(
                    self.bot.settings['emojis']['misc']['white-mark'],
                    escape_markdown(note, as_needed=False)))
Exemple #15
0
    async def blacklist_remove_user(self, ctx, user: discord.User, *, reason: str):
        """ Remove user from the blacklist """
        check = CM.get(self.bot, 'blacklist', user.id)

        if check and check['type'] == 2:
            if check['liftable'] != 0 and not await ctx.bot.is_owner(ctx.author):
                return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | This user cannot be unblacklisted!")
            await self.bot.db.execute("DELETE FROM blacklist WHERE _id = $1", user.id)
            self.bot.blacklist.pop(user.id)
            await self.bot.db.execute("DELETE FROM badges WHERE _id = $1", user.id)
            self.bot.badges.pop(user.id)
            e = discord.Embed(color=self.bot.settings['colors']['approve_color'], title='Blacklist state updated!', timestamp=datetime.now(timezone.utc))
            e.set_author(name=user, icon_url=user.avatar_url)
            e.description = f"Hey!\nJust wanted to let you know that your blacklist state was updated and you'll be able to use my commands again!\n**Reason:** {reason}"
            try:
                await user.send(embed=e)
                msg = ' and DMed them.'
            except Exception as e:
                msg = f', however error occured while DMing them: {e}'
            await ctx.send(f"{self.bot.settings['emojis']['misc']['white-mark']} | I've successfully removed **{user}** from the blacklist{msg}")
            await default.blacklist_log(ctx, 1, 0, user, reason)
        elif check and check['type'] == 1:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | **{user}** is blacklisted from sending DMs, only Moksej is allowed to unblacklist them.")
        elif not check:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | **{user}** is not in my blacklist.")
Exemple #16
0
    async def blacklist_add_suggestions(self, ctx, server: int, *, reason: str):
        """
        Blacklist server from submitting suggestions
        """
        to_block = self.bot.get_guild(server)

        if not to_block:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} Can't find server with this ID!")

        if await self.bot.db.fetchval("SELECT _id FROM noblack WHERE _id = $1", to_block) and not await ctx.bot.is_owner(ctx.author):
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | That server is whitelisted and cannot be blacklisted by bot admins.")

        check = CM.get(self.bot, 'blacklist', to_block.id)
        if check and check['type'] == 0:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | **{to_block}** is already in my suggestions blacklist.")
        elif check and check['type'] == 3:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | **{to_block}** is blacklisted, you shouldn't even be seeing this message though :/")
        elif not check:
            query = "INSERT INTO blacklist(_id, type, reason, dev, issued, liftable, owner_id, server_name) VALUES($1, $2, $3, $4, $5, $6, $7, $8)"
            query2 = "INSERT INTO bot_history(_id, action, dev, reason, issued, type, liftable) VALUES($1, $2, $3, $4, $5, $6, $7)"
            await self.bot.db.execute(query, to_block.id, 0, reason, ctx.author.id, datetime.now(), 0, to_block.owner.id, to_block.name)
            await self.bot.db.execute(query2, to_block.id, 1, ctx.author.id, reason, datetime.now(), 0, 0)
            self.bot.blacklist[to_block.id] = {'type': 0, 'reason': reason, 'dev': ctx.author.id, 'issued': datetime.now(), 'liftable': 0, 'owner_id': to_block.owner.id, 'server_name': to_block.name}
            await ctx.send(f"{self.bot.settings['emojis']['misc']['white-mark']} | I've successfully added **{to_block}** to the suggestions blacklist.")
            await default.blacklist_log(ctx, 0, 1, to_block, reason)
Exemple #17
0
    async def blacklist_remove_suggestions(self, ctx, server: int, *,
                                           reason: str):
        """
        Unblacklist server from submitting suggestions
        """

        check = CM.get(self.bot, 'blacklist', server)

        if check and check['type'] == 3:
            return await ctx.send(
                f"{self.bot.settings['emojis']['misc']['warn']} Server seems to be blacklisted from inviting me."
            )
        elif check and check['type'] == 0:
            query = "DELETE FROM blacklist WHERE _id = $1"
            await self.bot.db.execute(query, server)
            self.bot.blacklist.pop(server)
            await ctx.send(
                f"{self.bot.settings['emojis']['misc']['white-mark']} I've successfully unblacklisted **{check['server_name']}** ({server}) from submitting suggestions"
            )
            await default.blacklist_log(ctx, 1, 1, self.bot.get_guild(server),
                                        reason)
        elif not check:
            return await ctx.send(
                f"{self.bot.settings['emojis']['misc']['warn']} Server doesn't seem to be blacklisted from anything."
            )
Exemple #18
0
    async def automod_ignore_mods(self, ctx):
        """ Toggle whether or not bot should ignore members with manage messages permissions (moderators) """
        automod = cm.get(self.bot, 'automod', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))

        if automod['ignore_admins']:
            await self.bot.db.execute(
                "UPDATE automod SET ignore_admins = $1 WHERE guild_id = $2",
                False, ctx.guild.id)
            self.bot.automod[ctx.guild.id]['ignore_admins'] = False
            return await ctx.send(
                _("{0} I will not be ignoring people with manage messages permissions (moderators) from now on."
                  ).format(self.bot.settings['emojis']['misc']['white-mark']))
        else:
            await self.bot.db.execute(
                "UPDATE automod SET ignore_admins = $1 WHERE guild_id = $2",
                True, ctx.guild.id)
            self.bot.automod[ctx.guild.id]['ignore_admins'] = True
            return await ctx.send(
                _("{0} I will be ignoring people with manage messages permissions (moderators) from now on."
                  ).format(self.bot.settings['emojis']['misc']['white-mark']))
Exemple #19
0
    async def automod_delete_msgs(self, ctx):
        """ Toggle whether or not bot should delete the messages """
        automod = cm.get(self.bot, 'automod', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))

        if automod['delete_messages']:
            await self.bot.db.execute(
                "UPDATE automod SET delete_messages = $1 WHERE guild_id = $2",
                False, ctx.guild.id)
            self.bot.automod[ctx.guild.id]['delete_messages'] = False
            return await ctx.send(
                _("{0} I will not be deleting messages from now on.").format(
                    self.bot.settings['emojis']['misc']['white-mark']))
        else:
            await self.bot.db.execute(
                "UPDATE automod SET delete_messages = $1 WHERE guild_id = $2",
                True, ctx.guild.id)
            self.bot.automod[ctx.guild.id]['delete_messages'] = True
            return await ctx.send(
                _("{0} I will now be deleting messages from now on.").format(
                    self.bot.settings['emojis']['misc']['white-mark']))
Exemple #20
0
    async def nicknames(self, ctx, member: discord.Member = None):
        """ History of member nicknames """
        member = member or ctx.author

        if CM.get(self.bot, 'nicks_op', f'{ctx.author.id} - {ctx.guild.id}'):
            return await ctx.send(
                _("{0} | **{1}** has opted out of nickname logging.").format(
                    self.bot.settings['emojis']['misc']['warn'], member))

        nicks = await self.bot.db.fetch(
            "SELECT * FROM nicknames WHERE user_id = $1 AND guild_id = $2 ORDER BY time DESC LIMIT 10",
            member.id, ctx.guild.id)
        names = []
        for n in nicks:
            names.append(str(n['nickname']))

        if not names:
            return await ctx.send(
                _("{0} | **{1}** has had no past nicknames since I joined.").
                format(self.bot.settings['emojis']['misc']['warn'], member))

        recent = _("**{0}'s past nicknames:**").format(member)
        for num, res in enumerate(names, start=1):
            recent += f"\n`[{num}]` {escape_markdown(res, as_needed=False)}"

        await ctx.send(recent, allowed_mentions=discord.AllowedMentions.none())
Exemple #21
0
    async def blacklist_add_user(self, ctx, user: discord.User, liftable: int = 0, *, reason: str):
        """ Add user to bot's blacklist
        liftable values:
        0 - liftable
        1 - not liftable"""
        if await self.bot.is_admin(user) and not await self.bot.is_owner(user):
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | You cannot blacklist {user} because they're a part of bot staff team.")
        bslash = '\n\n'
        apply = f"{f'{bslash}If you wish to appeal, you can [join the support server]({self.bot.support})' if liftable == 0 else ''}"
        check = CM.get(self.bot, 'blacklist', user.id)

        if check and check['type'] == 2:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | **{user}** is already in my blacklist.")
        elif not check or check and check['type'] != 2:
            query = """INSERT INTO blacklist(_id, type, reason, dev, issued, liftable)
                        VALUES($1, $2, $3, $4, $5, $6)
                        ON CONFLICT (_id) DO UPDATE
                        SET type = $2, reason = $3
                        WHERE blacklist._id = $1 """
            await self.bot.db.execute(query, user.id, 2, reason, ctx.author.id, datetime.now(), liftable)
            self.bot.blacklist[user.id] = {'type': 2, 'reason': reason, 'dev': ctx.author.id, 'issued': datetime.now(), 'liftable': liftable}
            badge = self.bot.settings['emojis']['ranks']['blocked']
            await self.bot.db.execute("INSERT INTO badges(_id, flags) VALUES($1, $2)", user.id, 2048)
            self.bot.badges[user.id] = 2048
            await self.bot.db.execute("INSERT INTO bot_history(_id, action, dev, reason, issued, type) VALUES($1, $2, $3, $4, $5, $6)", user.id, 1, ctx.author.id, reason, datetime.now(), 2)
            e = discord.Embed(color=self.bot.settings['colors']['deny_color'], title='Blacklist state updated!', timestamp=datetime.now(timezone.utc))
            e.set_author(name=user, icon_url=user.avatar_url)
            e.description = f"Hey!\nI'm sorry, but your blacklist state was updated and you won't be able to use my commands anymore!\n**Reason:** {reason}{apply}"
            try:
                await user.send(embed=e)
                msg = ' and DMed them.'
            except Exception as e:
                msg = f', however error occured while DMing them: {e}'
            await ctx.send(f"{self.bot.settings['emojis']['misc']['white-mark']} | I've successfully added **{user}** to the blacklist{msg}")
            await default.blacklist_log(ctx, 0, 0, user, reason)
Exemple #22
0
    async def removebadge_server(self, ctx, server: int, badge: str):
        guild = self.bot.get_guild(server)

        if not guild:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | Server not found")

        attr = getattr(self.bot, 'settings')
        try:
            attr['emojis']['ranks'][badge]
        except Exception as e:
            e = discord.Embed(color=self.bot.settings['colors']['deny_color'], title='Invalid badge')
            badges = 'Those are the valid ones:\n'
            for badge in attr['emojis']['ranks']:
                badges += f'`{badge}`, '
            e.description = badges[:-2]
            return await ctx.send(embed=e)
        badges = CM.get(self.bot, 'badges', guild.id)

        if not getattr(publicflags.BotFlags(badges if badges else 0), badge):
            return await ctx.send(f"**{guild}** doesn't have {attr['emojis']['ranks'][badge]} badge")
        else:
            badge_value = default.badge_values(ctx)
            self.bot.badges[guild.id] -= badge_value[badge]
            await self.bot.db.execute("UPDATE badges SET flags = flags - $1 WHERE _id = $2", badge_value[badge], guild.id)
            await ctx.send(f"Removed {attr['emojis']['ranks'][badge]} from {guild} badges")
Exemple #23
0
    async def addbadge_server(self, ctx, server: int, badge: str):
        guild = self.bot.get_guild(server)

        if not guild:
            return await ctx.send(f"{self.bot.settings['emojis']['misc']['warn']} | Server not found")

        attr = getattr(self.bot, 'settings')
        try:
            attr['emojis']['ranks'][badge]
        except Exception as e:
            e = discord.Embed(color=self.bot.settings['colors']['deny_color'], title='Invalid badge')
            badges = 'Those are the valid ones:\n'
            for badge in attr['emojis']['ranks']:
                badges += f'`{badge}`, '
            e.description = badges[:-2]
            return await ctx.send(embed=e)
        badges = CM.get(self.bot, 'badges', guild.id)

        if getattr(publicflags.BotFlags(badges if badges else 0), badge):
            return await ctx.send(f"**{guild}** already has {attr['emojis']['ranks'][badge]}")
        else:
            badge_value = default.badge_values(ctx)
            if badges:
                self.bot.badges[guild.id] += badge_value[badge]
                await self.bot.db.execute("UPDATE badges SET flags = flags + $1 WHERE _id = $2", badge_value[badge], guild.id)
            else:
                self.bot.badges[guild.id] = badge_value[badge]
                await self.bot.db.execute("INSERT INTO badges(_id, flags) VALUES($1, $2)", guild.id, badge_value[badge])
            await ctx.send(f"Added {attr['emojis']['ranks'][badge]} to {guild} badges")
Exemple #24
0
    async def removebadge_user(self, ctx, user: typing.Union[discord.User, str], badge: str):
        user = await default.find_user(ctx, user)

        if not user:
            return await ctx.send(f"{ctx.bot.settings['emojis']['misc']['warn']} | User could not be found")

        attr = getattr(self.bot, 'settings')
        try:
            attr['emojis']['ranks'][badge]
        except Exception as e:
            e = discord.Embed(color=self.bot.settings['colors']['deny_color'], title='Invalid badge')
            badges = 'Those are the valid ones:\n'
            for badge in attr['emojis']['ranks']:
                badges += f'`{badge}`, '
            e.description = badges[:-2]
            return await ctx.send(embed=e)
        badges = CM.get(self.bot, 'badges', user.id)

        if not getattr(publicflags.BotFlags(badges if badges else 0), badge):
            return await ctx.send(f"**{user}** doesn't have {attr['emojis']['ranks'][badge]} badge")
        else:
            badge_value = default.badge_values(ctx)
            self.bot.badges[user.id] -= badge_value[badge]
            await self.bot.db.execute("UPDATE badges SET flags = flags - $1 WHERE _id = $2", badge_value[badge], user.id)
            await ctx.send(f"Removed {attr['emojis']['ranks'][badge]} from {user} badges")
Exemple #25
0
    async def dev_rank_add(self, ctx, user: discord.User, rank: str):
        """ Add a rank for user """

        ranks = {
            "staff": "admins",
            "booster": "boosters",
            "donator": 256,
            "bot_admin": 2
        }

        if rank not in ranks:
            return await ctx.send(
                f"{self.bot.settings['emojis']['misc']['warn']} Rank doesn't exist!"
            )

        check = CM.get(self.bot, ranks[rank], user.id)

        if check:
            return await ctx.send(
                f"{self.bot.settings['emojis']['misc']['warn']} Looks like user is already a {rank}"
            )
        else:
            await self.bot.db.execute(
                f"INSERT INTO {ranks[rank]} VALUES($1, $2)", user.id, '-')
            attr = getattr(self.bot, ranks[rank])
            attr[user.id] = '-'
            rank = 'donator' if ranks[rank] == 'boosters' else 'bot_admin'
            badge = ctx.bot.settings['emojis']['ranks'][rank]
            if CM.get(self.bot, 'badges', user.id):
                await self.bot.db.execute(
                    "UPDATE badges SET flags = flags + $1 WHERE _id = $2",
                    ranks[rank], user.id)
            else:
                await self.bot.db.execute("INSERT INTO badges VALUES($1, $2)",
                                          user.id, ranks[rank])
            await LC.reloadall(self.bot)
            try:
                dm_message = f"Hey {user}! Just letting you know your rank was updated and you're now a **{rank}**!"
                await user.send(dm_message)
                conf_msg = ' Sent them a DM as well.'
            except Exception:
                conf_msg = ' Was unable to send them a DM.'
                pass
            await ctx.send(
                f"{badge} **{user}**'s rank was updated and is now a {rank}.{conf_msg} *Also add them a role*"
            )
Exemple #26
0
    async def automod_anti_spam(self, ctx, value: AutomodValues):
        """" Set the automod value for anti spam """

        automod = cm.get(self.bot, 'automod', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))

        antispam = cm.get(self.bot, 'spam', ctx.guild.id)
        if not antispam and value['action'] != 0:
            await self.bot.db.execute(
                "INSERT INTO antispam(guild_id, level, time) VALUES($1, $2, $3)",
                ctx.guild.id, value['action'], value['time'])
            self.bot.spam[ctx.guild.id] = {
                'level': value['action'],
                'time': value['time']
            }
        elif antispam and value['action'] != 0:
            await self.bot.db.execute(
                "UPDATE antispam SET level = $1, time = $2 WHERE guild_id = $3",
                value['action'], value['time'], ctx.guild.id)
            self.bot.spam[ctx.guild.id] = {
                'level': value['action'],
                'time': value['time']
            }
        elif antispam and value['action'] == 0:
            await self.bot.db.execute(
                "DELETE FROM antispam WHERE guild_id = $1", ctx.guild.id)
            self.bot.spam.pop(ctx.guild.id)
            return await ctx.send(
                _("{0} Successfuly disabled anti spam in this server").format(
                    self.bot.settings['emojis']['misc']['white-mark']))
        elif not antispam and value['action'] == 0:
            raise commands.BadArgument(
                _("Anti spam is already disabled in this server."))

        the_value = value['action']
        await ctx.send(
            _("{0} Successfully set anti spam punishment type to **{1}** members.{2}"
              ).format(
                  self.bot.settings['emojis']['misc']['white-mark'],
                  automod_values(the_value),
                  _(" They will be muted/banned for 12 hours by default.")
                  if value['action'] in [5, 2] else ''))
Exemple #27
0
    async def anti_spam(self, message):
        current = message.created_at.replace(tzinfo=timezone.utc).timestamp()
        reason = _("Spam (sending multiple messages in a short time span)")
        automod = cm.get(self.bot, 'automod', message.guild.id)
        antispam = cm.get(self.bot, 'spam', message.guild.id)

        if not antispam:
            return

        content_bucket = self.messages_cooldown.get_bucket(message)
        if content_bucket.update_rate_limit(current):
            content_bucket.reset()
            await self.execute_punishment(antispam['level'], message, reason, btime.FutureTime(antispam['time']))

        user_bucket = self.user_cooldowns.get_bucket(message)
        if user_bucket.update_rate_limit(current):
            user_bucket.reset()
            await self.execute_punishment(antispam['level'], message, reason, btime.FutureTime(antispam['time']))
Exemple #28
0
    async def on_anti_raid(self, member):
        if not member.guild:
            return

        automod = cm.get(self.bot, 'automod', member.guild.id)
        raidmode = cm.get(self.bot, 'raidmode', member.guild.id)
        if not (automod or raidmode):
            return

        if not member.guild.me.guild_permissions.ban_members or not member.guild.me.guild_permissions.kick_members:
            return

        if not self.new_member(member) and raidmode['action'] in [1, 2]:
            return

        for coro in self.raidmode.copy():
            if await coro(self, member):
                break
Exemple #29
0
    async def whitelist_list(self, ctx, what: str):
        """ See a list of whitelisted roles/channels for automod
        Types: `roles`, `channels`"""

        automod = cm.get(self.bot, 'automod', ctx.guild.id)

        if not automod:
            raise commands.BadArgument(
                _("Automod is disabled in this server, enable it by using `{0}automod toggle` command"
                  ).format(ctx.prefix))

        whitelist_list = []
        if what == 'channels':
            channels_list = cm.get(self.bot, 'channels_whitelist',
                                   ctx.guild.id)
            if not channels_list:
                return await ctx.send(
                    _("{0} There are no whitelisted channels in the server."))

            embed_title = _("List of whitelisted channels")
            for num, channel in enumerate(channels_list, start=1):
                whitelist_list.append(
                    f"`[{num}]` {self.bot.get_channel(channel)} ({channel})")
        elif what == 'roles':
            roles_list = cm.get(self.bot, 'channels_whitelist', ctx.guild.id)
            if not roles_list:
                return await ctx.send(
                    _("{0} There are no whitelisted roles in the server."))

            embed_title = _("List of whitelisted roles")
            for num, role in enumerate(roles_list, start=1):
                whitelist_list.append(
                    f"`[{num}]` {ctx.guild.get_role(role)} ({role})")

        paginator = Pages(
            ctx,
            title=embed_title,
            entries=whitelist_list,
            thumbnail=None,
            per_page=10,
            embed_color=self.bot.settings['colors']['embed_color'],
            author=ctx.author)
        await paginator.paginate()
Exemple #30
0
    async def anti_mentions(self, message):
        current = message.created_at.replace(tzinfo=timezone.utc).timestamp()
        reason = _('Spamming mentions')
        automod = cm.get(self.bot, 'automod', message.guild.id)
        massmention = cm.get(self.bot, 'massmention', message.guild.id)

        if not massmention:
            return

        limit = massmention['limit']
        if len(message.mentions) > limit:
            content_bucket = self.mentions_limit.get_bucket(message)
            retry = content_bucket.update_rate_limit(current)
            if automod['delete_messages'] and message.channel.permissions_for(message.guild.me).manage_messages:
                await message.delete()

            if retry:
                content_bucket.reset()
                await self.execute_punishment(massmention['level'], message, reason, btime.FutureTime(massmention['time']))