-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path__init__.py
More file actions
477 lines (415 loc) · 17.7 KB
/
__init__.py
File metadata and controls
477 lines (415 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
"""Contains cog classes for any stats interactions."""
import math
from typing import TYPE_CHECKING
import discord
from config import settings
from db.core.models import LeftDiscordMember
from utils import CommandChecks, TeXBotBaseCog
from utils.error_capture_decorators import capture_guild_does_not_exist_error
from .counts import get_channel_message_counts, get_server_message_counts
from .graphs import amount_of_time_formatter, plot_bar_chart
if TYPE_CHECKING:
from collections.abc import AsyncIterable, Mapping, Sequence
from typing import Final
from utils import TeXBotApplicationContext
__all__: "Sequence[str]" = ("StatsCommandsCog",)
class StatsCommandsCog(TeXBotBaseCog):
"""Cog class that defines the "/stats" command group and its command call-back methods."""
_DISCORD_SERVER_NAME: "Final[str]" = f"""{
"the "
if (
settings["_GROUP_SHORT_NAME"] is not None
and (settings["_GROUP_SHORT_NAME"])
.replace("the", "")
.replace("THE", "")
.replace("The", "")
.strip()
)
else ""
}{
(
(settings["_GROUP_SHORT_NAME"])
.replace("the", "")
.replace("THE", "")
.replace("The", "")
.strip()
)
if (
settings["_GROUP_SHORT_NAME"] is not None
and (settings["_GROUP_SHORT_NAME"])
.replace("the", "")
.replace("THE", "")
.replace("The", "")
.strip()
)
else "our community group's"
}"""
stats: discord.SlashCommandGroup = discord.SlashCommandGroup(
name="stats",
description=f"Various statistics about {_DISCORD_SERVER_NAME} Discord server",
)
@stats.command(
name="channel", description="Displays the stats for the current/a given channel."
)
@discord.option(
name="channel",
description="The channel to display the stats for.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(
TeXBotBaseCog.autocomplete_get_text_channels
),
required=False,
parameter_name="str_channel_id",
)
async def channel_stats(
self, ctx: "TeXBotApplicationContext", str_channel_id: str
) -> None:
"""
Definition & callback response of the "channel_stats" command.
The "channel_stats" command sends a graph of the stats about messages sent in the given
channel.
"""
if not ctx.channel or not isinstance(
ctx.channel, (discord.TextChannel, discord.DMChannel)
):
await self.command_send_error(
ctx,
message="Channel statistics cannot be sent in this channel.",
)
return
stats_channel: discord.TextChannel | None = None
if not str_channel_id:
if not isinstance(ctx.channel, discord.TextChannel):
await self.command_send_error(
ctx,
message=(
"User did not provide a channel ID and the interaction channel "
"is not a text channel."
),
)
return
stats_channel = ctx.channel
if not stats_channel:
try:
channel_id: int = int(str_channel_id)
except ValueError:
await self.command_send_error(
ctx,
message="The provided channel ID was not a valid integer.",
)
return
result_channel = ctx.bot.get_channel(channel_id)
if not result_channel:
await self.command_send_error(
ctx,
message="The provided channel ID was not valid or could not be found.",
)
return
if not isinstance(result_channel, discord.TextChannel):
await self.command_send_error(
ctx,
message=(
"The provided channel ID relates to a channel type "
"that is not supported."
),
)
return
stats_channel = result_channel
await ctx.defer(ephemeral=True)
message_counts: Mapping[str, int] = await get_channel_message_counts(
channel=stats_channel
)
if math.ceil(max(message_counts.values()) / 15) < 1:
await self.command_send_error(
ctx, message="There are not enough messages sent in this channel."
)
return
await ctx.respond(":point_down:Your stats graph is shown below:point_down:")
await ctx.channel.send(
f"**{ctx.user.display_name}** used `/{ctx.command}`",
file=plot_bar_chart(
message_counts,
x_label="Role Name",
y_label=(
f"""Number of Messages Sent (in the past {
amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day")
})"""
),
title=f"Most Active Roles in #{stats_channel.name}",
filename=f"{stats_channel.name}_channel_stats.png",
description=(
"Bar chart of the number of messages "
f"sent by different roles in {stats_channel.mention}."
),
extra_text=(
"Messages sent by members with multiple roles are counted once "
"for each role "
"(except for @Member vs @Guest & @Committee vs @Committee-Elect)"
),
),
)
@stats.command(
name="server",
description=f"Displays the stats for the whole of {_DISCORD_SERVER_NAME}",
)
async def server_stats(self, ctx: "TeXBotApplicationContext") -> None:
"""
Definition & callback response of the "server_stats" command.
The "server_stats" command sends a graph of the stats about messages sent in the whole
of your group's Discord guild.
"""
# NOTE: Shortcut accessors are placed at the top of the function so that the exceptions they raise are displayed before any further errors may be sent
main_guild: discord.Guild = self.bot.main_guild
guest_role: discord.Role = await self.bot.guest_role
if not ctx.channel:
await self.command_send_error(
ctx,
message=(
"Interaction channel was None while attempting to send server stats."
),
)
return
if isinstance(
ctx.channel, (discord.VoiceChannel, discord.ForumChannel, discord.CategoryChannel)
):
await self.command_send_error(
ctx,
message=(
"Server stats cannot be sent in a voice, forum, or category channel."
),
)
return
await ctx.defer(ephemeral=True)
message_counts: Mapping[str, Mapping[str, int]] = await get_server_message_counts(
guild=main_guild, guest_role=guest_role
)
TOO_FEW_ROLES_STATS: Final[bool] = (
math.ceil(max(message_counts["roles"].values()) / 15) < 1
)
TOO_FEW_CHANNELS_STATS: Final[bool] = (
math.ceil(max(message_counts["channels"].values()) / 15) < 1
)
if TOO_FEW_ROLES_STATS or TOO_FEW_CHANNELS_STATS:
await self.command_send_error(ctx, message="There are not enough messages sent.")
return
await ctx.respond(":point_down:Your stats graph is shown below:point_down:")
await ctx.channel.send(
f"**{ctx.user.display_name}** used `/{ctx.command}`",
files=[
plot_bar_chart(
message_counts["roles"],
x_label="Role Name",
y_label=(
f"""Number of Messages Sent (in the past {
amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day")
})"""
),
title=(
f"Most Active Roles in the {self.bot.group_short_name} Discord Server"
),
filename="roles_server_stats.png",
description=(
"Bar chart of the number of messages sent by different roles "
f"in the {self.bot.group_short_name} Discord server."
),
extra_text=(
"Messages sent by members with multiple roles are counted once "
"for each role "
"(except for @Member vs @Guest & @Committee vs @Committee-Elect)"
),
),
plot_bar_chart(
message_counts["channels"],
x_label="Channel Name",
y_label=(
f"""Number of Messages Sent (in the past {
amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day")
})"""
),
title=(
"Most Active Channels "
f"in the {self.bot.group_short_name} Discord Server"
),
filename="channels_server_stats.png",
description=(
"Bar chart of the number of messages sent in different text channels "
f"in the {self.bot.group_short_name} Discord server."
),
),
],
)
@stats.command(
name="self", description="Displays stats about the number of messages you have sent."
)
@CommandChecks.check_interaction_user_in_main_guild
async def user_stats(self, ctx: "TeXBotApplicationContext") -> None:
"""
Definition & callback response of the "user_stats" command.
The "user_stats" command sends a graph of the stats about messages sent by the given
member.
"""
# NOTE: Shortcut accessors are placed at the top of the function so that the exceptions they raise are displayed before any further errors may be sent
main_guild: discord.Guild = self.bot.main_guild
interaction_member: discord.Member = await self.bot.get_main_guild_member(ctx.user)
guest_role: discord.Role = await self.bot.guest_role
if guest_role not in interaction_member.roles:
await self.command_send_error(
ctx,
message=(
"You must be inducted as a guest member "
f"of the {self.bot.group_short_name} Discord server "
"to use this command."
),
)
return
if not ctx.channel:
await self.command_send_error(
ctx,
message=("Interaction channel was None while attempting to send user stats."),
)
return
if isinstance(
ctx.channel, (discord.VoiceChannel, discord.ForumChannel, discord.CategoryChannel)
):
await self.command_send_error(
ctx,
message=("User stats cannot be sent in a voice, forum, or category channel."),
)
return
await ctx.defer(ephemeral=True)
message_counts: dict[str, int] = {"Total": 0}
channel: discord.TextChannel
for channel in main_guild.text_channels:
member_has_access_to_channel: bool = channel.permissions_for(
guest_role
).is_superset(discord.Permissions(send_messages=True))
if not member_has_access_to_channel:
continue
message_counts[f"#{channel.name}"] = 0
message_history_period: AsyncIterable[discord.Message] = channel.history(
after=discord.utils.utcnow() - settings["STATISTICS_DAYS"]
)
message: discord.Message
async for message in message_history_period:
if message.author == ctx.user and not message.author.bot:
message_counts[f"#{channel.name}"] += 1
message_counts["Total"] += 1
if math.ceil(max(message_counts.values()) / 15) < 1:
await self.command_send_error(ctx, message="You have not sent enough messages.")
return
await ctx.respond(":point_down:Your stats graph is shown below:point_down:")
await ctx.channel.send(
f"**{ctx.user.display_name}** used `/{ctx.command}`",
file=plot_bar_chart(
message_counts,
x_label="Channel Name",
y_label=(
f"""Number of Messages Sent (in the past {
amount_of_time_formatter(settings["STATISTICS_DAYS"].days, "day")
})"""
),
title=(
"Your Most Active Channels "
f"in the {self.bot.group_short_name} Discord Server"
),
filename=f"{ctx.user}_stats.png",
description=(
f"Bar chart of the number of messages sent by {ctx.user} "
"in different channels in "
f"the {self.bot.group_short_name} Discord server."
),
),
)
@stats.command(
name="left-members",
description=f"Displays the stats about members that have left {_DISCORD_SERVER_NAME}",
)
async def left_member_stats(self, ctx: "TeXBotApplicationContext") -> None:
"""
Definition & callback response of the "left_member_stats" command.
The "left_member_stats" command sends a graph of the stats about the roles that members
had when they left your group's Discord guild.
"""
# NOTE: Shortcut accessors are placed at the top of the function so that the exceptions they raise are displayed before any further errors may be sent
main_guild: discord.Guild = self.bot.main_guild
if not ctx.channel:
await self.command_send_error(
ctx,
message=(
"Interaction channel was None while attempting to send left member stats."
),
)
return
if isinstance(
ctx.channel, (discord.VoiceChannel, discord.ForumChannel, discord.CategoryChannel)
):
await self.command_send_error(
ctx,
message=(
"Left member stats cannot be sent in a voice, forum, or category channel."
),
)
return
await ctx.defer(ephemeral=True)
left_member_counts: dict[str, int] = {
"Total": await LeftDiscordMember.objects.acount() # codespell:ignore acount
}
role_name: str
for role_name in settings["STATISTICS_ROLES"]:
if discord.utils.get(main_guild.roles, name=role_name):
left_member_counts[f"@{role_name}"] = 0
left_member: LeftDiscordMember
async for left_member in LeftDiscordMember.objects.all():
for left_member_role in left_member.roles:
if left_member_role not in left_member_counts:
continue
is_committee_role: bool = left_member_role == "@Committee"
if is_committee_role and "@Committee-Elect" in left_member.roles:
continue
if left_member_role == "@Guest" and "@Member" in left_member.roles:
continue
left_member_counts[left_member_role] += 1
if math.ceil(max(left_member_counts.values()) / 15) < 1:
await self.command_send_error(
ctx, message="Not enough data about members that have left the server."
)
return
await ctx.respond(":point_down:Your stats graph is shown below:point_down:")
await ctx.channel.send(
f"**{ctx.user.display_name}** used `/{ctx.command}`",
file=plot_bar_chart(
left_member_counts,
x_label="Role Name",
y_label=(
"Number of Members that have left "
f"the {self.bot.group_short_name} Discord Server"
),
title=(
"Most Common Roles that Members had when they left "
f"the {self.bot.group_short_name} Discord Server"
),
filename="left_members_stats.png",
description=(
"Bar chart of the number of members with different roles "
f"that have left the {self.bot.group_short_name} Discord server."
),
extra_text=(
"Members that left with multiple roles "
"are counted once for each role "
"(except for @Member vs @Guest & @Committee vs @Committee-Elect)"
),
),
)
@TeXBotBaseCog.listener()
@capture_guild_does_not_exist_error
async def on_member_leave(self, member: discord.Member) -> None:
"""Update the stats of the roles that members had when they left your Discord guild."""
if member.guild != self.bot.main_guild or member.bot:
return
await LeftDiscordMember.objects.acreate( # type: ignore[misc]
roles={
f"@{role.name}"
for role in member.roles
if role.name.lower().strip("@").strip() != "everyone"
}
)