Passed
Branch BonHowi (675753)
by Bartosz
01:44
created

SpotStatsCog.get_old_stats()   A

Complexity

Conditions 4

Size

Total Lines 15
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 15
rs 9.75
c 0
b 0
f 0
cc 4
nop 2
1
import discord
2
from cogs.databasecog import DatabaseCog
3
from discord.ext import commands, tasks
4
from discord.utils import get
5
from cogs import cogbase
6
from discord_slash import cog_ext
7
8
9
class SpotStatsCog(cogbase.BaseCog):
10
    def __init__(self, base):
11
        super().__init__(base)
12
        self.hex_to_int = "%02x%02x%02x"
13
        self.lege_total = 0
14
        self.rare_total = 0
15
        self.common_total = 0
16
        self.update_spot_stats_loop.start()
17
18
    @cog_ext.cog_slash(name="updatedbwitholdstats", guild_ids=cogbase.GUILD_IDS,
19
                       description=" ",
20
                       default_permission=True,
21
                       permissions=cogbase.PERMISSION_MODS
22
                       )
23
    async def get_old_stats(self, ctx):
24
        await ctx.send("Generating spots stats", delete_after=5)
25
26
        guild = self.bot.get_guild(self.bot.guild[0])
27
        channel = self.bot.get_channel(self.bot.ch_common)
28
        async for message in channel.history(limit=None, oldest_first=True):
29
            for member in guild.members:
30
                if member == message.author:
31
                    await DatabaseCog.db_count_spot(member.id, "common", "")
32
        self.create_log_msg("Finished updating database")
33
34
    async def get_channel_history(self, channel_id, channel_type) -> list:
35
        guild = self.bot.get_guild(self.bot.guild[0])
36
        channel = self.bot.get_channel(channel_id)
37
        roles_list = []
38
        async for message in channel.history(limit=None, oldest_first=True):
39
            if message.content.startswith("<@&8"):  # If message is a ping for a role
40
                seq_type = type(message.content)
41
                role_id = int(seq_type().join(filter(seq_type.isdigit, message.content)))
42
                role = get(guild.roles, id=role_id)
43
                if role:
44
                    roles_list.append(self.get_monster_name(role, channel_type))
45
        roles_list = list(filter(None, roles_list))
46
        return roles_list
47
48
    def get_monster_name(self, role, channel_type):
49
        monster_found = None
50
        for monster in self.bot.config["commands"]:
51
            if monster["name"].lower() == role.name.lower() or role.name.lower() in monster["triggers"]:
52
                monster_found = monster
53
                break
54
        if monster_found["type"] == channel_type:
55
            return role.name
56
57
    async def create_spots_list(self, member_id: int, channel_type: int):
58
        spots_df = await DatabaseCog.db_get_total_spots_df(member_id, channel_type)
59
        spots_df = spots_df.to_dict(orient='records')
60
        spots_df = spots_df[0]
61
        del spots_df['member_id']
62
        top_print = []
63
        total = 0
64
        for key, value in spots_df.items():
65
            spotting_stats = [f"{key}:  **{value}**"]
66
            top_print.append(spotting_stats)
67
            total += value
68
        return top_print, total
69
70
    async def update_spot_stats(self, channel_id: int, channel_type: int):
71
        spot_stats_ch = self.bot.get_channel(self.bot.ch_spotting_stats)
72
        top_print, total = await self.create_spots_list(self.bot.user.id, channel_type)
73
        top_print = ['\n'.join([elem for elem in sublist]) for sublist in top_print]
74
        top_print = "\n".join(top_print)
75
76
        if channel_type == 1:
77
            embed_title = "LEGENDARY"
78
            embed_color = int(self.hex_to_int % (163, 140, 21), 16)
79
            self.lege_total = total
80
        elif channel_type == 0:
81
            embed_title = "RARE"
82
            embed_color = int(self.hex_to_int % (17, 93, 178), 16)
83
            self.rare_total = total
84
        else:
85
            embed_title = "OTHER"
86
            embed_color = int(self.hex_to_int % (1, 1, 1), 16)
87
88
        embed_command = discord.Embed(title=f"{embed_title}", description=top_print, color=embed_color)
89
        embed_command.add_field(name="Total", value=f"**{total}**", inline=False)
90
        dt_string = self.bot.get_current_time()
91
        embed_command.set_footer(text=f"{dt_string}")
92
        await spot_stats_ch.send(embed=embed_command)
93
94
        channel = self.bot.get_channel(channel_id)
95
        self.create_log_msg(f"Spotting stats updated - {channel.name}")
96
97
    @tasks.loop(hours=12)
98
    async def update_spot_stats_loop(self):
99
        spot_stats_ch = self.bot.get_channel(self.bot.ch_spotting_stats)
100
        await spot_stats_ch.purge()
101
        await self.update_spot_stats(self.bot.ch_legendary_spot, 1)
102
        await self.update_spot_stats(self.bot.ch_rare_spot, 0)
103
        self.create_log_msg(f"All spotting stats updated")
104
105
    @update_spot_stats_loop.before_loop
106
    async def before_update_spot_stats_loop(self):
107
        self.create_log_msg(f"Waiting until Bot is ready")
108
        await self.bot.wait_until_ready()
109
110
    # TODO: code refactoring
111
    # Member own stats
112
    @cog_ext.cog_slash(name="mySpottingStats", guild_ids=cogbase.GUILD_IDS,
113
                       description="Get detailed spotting stats to your dm",
114
                       default_permission=True,
115
                       permissions=cogbase.PERMISSION_MODS
116
                       )
117
    async def get_spotting_stats(self, ctx):
118
        await ctx.send("Generating spots stats", delete_after=5)
119
120
        # Legendary
121
        leges_list, leges_total = await self.create_spots_list(ctx.author.id, 1)
122
        leges_print = ['\n'.join([elem for elem in sublist]) for sublist in leges_list]
123
        leges_print = "\n".join(leges_print)
124
125
        leges_color = int(self.hex_to_int % (163, 140, 21), 16)
126
        embed_command = discord.Embed(title=f"Legendary", description=leges_print, color=leges_color)
127
        embed_command.add_field(name="Total", value=f"**{leges_total}**", inline=False)
128
        if self.lege_total != 0:
129
            percentage_leges = round(leges_total / self.lege_total * 100, 2)
130
            embed_command.add_field(name="Server %", value=f"**{percentage_leges}%**", inline=False)
131
        dt_string = self.bot.get_current_time()
132
        embed_command.set_footer(text=f"{dt_string}")
133
        await ctx.author.send(embed=embed_command)
134
135
        # Rare
136
        rares_list, rares_total = await self.create_spots_list(ctx.author.id, 0)
137
        rares_print = ['\n'.join([elem for elem in sublist]) for sublist in rares_list]
138
        rares_print = "\n".join(rares_print)
139
140
        rares_color = int(self.hex_to_int % (17, 93, 178), 16)
141
        embed_command = discord.Embed(title=f"Rare", description=rares_print, color=rares_color)
142
        embed_command.add_field(name="Total", value=f"**{rares_total}**", inline=False)
143
        if self.rare_total != 0:
144
            percentage_rares = round(rares_total / self.rare_total * 100, 2)
145
            embed_command.add_field(name="Server %", value=f"**{percentage_rares}%**", inline=False)
146
        dt_string = self.bot.get_current_time()
147
        embed_command.set_footer(text=f"{dt_string}")
148
        await ctx.author.send(embed=embed_command)
149
150
        # Common
151
        common_ch = self.bot.get_channel(self.bot.ch_common)
152
        common_total = 0
153
        async for message in common_ch.history(limit=None, oldest_first=True):
154
            self.common_total += 1
155
            if ctx.author == message.author:
156
                common_total += 1
157
        embed_command = discord.Embed(title=f"Common")
158
        embed_command.add_field(name="Total", value=f"**{common_total}**", inline=False)
159
        if self.common_total != 0:
160
            percentage_common = round(common_total / self.common_total * 100, 2)
161
            embed_command.add_field(name="Server %", value=f"**{percentage_common}%**", inline=False)
162
        dt_string = self.bot.get_current_time()
163
        embed_command.set_footer(text=f"{dt_string}")
164
        await ctx.author.send(embed=embed_command)
165
        self.create_log_msg(f"Spotting stats created for {ctx.author}")
166
167
168
def setup(bot: commands.Bot):
169
    bot.add_cog(SpotStatsCog(bot))
170