-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcommittee_actions_tracking.py
More file actions
928 lines (821 loc) · 34.1 KB
/
committee_actions_tracking.py
File metadata and controls
928 lines (821 loc) · 34.1 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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
"""Contains cog classes for tracking committee-actions."""
import contextlib
import logging
import random
import textwrap
from enum import Enum
from typing import TYPE_CHECKING
import discord
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist, ValidationError
from django.db.models import Q
from db.core.models import AssignedCommitteeAction, DiscordMember
from exceptions import (
CommitteeElectRoleDoesNotExistError,
CommitteeRoleDoesNotExistError,
InvalidActionDescriptionError,
InvalidActionTargetError,
)
from utils import CommandChecks, TeXBotBaseCog
if TYPE_CHECKING:
from collections.abc import Sequence
from collections.abc import Set as AbstractSet
from logging import Logger
from typing import Final
from utils import TeXBotApplicationContext, TeXBotAutocompleteContext
__all__: "Sequence[str]" = (
"CommitteeActionsTrackingBaseCog",
"CommitteeActionsTrackingContextCommandCog",
"CommitteeActionsTrackingSlashCommandsCog",
)
logger: "Final[Logger]" = logging.getLogger("TeX-Bot")
class Status(Enum):
"""Enum class to define the possible statuses of an action."""
BLOCKED = "BLK"
CANCELLED = "CND"
COMPLETED = "CMP"
IN_PROGRESS = "INP"
NOT_STARTED = "NST"
class CommitteeActionsTrackingBaseCog(TeXBotBaseCog):
"""Base cog class that defines methods for committee actions tracking."""
async def _create_action(
self, ctx: "TeXBotApplicationContext", action_user: discord.Member, description: str
) -> AssignedCommitteeAction | None:
"""
Create the action object with the given description for the given user.
If action creation is successful, the Action object will be returned.
If unsuccessful, a string explaining the error will be returned.
"""
if len(description) >= 200:
INVALID_DESCRIPTION_ERROR_MESSAGE: Final[str] = (
f"Action description length was {len(description)} characters which is "
"greater than the maximum of 200."
)
raise InvalidActionTargetError(message=INVALID_DESCRIPTION_ERROR_MESSAGE)
if action_user.bot:
INVALID_ACTION_TARGET_MESSAGE: Final[str] = (
f"Actions cannot be assigned to bots. ({action_user})"
)
raise InvalidActionTargetError(message=INVALID_ACTION_TARGET_MESSAGE)
try:
action: AssignedCommitteeAction = await AssignedCommitteeAction.objects.acreate(
discord_member=(
await DiscordMember.objects.aget_or_create(discord_id=action_user.id)
)[0],
description=description,
)
except ValidationError as create_action_error:
error_is_already_exits: bool = (
"__all__" in create_action_error.message_dict
and any(
"already exists" in error
for error in create_action_error.message_dict["__all__"]
)
)
if not error_is_already_exits:
await self.command_send_error(ctx, message="An unrecoverable error occurred.")
logger.critical("Error upon creating Action object: %s", create_action_error)
await self.bot.close()
DUPLICATE_ACTION_MESSAGE: Final[str] = (
f"User: {action_user} already has an action with description: {description}!"
)
logger.debug(
(
"Action creation for user: %s, failed because an action "
"with description: %s, already exists."
),
action_user,
description,
)
raise InvalidActionDescriptionError(
message=DUPLICATE_ACTION_MESSAGE
) from create_action_error
return action
class CommitteeActionsTrackingSlashCommandsCog(CommitteeActionsTrackingBaseCog):
"""Cog class that defines the committee-actions tracking slash commands functionality."""
committee_actions: discord.SlashCommandGroup = discord.SlashCommandGroup(
name="committee-actions",
description="Add, list, remove and reassign tracked committee-actions.",
)
@staticmethod
async def autocomplete_get_committee_members(
ctx: "TeXBotAutocompleteContext",
) -> "AbstractSet[discord.OptionChoice] | AbstractSet[str]":
"""Autocomplete callable that generates a set of selectable committee members."""
try:
committee_role: discord.Role = await ctx.bot.committee_role
except CommitteeRoleDoesNotExistError:
return set()
committee_elect_role: discord.Role | None = None
with contextlib.suppress(CommitteeElectRoleDoesNotExistError):
committee_elect_role = await ctx.bot.committee_elect_role
return {
discord.OptionChoice(
name=f"{member.display_name} ({member.global_name})", value=str(member.id)
)
for member in (
set(committee_role.members)
| (
set(committee_elect_role.members)
if committee_elect_role is not None
else set()
)
)
if not member.bot
}
@staticmethod
async def autocomplete_get_user_action_ids(
ctx: "TeXBotAutocompleteContext",
) -> "AbstractSet[discord.OptionChoice] | AbstractSet[str]":
"""Autocomplete callable that provides a set of actions that belong to the user."""
if not ctx.interaction.user:
logger.debug("User actions autocomplete did not have an interaction user!!")
return set()
try:
interaction_user: discord.Member = await ctx.bot.get_member_from_str_id(
str(ctx.interaction.user.id)
)
except ValueError:
logger.debug("User action ID autocomplete could not acquire an interaction user!")
return set()
admin_role: discord.Role | None = discord.utils.get(
ctx.bot.main_guild.roles, name="Admin"
)
if admin_role and admin_role in interaction_user.roles:
return {
discord.OptionChoice(
name=f"{action.description} ({action.status})", value=str(action.id)
)
async for action in AssignedCommitteeAction.objects.select_related().all()
}
return {
discord.OptionChoice(name=action.description, value=str(action.id))
async for action in AssignedCommitteeAction.objects.filter(
(
Q(status=Status.IN_PROGRESS.value)
| Q(status=Status.BLOCKED.value)
| Q(status=Status.NOT_STARTED.value)
),
discord_member__discord_id=interaction_user.id,
)
}
@staticmethod
async def autocomplete_get_action_status(
ctx: "TeXBotAutocompleteContext", # noqa: ARG004
) -> "AbstractSet[discord.OptionChoice] | AbstractSet[str]":
"""Autocomplete callable that provides the set of possible Status' of actions."""
status_options: Sequence[tuple[str, str]] = AssignedCommitteeAction._meta.get_field(
"status"
).choices # type: ignore[assignment]
if not status_options:
logger.error("The autocomplete could not find any action Status'!")
return set()
return {discord.OptionChoice(name=value, value=code) for code, value in status_options}
@committee_actions.command(
name="create", description="Adds a new action with the specified description."
)
@discord.option(
name="description",
description="The description of the action to assign.",
input_type=str,
required=True,
parameter_name="action_description",
)
@discord.option(
name="user",
description="The user to assign the action to.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_committee_members),
required=False,
default=None,
parameter_name="action_member_id",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def create(
self,
ctx: "TeXBotApplicationContext",
action_description: str,
action_member_id: str | None,
) -> None:
"""
Definition and callback response of the "create" command.
The "create" command creates an action with the specified description.
If no user is specified, the user issuing the command will be actioned.
In normal use the autocomplete should be used, but a discord ID can be
used directly if the user wishes to action a user not included in the autocomplete.
"""
member_id: str = action_member_id or str(ctx.user.id)
try:
action_user: discord.Member = await self.bot.get_member_from_str_id(member_id)
except ValueError:
await ctx.respond(
content=f":warning: The user ID provided: {member_id}, was not valid.",
ephemeral=True,
)
logger.debug(
"User: %s, tried to create an action with an invalid user ID: %s",
ctx.user,
member_id,
)
return
try:
await self._create_action(ctx, action_user, action_description)
await ctx.respond(
content=f"Action `{action_description}` created for: {action_user.mention}"
)
except (
InvalidActionDescriptionError,
InvalidActionTargetError,
) as creation_failed_error:
await ctx.respond(content=creation_failed_error.message)
@committee_actions.command(
name="update-status", description="Update the status of the provided action."
)
@discord.option(
name="action",
description="The action to mark as completed.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_user_action_ids),
required=True,
parameter_name="action_id",
)
@discord.option(
name="status",
description="The desired status of the action.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_action_status),
required=True,
parameter_name="status",
)
async def update_status( # NOTE: Committee role check is not present because non-committee can have actions, and need to be able to list their own actions.
self, ctx: "TeXBotApplicationContext", action_id: str, status: str
) -> None:
"""
Definition and callback of the "update-status" command.
Takes in an action object and a Status string,
sets the status of the provided action to be the provided status.
"""
try:
action_id_int: int = int(action_id)
except ValueError:
await self.command_send_error(
ctx,
message="Action ID entered was not valid! Please use the autocomplete.",
logging_message=f"{ctx.user} entered action ID: {action_id} which was invalid",
)
return
try:
action: AssignedCommitteeAction = (
await AssignedCommitteeAction.objects.select_related().aget(id=action_id_int)
)
except (MultipleObjectsReturned, ObjectDoesNotExist):
await self.command_send_error(
ctx, message="Action provided was either not unique or could not be found."
)
return
try:
new_status: AssignedCommitteeAction.Status = AssignedCommitteeAction.Status(status)
except (ValueError, KeyError) as invalid_status:
await self.command_send_error(
ctx, message=f"Status ({status}) provided was not valid or could not be found."
)
logger.debug(invalid_status)
return
if not new_status:
await self.command_send_error(
ctx,
message=f"Status ({status}) provided was not valid or could not be found.",
)
logger.debug("An invalid status was provided but did not raise an exception.")
return
await action.aupdate(status=new_status)
await ctx.respond(
content=f"Status for action`{action.description}` updated to `{action.status}`",
ephemeral=True,
)
@committee_actions.command(
name="update-description", description="Update the description of the provided action."
)
@discord.option(
name="action",
description="The action to mark as completed.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_user_action_ids),
required=True,
parameter_name="action_id",
)
@discord.option(
name="description",
description="The description to be used for the action.",
input_type=str,
required=True,
parameter_name="action_description",
)
async def update_description(
self, ctx: "TeXBotApplicationContext", action_id: str, new_description: str
) -> None:
"""
Definition and callback response of the "update-description" command.
Takes in an action id and description, retrieves the action from the ID
and updates the action to with the new description.
"""
if len(new_description) >= 200:
await ctx.respond(
content=":warning: The provided description was too long! No action taken."
)
return
try:
action_id_int: int = int(action_id)
except ValueError:
await self.command_send_error(
ctx,
message="Action ID entered was not valid! Please use the autocomplete.",
logging_message=f"{ctx.user} entered action ID: {action_id} which was invalid",
)
return
try:
action: AssignedCommitteeAction = (
await AssignedCommitteeAction.objects.select_related().aget(id=action_id_int)
)
except (MultipleObjectsReturned, ObjectDoesNotExist):
await self.command_send_error(
ctx, message="Action provided was either not unique or could not be found."
)
return
old_description: str = action.description
await action.aupdate(description=new_description)
await ctx.respond(
content=f"Action `{old_description}` updated to `{action.description}`!"
)
@committee_actions.command(
name="action-random-user",
description="Creates an action object with the specified description and random user.",
)
@discord.option(
name="description",
description="The description to be used for the action.",
input_type=str,
required=True,
parameter_name="action_description",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def action_random_user(
self, ctx: "TeXBotApplicationContext", action_description: str
) -> None:
"""
Definition and callback response of the "action-random-user" command.
Creates an action object with the specified description
but randomises the committee member.
"""
committee_role: discord.Role = await self.bot.committee_role
committee_members: list[discord.Member] = committee_role.members
if not committee_members:
await ctx.respond(
content=(
"No committee members were found to randomly select from! Command aborted."
)
)
return
action_user: discord.Member = random.choice(committee_members) # noqa: S311
try:
await self._create_action(
ctx, action_user=action_user, description=action_description
)
await ctx.respond(
content=f"Action `{action_description}` created for: {action_user.mention}"
)
except (
InvalidActionTargetError,
InvalidActionDescriptionError,
) as creation_failed_error:
await ctx.respond(content=creation_failed_error.message)
return
@committee_actions.command(
name="action-all-committee",
description="Creates an action with the description for every committee member.",
)
@discord.option(
name="description",
description="The description to be used for the actions.",
input_type=str,
required=True,
parameter_name="action_description",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def action_all_committee(
self, ctx: "TeXBotApplicationContext", action_description: str
) -> None:
"""
Definition and callback response of the "action-all-committee" command.
Creates an action object with the specified description for all committee members.
"""
committee_role: discord.Role = await self.bot.committee_role
committee_members: list[discord.Member] = committee_role.members
if not committee_members:
await ctx.respond(content="No committee members were found! Command aborted.")
return
success_members: list[discord.Member] = []
failed_members: str = ""
committee_member: discord.Member
for committee_member in committee_members:
try:
_: AssignedCommitteeAction | None = await self._create_action(
ctx, action_user=committee_member, description=action_description
)
success_members.append(committee_member)
except (
InvalidActionDescriptionError,
InvalidActionTargetError,
) as creation_failed_error:
failed_members += creation_failed_error.message + "\n"
response_message: str = ""
if success_members:
response_message += (
f"Successfully created action `{action_description}` for users: \n"
)
response_message += "\n".join(
f"{success_member.mention}" for success_member in success_members
)
if len(failed_members) > 1:
response_message += (
"\n\nThe following errors were also raised: \n" + failed_members
)
else:
response_message += "Could not create any actions! See errors below: \n"
response_message += failed_members
await ctx.respond(content=response_message)
@committee_actions.command(
name="list", description="Lists all actions for a specified user."
)
@discord.option(
name="user",
description="The user to list actions for.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_committee_members),
required=False,
default=None,
parameter_name="action_member_id",
)
@discord.option(
name="ping",
description="Triggers whether the message pings users or not.",
input_type=bool,
default=False,
required=False,
)
@discord.option(
name="status",
description="The desired status of the action.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_action_status),
required=False,
default=None,
parameter_name="status",
)
async def list_user_actions( # NOTE: Committee role check is not present because non-committee can have actions, and need to be able to list their own actions.
self,
ctx: "TeXBotApplicationContext",
action_member_id: str | None,
ping: bool, # noqa: FBT001
status: str | None,
) -> None:
"""
Definition and callback of the "/list" command.
Takes in a user and lists out their current actions.
If no user is specified, the user issuing the command will be used.
If a user has the committee role, they can list actions for other users.
If a user does not have the committee role, they can only list their own actions.
"""
if action_member_id is not None:
action_member_id = action_member_id.strip()
action_member: discord.Member | discord.User = (
await self.bot.get_member_from_str_id(action_member_id)
if action_member_id
else ctx.user
)
if action_member != ctx.user and not await self.bot.check_user_has_committee_role(
ctx.user
):
await ctx.respond(
content="Committee role is required to list actions for other users.",
ephemeral=True,
)
logger.debug(
(
"User: %s, tried to list actions for user: %s, "
"but did not have the committee role."
),
ctx.user,
action_member,
)
return
user_actions: list[AssignedCommitteeAction]
if not status:
user_actions = [
action
async for action in AssignedCommitteeAction.objects.filter(
(
Q(status=Status.IN_PROGRESS.value)
| Q(status=Status.BLOCKED.value)
| Q(status=Status.NOT_STARTED.value)
),
discord_member__discord_id=action_member.id,
)
]
else:
user_actions = [
action
async for action in AssignedCommitteeAction.objects.filter(
status=status,
discord_member__discord_id=action_member.id,
)
]
if not user_actions:
await ctx.respond(
content=(
(
f"User: {action_member.mention if ping else action_member} has no "
"in progress actions."
)
if not status
else "actions matching given filter."
)
)
return
actions_message: str = (
f"Found {len(user_actions)} actions for user "
f"{action_member.mention if ping else action_member}:"
f"\n{
'\n'.join(
str(action.description)
+ f' ({AssignedCommitteeAction.Status(action.status).label})'
for action in user_actions
)
}"
)
if len(actions_message) >= 2000:
chunk: str
for chunk in textwrap.wrap(
text=actions_message,
width=1950,
break_long_words=False,
fix_sentence_endings=True,
):
await ctx.respond(content=chunk)
return
await ctx.respond(content=actions_message)
@committee_actions.command(
name="reassign", description="Reassign the specified action to another user."
)
@discord.option(
name="action",
description="The action to reassign.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_user_action_ids),
required=True,
parameter_name="action_id",
)
@discord.option(
name="user",
description="The user to reassign the action to.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_committee_members),
required=False,
parameter_name="member_id",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def reassign_action(
self, ctx: "TeXBotApplicationContext", action_id: str, member_id: str | None
) -> None:
"""Reassign the specified action to the specified user."""
try:
action_id_int: int = int(action_id)
except ValueError:
await self.command_send_error(
ctx,
message="Action ID entered was not valid! Please use the autocomplete.",
logging_message=f"{ctx.user} entered action ID: {action_id} which was invalid",
)
return
if not member_id:
logger.debug(
"Member ID was not provided, selecting a random committee member "
"to assign the action to."
)
try:
committee_members: list[discord.Member] = (
await self.bot.committee_role
).members
except CommitteeRoleDoesNotExistError:
await self.command_send_error(
ctx,
message="Committee role does not exist! No action has been taken.",
)
return
if not committee_members:
logger.debug(
"Committee role was found but no members held the role, "
"while attempting to randomly re-assign action."
)
await ctx.respond(
content=(
"No committee members were found to randomly select from! "
"No action has been taken."
)
)
return
member_id = str(random.choice(committee_members).id) # noqa: S311
new_user_to_action: discord.Member = await self.bot.get_member_from_str_id(
member_id,
)
try:
action_to_reassign: AssignedCommitteeAction = (
await AssignedCommitteeAction.objects.select_related().aget(id=action_id_int)
)
except (MultipleObjectsReturned, ObjectDoesNotExist):
await self.command_send_error(
ctx, message="Action provided was either not unique or could not be found."
)
return
if str(action_to_reassign.discord_member) == str(new_user_to_action.id):
await ctx.respond(
content=(
f"HEY! Action `{action_to_reassign.description}` is already assigned "
f"to user: {new_user_to_action.mention}\nNo action has been taken."
)
)
return
try:
new_action: AssignedCommitteeAction | None = await self._create_action(
ctx,
action_user=new_user_to_action,
description=action_to_reassign.description,
)
if new_action:
await action_to_reassign.adelete()
await ctx.respond(
content=(
f"Action `{new_action.description}` successfully "
f"reassigned to {new_user_to_action.mention}!"
)
)
except (
InvalidActionDescriptionError,
InvalidActionTargetError,
) as invalid_description_error:
await ctx.respond(content=invalid_description_error.message)
return
@committee_actions.command(name="list-all", description="List all current actions.")
@discord.option(
name="ping",
description="Triggers whether the message pings users or not.",
input_type=bool,
default=False,
required=False,
)
@discord.option(
name="status-filter",
description="The filter to apply to the status of actions.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_action_status),
required=False,
default=None,
parameter_name="status",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def list_all_actions(
self,
ctx: "TeXBotApplicationContext",
ping: bool, # noqa: FBT001
status: str | None,
) -> None:
"""List all actions.""" # NOTE: this doesn't actually list *all* actions as it is possible for non-committee to be actioned.
committee_role: discord.Role = await self.bot.committee_role
actions: list[AssignedCommitteeAction] = [
action async for action in AssignedCommitteeAction.objects.select_related().all()
]
desired_status: list[str] = (
[status]
if status
else [Status.NOT_STARTED.value, Status.IN_PROGRESS.value, Status.BLOCKED.value]
)
committee_members: list[discord.Member] = committee_role.members
committee_actions: dict[discord.Member, list[AssignedCommitteeAction]] = {
committee: [
action
for action in actions
if str(action.discord_member) == str(committee.id)
and action.status in desired_status
]
for committee in committee_members
}
filtered_committee_actions = {
committee: actions for committee, actions in committee_actions.items() if actions
}
if not filtered_committee_actions:
await ctx.respond(content="No one has any actions that match the request!")
logger.debug("No actions found with the status filter: %s", status)
return
all_actions_message: str = "\n".join(
[
f"\n{committee.mention if ping else committee}, Actions:"
f"\n{', \n'.join(str(action.description) + f' ({AssignedCommitteeAction.Status(action.status).label})' for action in actions)}" # noqa: E501
for committee, actions in filtered_committee_actions.items()
],
)
if len(all_actions_message) >= 2000:
chunk: str
for chunk in all_actions_message.split("\n\n"):
sub_chunk: str
for sub_chunk in textwrap.wrap(
text=chunk,
width=1950,
break_long_words=False,
fix_sentence_endings=True,
):
await ctx.respond(content=sub_chunk)
return
await ctx.respond(content=all_actions_message)
@committee_actions.command(
name="delete", description="Deletes the specified action from the database completely."
)
@discord.option(
name="action",
description="The action to delete.",
input_type=str,
autocomplete=discord.utils.basic_autocomplete(autocomplete_get_user_action_ids),
required=True,
parameter_name="action_id",
)
async def delete_action(self, ctx: "TeXBotApplicationContext", action_id: str) -> None:
"""
Definition & callback response of the "delete" command.
Takes in an action as an argument and deletes it from the database.
This command should be used for administrative purposes only, in most circumstances
the update-status command should be used.
"""
try:
action_id_int: int = int(action_id)
except ValueError:
await self.command_send_error(
ctx,
message="Action ID entered was not valid! Please use the autocomplete.",
logging_message=f"{ctx.user} entered action ID: {action_id} which was invalid",
)
return
try:
action: AssignedCommitteeAction = (
await AssignedCommitteeAction.objects.select_related().aget(id=action_id_int)
)
except (ObjectDoesNotExist, MultipleObjectsReturned):
await self.command_send_error(
ctx, message="Action provided was either not unique or could not be found."
)
return
action_description: str = action.description
await action.adelete()
await ctx.respond(content=f"Action `{action_description}` successfully deleted.")
class CommitteeActionsTrackingContextCommandCog(CommitteeActionsTrackingBaseCog):
"""Cog class to define the actions tracking message context commands."""
@discord.message_command(
name="Action Message Author",
description="Creates a new action for the message author using the message content.",
)
@CommandChecks.check_interaction_user_has_committee_role
@CommandChecks.check_interaction_user_in_main_guild
async def action_message_author(
self, ctx: "TeXBotApplicationContext", message: discord.Message
) -> None:
"""
Definition and callback response of the "action-message-author" message command.
Creates a new action assigned to the message author
using the message content as the description of the action.
"""
if message.author.bot:
await ctx.respond(content="Actions cannot be assigned to bots you melon!")
logger.debug("User: %s, attempted to action a bot. silly billy.", ctx.user)
return
actioned_message_text: str = message.content
actioned_message_user: discord.Member | discord.User = message.author
if isinstance(actioned_message_user, discord.User):
await ctx.respond(content="Message author is not in the server!")
return
try:
await self._create_action(
ctx, action_user=actioned_message_user, description=actioned_message_text
)
await ctx.respond(
content=(
f"Action `{actioned_message_text}` created "
f"for: {actioned_message_user.mention}"
)
)
except (
InvalidActionTargetError,
InvalidActionDescriptionError,
) as creation_failure_error:
await ctx.respond(content=creation_failure_error.message)