Compare commits

...
11 Commits
Author SHA1 Message Date
imcompiling 95cfcca600 Issue #79, add a 2 hour timeout to event submission.
build_latest / build (push) Successful in 1m27s
build_release / build (push) Successful in 22s
2024-12-22 17:11:54 -05:00
imcompiling 0419c9dfd6 Add auto complete for view clan points command.
build_latest / build (push) Successful in 1m30s
2024-12-22 16:51:10 -05:00
imcompiling 6ec2862aed Merge branch '76-clan-points'
build_latest / build (push) Successful in 17s
build_release / build (push) Successful in 17s
2024-12-22 15:49:24 -05:00
imcompiling c8f5c5bffb Add view clan points command. Break out function for creating the string so that code isn't duplicated.
build_develop / build (push) Successful in 2m11s
2024-12-22 15:48:10 -05:00
imcompiling a56b47a5fa Revamped utils to handle clan and event points in one. Updated record as needed. 2024-12-22 15:34:14 -05:00
imcompiling 906b63d57f Update view event points for new table name. 2024-12-22 15:13:35 -05:00
imcompiling 1bae320446 Fix in typos. 2024-12-22 15:10:47 -05:00
imcompiling a081718f8d Combine event and clan points into one table. 2024-12-22 14:41:50 -05:00
imcompiling 0dd1a90edd Merge branch 'main' into 76-clan-points 2024-12-22 14:04:03 -05:00
imcompiling 1305e15edf Change cutoff months for rollover.
build_latest / build (push) Successful in 1m49s
build_develop / build (push) Successful in 24s
build_release / build (push) Successful in 20s
2024-12-14 18:36:47 -05:00
imcompiling 86e9e3e32b Write a new test case for quarter name. 2024-12-14 17:57:01 -05:00
6 changed files with 166 additions and 84 deletions
+13 -9
View File
@@ -5,7 +5,7 @@ from discord import TextInputStyle
from nextcord.ext import commands
from DakinySettings import settings
from utils import GUILDS, MAX_DISCORD_MESSAGE_LENGTH, record_event_points
from utils import GUILDS, MAX_DISCORD_MESSAGE_LENGTH, PointType, record_points
class RecordCog(commands.Cog, name="Record Commands"):
@@ -117,16 +117,18 @@ class RecordCog(commands.Cog, name="Record Commands"):
await interaction.response.send_message("Please only provide 1 recipient.", ephemeral=True)
return
elif recipient is not None: # noqa: RET505
record_event_points(
record_points(
[str(recipient.id)],
settings.point_settings.participate_points,
settings.point_settings.clan_points,
PointType.CLAN,
is_member=True,
)
recipient_str = f"<@{recipient.id}>"
elif non_discord_recipient is not None:
record_event_points(
record_points(
[non_discord_recipient],
settings.point_settings.participate_points,
settings.point_settings.clan_points,
PointType.CLAN,
is_member=False,
)
recipient_str = f'"{non_discord_recipient}"'
@@ -152,7 +154,7 @@ class EventView(nextcord.ui.View):
"""
def __init__(self, name: str, host_id: int):
super().__init__()
super().__init__(timeout=60 * 60 * 2) # timeout 2 hours
self.name: str = name
self.host_id: int = host_id
@@ -337,18 +339,20 @@ def process_event(discord_users: list[nextcord.Member], non_discord_users: str,
"""
if discord_users:
discord_users_list: list[str] = [str(user.id) for user in discord_users if user.id is not host_id]
record_event_points(
record_points(
discord_users_list,
settings.point_settings.participate_points,
PointType.EVENT,
is_member=True,
)
if non_discord_users:
non_discord_users_list: list[str] = non_discord_users.split("\n")
record_event_points(
record_points(
non_discord_users_list,
settings.point_settings.participate_points,
PointType.EVENT,
is_member=False,
)
record_event_points([host_id], settings.point_settings.host_points, is_member=True)
record_points([host_id], settings.point_settings.host_points, PointType.EVENT, is_member=True)
+13 -1
View File
@@ -5,7 +5,7 @@ from nextcord.ext import application_checks, commands
from classes.election import Election
from DakinySettings import settings
from utils import GUILDS, get_active_election_cycle
from utils import GUILDS, get_active_election_cycle, get_quarter_name
ME = 206602713511886849
@@ -141,3 +141,15 @@ class TestCog(commands.Cog, name="Test commands."):
)
await cycle.term_start_action()
await interaction.send("Test command sent.", ephemeral=True)
@test.subcommand()
@is_me()
async def get_quarter_name(self, interaction: nextcord.Interaction) -> None:
"""
Tests getting the quarter name.
Args:
interaction (nextcord.Interaction): Interaction with the message.
"""
name = get_quarter_name()
await interaction.send(name)
+92 -28
View File
@@ -7,12 +7,12 @@ from sqlalchemy import select
from sqlalchemy.orm import Session
from database_setup.sql_data_classes import (
EventPoints,
Points,
Presences,
Votes,
engine,
)
from utils import MAX_DISCORD_MESSAGE_LENGTH, VoteType
from utils import GUILDS, MAX_DISCORD_MESSAGE_LENGTH, PointType, VoteType
class ViewCog(commands.Cog, name="View Commands"):
@@ -21,7 +21,7 @@ class ViewCog(commands.Cog, name="View Commands"):
def __init__(self) -> None:
"""Default constructor for ViewCog class. Does nothing."""
@nextcord.slash_command()
@nextcord.slash_command(guild_ids=GUILDS)
async def view(self, interaction: nextcord.Interaction) -> None:
"""Parent slash command for set. Never called."""
@@ -49,12 +49,12 @@ class ViewCog(commands.Cog, name="View Commands"):
with Session(engine) as session:
if quarter_name:
ppdf = pd.read_sql_query(
sql=session.query(EventPoints).where(EventPoints.QuarterName.startswith(quarter_name)).statement,
sql=session.query(Points).where(Points.QuarterName.startswith(quarter_name)).statement,
con=engine,
)
else:
ppdf = pd.read_sql_query(
sql=session.query(EventPoints).statement,
sql=session.query(Points).statement,
con=engine,
)
@@ -63,30 +63,53 @@ class ViewCog(commands.Cog, name="View Commands"):
return
quarters = ppdf.groupby("QuarterName")
content = ""
for quarter in quarters.groups:
content += f"**{quarter}**\n"
unsorted_all = quarters.get_group(quarter).groupby("DiscordMember")
members = unsorted_all.get_group(name=True)
content = create_points_string(interaction, quarters, PointType.EVENT)
# there can be no non-discord members sometimes.
try:
sorted_non_members = unsorted_all.get_group(name=False).sort_values(by="UserId")
except KeyError:
sorted_non_members = None
sorted_members = members.sort_values(
by="UserId",
key=lambda user_ids: (
[interaction.guild.get_member(int(user_id)).display_name.lower() for user_id in user_ids]
),
if len(content) > MAX_DISCORD_MESSAGE_LENGTH:
await interaction.followup.send("Message length is too long, please select search to limit results.")
return
await interaction.followup.send(content=content, ephemeral=True)
@view.subcommand(description="Show event points.")
async def clan_points(
self,
interaction: nextcord.Interaction,
quarter_name: str = nextcord.SlashOption(
description="The quarter to view",
required=False,
),
) -> None:
"""
View the clan points.
Builds a message with the clan points for the quarter that matches with quarter_name.
Args:
interaction (nextcord.Interaction): Interaction with the message.
quarter_name (str, optional): Same of quarter to autofill with. Is SlashOption.
"""
# just in case
await interaction.response.defer(ephemeral=True)
with Session(engine) as session:
if quarter_name:
ppdf = pd.read_sql_query(
sql=session.query(Points).where(Points.QuarterName.startswith(quarter_name)).statement,
con=engine,
)
sorted_all = pd.concat([sorted_members, sorted_non_members], ignore_index=True, sort=False)
for row in sorted_all.itertuples():
userid = row.UserId
points = row.Points
discord_member = row.DiscordMember
content += f"<@{userid}>: {points}\n" if discord_member else f"{userid}: {points}\n"
content += "\n"
else:
ppdf = pd.read_sql_query(
sql=session.query(Points).statement,
con=engine,
)
if ppdf.empty:
await interaction.followup.send(f'Quarter "{quarter_name}" is invalid.', ephemeral=True)
return
quarters = ppdf.groupby("QuarterName")
content = create_points_string(interaction, quarters, PointType.CLAN)
if len(content) > MAX_DISCORD_MESSAGE_LENGTH:
await interaction.followup.send("Message length is too long, please select search to limit results.")
@@ -192,6 +215,7 @@ class ViewCog(commands.Cog, name="View Commands"):
await interaction.response.send_autocomplete(autofilled_elections[:25])
@event_points.on_autocomplete("quarter_name")
@clan_points.on_autocomplete("quarter_name")
async def event_points_autocomplete(self, interaction: nextcord.Interaction, quarter_name: str) -> None:
"""
Collects all elections that start with the election string.
@@ -201,7 +225,7 @@ class ViewCog(commands.Cog, name="View Commands"):
quarter_name (str): String to run autocomplete on.
"""
with Session(engine) as session:
stmt = select(EventPoints.QuarterName).distinct()
stmt = select(Points.QuarterName).distinct()
quarters = session.scalars(stmt)
# if empty compare string
@@ -213,3 +237,43 @@ class ViewCog(commands.Cog, name="View Commands"):
quarter for quarter in quarters if quarter.lower().startswith(quarter_name.lower())
]
await interaction.response.send_autocomplete(autofilled_quarters[:25])
def create_points_string(interaction: nextcord.Interaction, quarters: any, point_type: PointType) -> str:
"""
Creates the string to show how many clan/event points users have.
Args:
interaction (nextcord.Interaction): Discord interaction of the command.
quarters (any): Pandas objects grouped by quarters.
point_type (PointType): The type of points to create the message for.
Returns:
str: The string with the message content.
"""
content: str = ""
for quarter in quarters.groups:
content += f"**{quarter}**\n"
unsorted_all = quarters.get_group(quarter).groupby("DiscordMember")
members = unsorted_all.get_group(name=True)
# there can be no non-discord members sometimes.
try:
sorted_non_members = unsorted_all.get_group(name=False).sort_values(by="UserId")
except KeyError:
sorted_non_members = None
sorted_members = members.sort_values(
by="UserId",
key=lambda user_ids: (
[interaction.guild.get_member(int(user_id)).display_name.lower() for user_id in user_ids]
),
)
sorted_all = pd.concat([sorted_members, sorted_non_members], ignore_index=True, sort=False)
for row in sorted_all.itertuples():
userid = row.UserId
points = row.EventPoints if point_type == PointType.EVENT else row.ClanPoints
discord_member = row.DiscordMember
if points > 0:
content += f"<@{userid}>: {points}\n" if discord_member else f"{userid}: {points}\n"
content += "\n"
return content
+6 -19
View File
@@ -41,11 +41,12 @@ CREATE TABLE Presences (
Presence varchar(100) not null
);
CREATE TABLE EventPoints (
CREATE TABLE Points (
QuarterName varchar(30) not null,
UserId varchar(32) not null,
DiscordMember boolean not null,
Points int unsigned DEFAULT 0,
EventPoints int unsigned DEFAULT 0,
ClanPoints int unsigned DEFAULT 0,
PRIMARY KEY (QuarterName, UserId)
);
@@ -54,24 +55,10 @@ CREATE TABLE Messages (
Id bigint unsigned not null
);
CREATE TABLE EventPointsLimit (
CREATE TABLE PointsLimit (
UserId varchar(32) not null,
Points int unsigned DEFAULT 0,
Week varchar(7) not null,
PRIMARY KEY (UserId, Week)
);
CREATE TABLE ClanPoints (
QuarterName varchar(30) not null,
UserId varchar(32) not null,
DiscordMember boolean not null,
Points int unsigned DEFAULT 0,
PRIMARY KEY (QuarterName, UserId)
);
CREATE TABLE ClanPointsLimit (
UserId varchar(32) not null,
Points int unsigned DEFAULT 0,
EventPoints int unsigned DEFAULT 0,
ClanPoints int unsigned DEFAULT 0,
Week varchar(7) not null,
PRIMARY KEY (UserId, Week)
);
+2 -4
View File
@@ -10,12 +10,10 @@ Base = automap_base()
Base.prepare(autoload_with=engine)
# define the classes
ClanPoints = Base.classes.ClanPoints
ClanPointsLimit = Base.classes.ClanPointsLimit
Points = Base.classes.Points
PointsLimit = Base.classes.PointsLimit
CouncilMembers = Base.classes.CouncilMembers
ElectionInformation = Base.classes.ElectionInformation
EventPoints = Base.classes.EventPoints
EventPointsLimit = Base.classes.EventPointsLimit
Messages = Base.classes.Messages
Presences = Base.classes.Presences
UserBirthday = Base.classes.UserBirthday
+40 -23
View File
@@ -15,9 +15,9 @@ from sqlalchemy.orm import Session
from DakinySettings import settings
from database_setup.sql_data_classes import (
CouncilMembers,
EventPoints,
EventPointsLimit,
Messages,
Points,
PointsLimit,
Votes,
engine,
)
@@ -30,6 +30,7 @@ MAX_DISCORD_MESSAGE_LENGTH = 2000
GUILDS = [1000247361639030804, 239758371358638080]
VoteType = StrEnum("VoteType", ["COUNCIL", "DISCORDMANAGER", "CLANLEADER"])
PointType = StrEnum("PointType", ["CLAN", "EVENT"])
def get_datetime(day: str) -> datetime:
@@ -48,10 +49,10 @@ def get_datetime(day: str) -> datetime:
day = int(day.split("/")[1])
# ensure that year rolls over if current month is December and the next month is less than 12.
if today.month == calendar.DECEMBER and month < calendar.DECEMBER:
if today.month == calendar.DECEMBER and month < calendar.OCTOBER:
year += 1
if today.month == calendar.JANUARY and month > calendar.JANUARY:
if today.month == calendar.JANUARY and month > calendar.MARCH:
year -= 1
return datetime(year, month, day, tzinfo=UTC)
@@ -290,41 +291,46 @@ def decorate_dm_nomination(user_id: int, speech: str) -> str:
return msg
def record_event_points(users: Sequence[str], add_points: int, *, is_member: bool) -> None:
def record_points(users: Sequence[str], add_points: int, point_type: PointType, *, is_member: bool) -> None:
"""
Adds event points to all users listed.
Adds points to all users listed.
Checks if they don't exist in order to make a new entry, otherwise
adds points to the existing value. Can be used for hosting or participating.
adds points to the existing value. Can be used for hosting or participating in events or for the clan
points.
Args:
users (Sequence[int]): users that participated and need points.
add_points (int): number of points to add
point_type (PointType): which point type to add to
is_member (bool): whether the users are a discord member or not
"""
quarter_name = get_quarter_name()
with Session(engine) as session:
for user in users:
stmt = select(EventPoints).where(EventPoints.UserId == user).where(EventPoints.QuarterName == quarter_name)
stmt = select(Points).where(Points.UserId == user).where(Points.QuarterName == quarter_name)
points = session.scalar(stmt)
if points is None:
add_points = get_allowed_points(session, settings.point_settings.events_weekly_limit, user, add_points)
new_points = EventPoints(
points_obj = session.scalar(stmt)
add_points = get_allowed_points(session, point_type, user, add_points)
add_clan_points = add_points if point_type == PointType.CLAN else 0
add_event_points = add_points if point_type == PointType.EVENT else 0
if points_obj is None:
new_points = Points(
QuarterName=quarter_name,
UserId=user,
DiscordMember=is_member,
Points=add_points,
EventPoints=add_event_points,
ClanPoints=add_clan_points,
)
session.add(new_points)
else:
add_points = get_allowed_points(session, settings.point_settings.events_weekly_limit, user, add_points)
points.Points += add_points
points_obj.EventPoints += add_event_points
points_obj.ClanPoints += add_clan_points
session.commit()
def get_allowed_points(session: Session, points_limit: int, user: str, points: int) -> int:
def get_allowed_points(session: Session, point_type: PointType, user: str, points: int) -> int:
"""
Gets the maximum number of points a user can be given.
@@ -334,7 +340,7 @@ def get_allowed_points(session: Session, points_limit: int, user: str, points: i
Args:
session (Session): Open connection to database.
points_limit (int): Maximum number of points a user can be given in a week.
point_type (PointType): Which type of points to check the limit for.
user (str): user to be given points. Used to check a user's limit.
points (int): maximum number of points to give to user.
@@ -344,18 +350,29 @@ def get_allowed_points(session: Session, points_limit: int, user: str, points: i
# check for limit
today = datetime.now(tz=UTC).date()
this_week = f"{today.isocalendar().year}-{today.isocalendar().week}"
stmt = select(EventPointsLimit).where(EventPointsLimit.UserId == user).where(EventPointsLimit.Week == this_week)
points_limit = (
settings.point_settings.events_weekly_limit
if point_type == PointType.EVENT
else settings.point_settings.clan_points_weekly_limit
)
stmt = select(PointsLimit).where(PointsLimit.UserId == user).where(PointsLimit.Week == this_week)
# if under limit, can add up to however many points would make the current limit equal to the
# allowed limit.
limit = session.scalar(stmt)
if limit is None:
new_limit = EventPointsLimit(UserId=user, Points=points, Week=this_week)
limit_obj = session.scalar(stmt)
if limit_obj is None:
clan_points = points if point_type == PointType.CLAN else 0
event_points = points if point_type == PointType.EVENT else 0
new_limit = PointsLimit(UserId=user, Week=this_week, EventPoints=event_points, ClanPoints=clan_points)
add_points = points
session.add(new_limit)
else:
add_points = points if limit.Points + points <= points_limit else (max(0, points_limit - limit.Points))
limit.Points += add_points
curr_points = limit_obj.EventPoints if point_type == PointType.EVENT else limit_obj.ClanPoints
add_points = points if curr_points + points <= points_limit else (max(0, points_limit - curr_points))
if point_type == PointType.EVENT:
limit_obj.EventPoints += add_points
else:
limit_obj.ClanPoints += add_points
session.commit()