tasks.TaskCog.__init__()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
"""Cog for tasks that are scheduled to run"""
2
from datetime import datetime
3
from discord.ext import commands, tasks
4
from bot import utils
5
6
7
class TaskCog(commands.Cog, name="Tasks"):
8
    """
9
    Task Cog
10
11
        Cog that holds tasks for the bot
12
13
    **Tasks:**
14
        - :ref:`error_report`: Output all errors for a day to admin channels.
15
16
    """
17
18
    def __init__(self, bot):
19
        self.bot = bot
20
        if self.bot.daily_reporting:
21
            self.report_errors.start()  # pylint: disable=no-member
22
23
    @commands.command(name="disable-daily-reporting")
24
    @commands.check(utils.check_admin)
25
    async def disable_error_reporting(self, ctx: commands.Context):
26
        """Disable Error Reporting for server"""
27
        await utils.insert("keys", ["daily-report", False])
28
        self.report_errors.stop()
29
        self.bot.daily_reporting = False
30
        await ctx.send("Daily reporting has been disabled")
31
32
    @commands.command(name="enable-daily-reporting")
33
    @commands.check(utils.check_admin)
34
    async def enable_error_reporting(self, ctx: commands.Context):
35
        """Enable Error Reporting for server"""
36
        await utils.insert("keys", ["daily-report", True])
37
        self.report_errors.start()
38
        self.bot.daily_reporting = True
39
        await ctx.send("Daily reporting has been enabled")
40
41
    @tasks.loop(hours=24.0)
42
    async def report_errors(self) -> None:
43
        """
44
        Report error
45
46
        Every 24 hours, all errors for the current day are sent to the admin channels.
47
48
        :return: None
49
        """
50
        date = datetime.utcnow().strftime("%Y-%m-%d")
51
        error_record = [
52
            error
53
            for error in await utils.select(
54
                "errors", "id, message, error, ack", "date_trunc('day', time)", date
55
            )
56
            if error[-1] is False
57
        ]
58
        if not error_record:
59
            errors = f"No errors found for {date}"
60
        else:
61
            errors = f"Errors for {date}.\n"
62
            for error in error_record:
63
                errors += f"- {error[0]}: {error[1]}; {error[2]}\n\n"
64
        await utils.admin_log(self.bot, errors, True)
65
66
67
async def setup(bot: commands.Bot) -> None:
68
    """Needed for extension loading"""
69
    await bot.add_cog(TaskCog(bot))
70