Пример #1
0
    async def initial_unbans(self):
        try:
            data = json.loads(self.redis.get(f"{self.bot.bot_name}:timeouts-discord"))
            for user in data:
                unban_date = utils.parse_date(data[user]["unban_date"])
                time_now = utils.now()
                resp_timeout = data.get("resp_timeout", "")
                resp_timeout += " after " if resp_timeout else ""
                if unban_date < time_now:
                    ScheduleManager.execute_now(
                        method=self.unban,
                        args=[
                            data[user]["discord_id"],
                            f"Unbanned by timer{resp_timeout}",
                        ],
                    )
                    continue
                ScheduleManager.execute_delayed(
                    delay=(unban_date - time_now).seconds,
                    method=self.unban,
                    args=[data[user]["discord_id"], f"Unbanned by timer{resp_timeout}"],
                )
        except Exception as e:
            log.exception(e)
            self.redis.set(f"{self.bot.bot_name}:timeouts-discord", json.dumps({}))

        with DBManager.create_session_scope() as db_session:
            unnamed_users = db_session.query(User).filter_by(user_name="").all()
            for user in unnamed_users:
                member = self.get_member(int(user.discord_id))
                if not member:
                    db_session.delete(user)
                    continue

                user.user_name = str(member)
Пример #2
0
    async def _ban(
        self, user, timeout_in_seconds=0, reason=None, delete_message_days=0
    ):
        delete_message_days = (
            7
            if delete_message_days > 7
            else (0 if delete_message_days < 0 else delete_message_days)
        )

        if not self.guild:
            return
        if not user:
            return
        try:
            ban = await self.guild.fetch_ban(user)
            if ban:
                return
        except:
            pass
        if timeout_in_seconds > 0:
            reason = f"{reason} for {timeout_in_seconds} seconds"
            timeouts = json.loads(self.redis.get("timeouts-discord"))
            timeouts[str(user.id)] = {
                "discord_id": str(user.id),
                "unban_date": str(utils.now() + timedelta(seconds=timeout_in_seconds)),
                "reason": str(reason)
            }
            self.redis.set("timeouts-discord", json.dumps(timeouts))
            ScheduleManager.execute_delayed(delay=timeout_in_seconds, method=self.unban, args=[user.id, "Unbanned by timer"])
        await self.guild.ban(
            user=user, reason=reason, delete_message_days=delete_message_days
        )
Пример #3
0
 def enable(self, settings):
     self.settings = settings
     self.salt = utils.random_string()
     with DBManager.create_session_scope() as db_session:
         current_timeouts = Timeout._active_timeouts(db_session)
         for timeout in current_timeouts:
             if timeout.time_left:
                 ScheduleManager.execute_delayed(
                     timeout.time_left + 1,
                     self.auto_untimeout,
                     args=[timeout.id, self.salt],
                 )
Пример #4
0
    async def ban(self, user, timeout_in_seconds=0, reason=None, delete_message_days=0):
        delete_message_days = (
            7
            if delete_message_days > 7
            else (0 if delete_message_days < 0 else delete_message_days)
        )

        if not self.guild:
            return False
        if not user:
            return False
        try:
            ban = await self.guild.fetch_ban(user)
            if ban:
                return False
        except:
            return False
        try:
            resp_timeout = utils.seconds_to_resp(timeout_in_seconds)
            reason += (
                f" for {resp_timeout}!" if timeout_in_seconds > 0 else " Permanently!"
            )
            await self.guild.ban(
                user=user, reason=reason, delete_message_days=delete_message_days
            )
            if timeout_in_seconds > 0:
                timeouts = json.loads(
                    self.redis.get(f"{self.bot.bot_name}:timeouts-discord")
                )
                timeouts[str(user.id)] = {
                    "discord_id": str(user.id),
                    "unban_date": str(
                        utils.now() + timedelta(seconds=timeout_in_seconds)
                    ),
                    "resp_timeout": resp_timeout,
                    "reason": str(reason),
                }
                self.redis.set(
                    f"{self.bot.bot_name}:timeouts-discord", json.dumps(timeouts)
                )
                ScheduleManager.execute_delayed(
                    delay=timeout_in_seconds,
                    method=self.unban,
                    args=[user.id, f"Unbanned by timer after {resp_timeout}"],
                )
        except:
            return False
        return True
Пример #5
0
 def initial_unbans(self):
     try:
         data = json.loads(self.redis.get("timeouts-discord"))
         for user in data:
             unban_date = data[user]["unban_date"]
             if ":" in unban_date[-5:]:
                 unban_date = f"{unban_date[:-5]}{unban_date[-5:-3]}{unban_date[-2:]}"
             unban_date = datetime.strptime(unban_date, "%Y-%m-%d %H:%M:%S.%f%z")
             time_now = utils.now()
             if unban_date < time_now:
                 ScheduleManager.execute_now(method=self.unban, args=[data[user]["discord_id"], "Unbanned by timer"])
                 continue
             ScheduleManager.execute_delayed(delay=(unban_date - time_now).seconds, method=self.unban, args=[data[user]["discord_id"], "Unbanned by timer"])
     except Exception as e:
         log.exception(e)
         self.redis.set("timeouts-discord", json.dumps({}))
Пример #6
0
 def enable(self, bot):
     if not bot:
         return
     try:
         reminders_list = json.loads(self.redis.get("remind-me-reminders"))
         """
         { 
             user_id: {
                 "message_id": message_id,
                 "message": message,
                 "date_of_reminder": date_of_reminder,
             },
         }
         """
     except:
         self.redis.set("remind-me-reminders", json.dumps({}))
         reminders_list = {}
     new_reminders_list = {}
     for user in reminders_list:
         user_reminders = reminders_list[user]
         new_user_reminders = []
         for reminder in user_reminders:
             salt = random_string()
             date_of_reminder = reminder["date_of_reminder"]
             if ":" in date_of_reminder[-5:]:
                 date_of_reminder = f"{date_of_reminder[:-5]}{date_of_reminder[-5:-3]}{date_of_reminder[-2:]}"
             date_of_reminder = datetime.strptime(date_of_reminder, "%Y-%m-%d %H:%M:%S.%f%z")
             if date_of_reminder < utils.now():
                 continue
             new_user_reminders.append(reminder)
             self.reminder_tasks[salt] = ScheduleManager.execute_delayed((date_of_reminder-utils.now()).seconds, self.execute_reminder, args=[salt, reminder])
Пример #7
0
 def enable(self, bot):
     if not bot:
         return
     try:
         reminders_list = json.loads(
             self.redis.get(f"{self.bot.bot_name}:remind-me-reminders"))
         """
         { 
             user_id: [
                 {
                     "message_id": message_id,
                     "channel_id": channel_id,
                     "salt": salt,
                     "message": message,
                     "date_of_reminder": date_of_reminder,
                     "date_reminder_set": date_reminder_set
                 },
             ],
         }
         """
     except:
         self.redis.set(f"{self.bot.bot_name}:remind-me-reminders",
                        json.dumps({}))
         reminders_list = {}
     new_reminders_list = {}
     for user_id in reminders_list:
         user_reminders = reminders_list[user_id]
         new_user_reminders = []
         for reminder in user_reminders:
             salt = reminder["salt"]
             date_of_reminder = utils.parse_date(
                 reminder["date_of_reminder"])
             if date_of_reminder < utils.now():
                 continue
             new_user_reminders.append(reminder)
             self.reminder_tasks[salt] = ScheduleManager.execute_delayed(
                 (date_of_reminder - utils.now()).total_seconds(),
                 self.execute_reminder,
                 args=[salt, user_id, reminder],
             )
         new_reminders_list[user_id] = new_user_reminders
     self.redis.set(f"{self.bot.bot_name}:remind-me-reminders",
                    json.dumps(new_reminders_list))
Пример #8
0
 async def create_reminder(self, bot, author, channel, message, args):
     command_args = message.split(" ") if message else []
     try:
         reminders_list = json.loads(
             self.redis.get(f"{self.bot.bot_name}:remind-me-reminders"))
         """
         { 
             user_id: [
                 {
                     "message_id": message_id,
                     "channel_id": channel_id,
                     "message": message,
                     "date_of_reminder": date_of_reminder,
                     "date_reminder_set": date_reminder_set
                 },
             ],
         }
         """
     except:
         self.redis.set(f"{self.bot.bot_name}:remind-me-reminders",
                        json.dumps({}))
         reminders_list = {}
     user_reminders = (reminders_list[str(author.id)]
                       if str(author.id) in reminders_list else [])
     if len(user_reminders) >= int(self.settings["max_reminders_per_user"]):
         await self.bot.say(
             channel,
             f"{author.mention} you already have {len(user_reminders)} reminders!",
         )
         return False
     if len(command_args) == 0:
         await self.bot.say(channel, embed=self.help)
         return False
     time_delta = utils.parse_timedelta(command_args[0])
     if not time_delta:
         await self.bot.say(
             channel, f"{author.mention} invalid time: {command_args[0]}")
         return False
     await self.bot.say(
         channel,
         f"{author.mention} ill remind you that in {utils.seconds_to_resp(time_delta.total_seconds())}",
     )
     bot_message = await self.bot.say(
         channel,
         f"If anyone else wants to be reminded click the {self.settings['emoji']}",
     )
     salt = utils.random_string()
     await bot_message.add_reaction(self.settings["emoji"])
     reminder = {
         "message_id": bot_message.id,
         "channel_id": bot_message.channel.id,
         "salt": salt,
         "message": " ".join(command_args[1:]),
         "date_of_reminder": str(utils.now() + time_delta),
         "date_reminder_set": str(utils.now()),
     }
     user_reminders.append(reminder)
     reminders_list[str(author.id)] = user_reminders
     self.redis.set(f"{self.bot.bot_name}:remind-me-reminders",
                    json.dumps(reminders_list))
     self.reminder_tasks[salt] = ScheduleManager.execute_delayed(
         time_delta.total_seconds(),
         self.execute_reminder,
         args=[salt, author.id, reminder],
     )
Пример #9
0
 def execute_delayed(self, delay, function, *args, **kwargs):
     ScheduleManager.execute_delayed(delay,
                                     lambda: function(*args, **kwargs))
Пример #10
0
    async def timeout_user(self, db_session, member, banner, until,
                           ban_reason):
        if not self.settings["enabled"]:
            return False, "Module is not enabled"
        current_timeout = Timeout._is_timedout(db_session, str(member.id))
        new_timeout = None
        if current_timeout is not None:
            if current_timeout.check_lengths(until):
                current_timeout.active = False
                new_timeout = Timeout._create(db_session, str(member.id),
                                              str(banner.id), until,
                                              ban_reason)
                db_session.commit()
                current_timeout.unban(
                    db_session,
                    None,
                    f"Timeout overwritten by Timeout #{new_timeout.id}",
                )
                db_session.commit()
            else:
                return (
                    False,
                    f"{member} is currently timedout by Timeout #{current_timeout.id}",
                )
        if not new_timeout:
            new_timeout = Timeout._create(db_session, str(member.id),
                                          str(banner.id), until, ban_reason)
            db_session.commit()
        await self.apply_timeout(member, new_timeout)

        if self.settings["log_timeout"]:
            embed = discord.Embed(
                title="Member has been timedout",
                timestamp=new_timeout.created_at,
                colour=member.colour,
            )
            embed.set_author(
                name=f"{member} ({member.id})- Timeout Removed",
                icon_url=str(member.avatar_url),
            )
            embed.add_field(
                name="Banned on",
                value=str(
                    new_timeout.created_at.strftime("%b %d %Y %H:%M:%S %Z")),
                inline=False,
            )
            if new_timeout.issued_by_id:
                issued_by = self.bot.filters.get_member(
                    [int(new_timeout.issued_by_id)], None, {})[0]
                embed.add_field(
                    name="Banned by",
                    value=issued_by.mention
                    if issued_by else f"{new_timeout.issued_by_id}",
                    inline=False,
                )
            if new_timeout.ban_reason:
                embed.add_field(name="Ban Reason",
                                value=str(new_timeout.ban_reason),
                                inline=False)
            await HandlerManager.trigger("aml_custom_log", embed=embed)
        if new_timeout.time_left:
            ScheduleManager.execute_delayed(
                new_timeout.time_left + 5,
                self.auto_untimeout,
                args=[new_timeout.id, self.salt],
            )
        return True, None