Compare commits

..
30 Commits
Author SHA1 Message Date
imcompiling a15a35fcda Feat: Update uv.lock.
build_develop / build (push) Successful in 43s
2025-07-16 21:08:13 -04:00
imcompiling 44baf01a51 Feat: Update utils to use new models.
build_develop / build (push) Successful in 35s
Address many pylance smells. Ignoring some I don't know how to handle,
added some TODOs for handling others later.
2025-07-16 12:02:56 -04:00
imcompiling abc2950b21 Fix: Add default of None to speech ids. 2025-07-16 11:25:42 -04:00
imcompiling 1cc46ce2fd Feat: Rename DakinySettings -> dakiny_settings.
build_develop / build (push) Successful in 37s
Also handle the list error from pylance.
2025-07-16 10:55:15 -04:00
imcompiling bb2d6b62fe Feat: Remove pylance warnings in app.py.
Also removed old database setup.
2025-07-16 10:54:29 -04:00
imcompiling 77ce54f383 Remove: Old database files.
build_develop / build (push) Successful in 39s
2025-07-16 10:37:51 -04:00
imcompiling f81ebca4de Fix: errors on models from generating database. 2025-07-16 10:35:00 -04:00
imcompiling 2e66b1c37c Feat: Add database engine. 2025-07-16 10:26:26 -04:00
imcompiling ae1f98abe3 Add: ondelete to spelling settings.
build_develop / build (push) Successful in 19s
2025-07-16 09:10:05 -04:00
imcompiling 490c30e88c Add: PointsLimit model.
build_develop / build (push) Successful in 41s
2025-07-16 09:04:42 -04:00
imcompiling 35670358c4 Fix: Add default to points. 2025-07-16 09:00:22 -04:00
imcompiling 7a59f3b453 Add: Messages model. 2025-07-16 08:56:27 -04:00
imcompiling e01ab64411 Add: Points model. 2025-07-16 08:51:51 -04:00
imcompiling df482d80f0 Fix: Add boolean column types. 2025-07-16 08:51:39 -04:00
imcompiling 0d06d98060 Add: Presence model.
build_develop / build (push) Successful in 45s
2025-07-15 15:58:57 -04:00
imcompiling c267762efa Add: UserBirthday model.
build_develop / build (push) Successful in 38s
2025-07-15 15:45:26 -04:00
imcompiling e837cec46b Add: Vote model.
build_develop / build (push) Successful in 39s
2025-07-15 15:40:32 -04:00
imcompiling 0a856755c8 Add: CouncilMembers model.
build_develop / build (push) Successful in 44s
2025-07-15 15:05:15 -04:00
imcompiling eb8cfee7fd Feat: Add ElectionInformation table.
build_develop / build (push) Successful in 37s
2025-07-15 09:48:17 -04:00
imcompiling 6b5dc771d4 Feat: Install sqlmodel.
build_develop / build (push) Successful in 37s
2025-07-15 09:20:58 -04:00
imcompiling 70037fb47a Update renovate.json
build_latest / build (push) Successful in 19s
Don't automerge major versions, don't automerge docker minor versions.
2025-07-15 09:05:24 -04:00
renovate-bot 4ae3866e44 Update ghcr.io/astral-sh/uv Docker tag to v0.7.20
build_latest / build (push) Successful in 40s
2025-07-13 04:00:48 +00:00
renovate-bot 1349813f0d Update ghcr.io/astral-sh/uv Docker tag to v0.7.19
build_latest / build (push) Successful in 1m0s
2025-07-06 04:00:49 +00:00
renovate-bot 294b672fe2 Update ghcr.io/astral-sh/uv Docker tag to v0.7.16
build_latest / build (push) Successful in 45s
2025-06-29 04:00:48 +00:00
renovate-bot 72349a4cae Update python Docker tag to v3.13.5
build_latest / build (push) Successful in 1m4s
2025-06-15 04:01:25 +00:00
renovate-bot f6e9d3c32e Update ghcr.io/astral-sh/uv Docker tag to v0.7.13
build_latest / build (push) Waiting to run
2025-06-15 04:01:19 +00:00
renovate-bot 7c8455bf29 Update python Docker tag to v3.13.4
build_latest / build (push) Successful in 51s
2025-06-08 04:01:23 +00:00
renovate-bot f4c4a0435b Update ghcr.io/astral-sh/uv Docker tag to v0.7.12
build_latest / build (push) Waiting to run
2025-06-08 04:01:18 +00:00
renovate-bot bbc63dd77a Update dependency setuptools to <80.9.1,>=80.9.0
build_latest / build (push) Successful in 39s
2025-06-01 04:01:50 +00:00
renovate-bot 7ed3f0d613 Update ghcr.io/astral-sh/uv Docker tag to v0.7.9
build_latest / build (push) Waiting to run
2025-06-01 04:01:17 +00:00
23 changed files with 416 additions and 170 deletions
+2 -1
View File
@@ -9,6 +9,7 @@
"Dakiny",
"DISCORDMANAGER",
"highcouncil",
"nextcord"
"nextcord",
"ondelete"
]
}
+2 -2
View File
@@ -1,10 +1,10 @@
FROM python:3.13.3-slim
FROM python:3.13.5-slim
# install dependencies
RUN apt-get update && apt-get -y upgrade && apt-get -y install git sqlite3
# install uv
COPY --from=ghcr.io/astral-sh/uv:0.7.8 /uv /uvx /bin/
COPY --from=ghcr.io/astral-sh/uv:0.7.20 /uv /uvx /bin/
COPY . /home
+18 -12
View File
@@ -1,6 +1,6 @@
"""Main file for bot."""
import os
import pathlib
import nextcord
from nextcord.ext import commands
@@ -9,9 +9,9 @@ from dakiny_bot.classes.nominate_highcouncil_views import NominateHighCouncilVie
from dakiny_bot.classes.nominate_views import NominateView
from dakiny_bot.classes.voting_highcouncil_views import VoteHighcouncilView
from dakiny_bot.classes.voting_views import VoteView
from dakiny_bot.database import create_database
from dakiny_bot.logger import dakiny_logger
from .DakinySettings import settings
from .dakiny_settings import settings
birthday_list: list[int] = []
@@ -31,19 +31,25 @@ def run() -> None:
bot = commands.Bot(intents=intents)
# Get the modules of all cogs whose directory structure is ./cogs/<module_name>
for folder in os.listdir("dakiny_bot/cogs"):
bot.load_extension(f"dakiny_bot.cogs.{folder}")
for folder in pathlib.Path("dakiny_bot/cogs").iterdir():
bot.load_extension(f"dakiny_bot.cogs.{folder.name}")
@bot.listen()
async def on_ready() -> None:
"""When Discord is connected."""
assert bot.user is not None # noqa: S101 documentation does this
create_database # noqa: B018
bot.add_view(NominateView(bot.get_guild(settings.params.guild_id)))
bot.add_view(NominateHighCouncilView(bot.get_guild(settings.params.guild_id)))
bot.add_view(VoteView(bot.get_guild(settings.params.guild_id)))
bot.add_view(VoteHighcouncilView(bot.get_guild(settings.params.guild_id)))
print(f"{bot.user.name} has connected to Discord!") # noqa: T201 TODO make logging to print my stuff to console
if bot.user is None:
dakiny_logger.error("Discord connection failed.")
return
if (guild := bot.get_guild(settings.params.guild_id)) is None:
dakiny_logger.error("Could not find Dakiny guild object.")
return
bot.add_view(NominateView(guild))
bot.add_view(NominateHighCouncilView(guild))
bot.add_view(VoteView(guild))
bot.add_view(VoteHighcouncilView(guild))
dakiny_logger.info("%s has connected to Discord!", bot.user.name)
# Run Discord bot
bot.run(settings.params.discord_token)
+1 -1
View File
@@ -9,7 +9,7 @@ from dakiny_bot.classes.nominate_highcouncil_views import NominateHighCouncilVie
from dakiny_bot.classes.nominate_views import NominateView
from dakiny_bot.classes.voting_highcouncil_views import VoteHighcouncilView
from dakiny_bot.classes.voting_views import VoteView
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.database.sql_data_classes import (
CouncilMembers,
ElectionInformation,
@@ -1,11 +1,7 @@
"""Contains various views to be used in the high council nomination process."""
import nextcord
from nextcord.interactions import Interaction
from sqlalchemy import select
from sqlalchemy.orm import Session
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.database.sql_data_classes import CouncilMembers, engine
from dakiny_bot.utils import (
NOMINEE_SPLITTER,
@@ -13,6 +9,9 @@ from dakiny_bot.utils import (
decorate_dm_nomination,
get_election_name,
)
from nextcord.interactions import Interaction
from sqlalchemy import select
from sqlalchemy.orm import Session
class NominateDMModal(nextcord.ui.Modal):
+3 -4
View File
@@ -1,14 +1,13 @@
"""Contains various views to be used in the nomination process."""
import nextcord
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.database.sql_data_classes import CouncilMembers, engine
from dakiny_bot.utils import NOMINEE_SPLITTER, decorate_nomination, get_election_name
from nextcord.interactions import Interaction
from sqlalchemy import select
from sqlalchemy.orm import Session
from dakiny_bot.DakinySettings import settings
from dakiny_bot.database.sql_data_classes import CouncilMembers, engine
from dakiny_bot.utils import NOMINEE_SPLITTER, decorate_nomination, get_election_name
class NominateModal(nextcord.ui.Modal):
"""
@@ -1,12 +1,7 @@
"""Contains various views to be used while voting for high council. Controls the logic when performing the vote."""
import nextcord
from nextcord import SelectOption
from nextcord.interactions import Interaction
from sqlalchemy import exc, select, update
from sqlalchemy.orm import Session
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.database.sql_data_classes import (
CouncilMembers,
ElectionInformation,
@@ -14,6 +9,10 @@ from dakiny_bot.database.sql_data_classes import (
engine,
)
from dakiny_bot.utils import VoteType, build_highcouncil_votes_str, get_election_name
from nextcord import SelectOption
from nextcord.interactions import Interaction
from sqlalchemy import exc, select, update
from sqlalchemy.orm import Session
class VoteSelect(nextcord.ui.StringSelect):
+5 -6
View File
@@ -1,12 +1,7 @@
"""Contains various views to be used while voting. Controls the logic when performing the vote."""
import nextcord
from nextcord import SelectOption
from nextcord.interactions import Interaction
from sqlalchemy import exc, select, update
from sqlalchemy.orm import Session
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.database.sql_data_classes import (
CouncilMembers,
ElectionInformation,
@@ -14,6 +9,10 @@ from dakiny_bot.database.sql_data_classes import (
engine,
)
from dakiny_bot.utils import VoteType, build_votes_str, get_election_name
from nextcord import SelectOption
from nextcord.interactions import Interaction
from sqlalchemy import exc, select, update
from sqlalchemy.orm import Session
class VoteSelect(nextcord.ui.StringSelect):
+1 -1
View File
@@ -10,7 +10,7 @@ from git.exc import GitCommandError
from nextcord.ext import commands
from dakiny_bot.classes.gitea_webhook import GiteaWebhook
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.logger import dakiny_logger
from dakiny_bot.utils import REPO_DIR, edit_clan_council_info, update_clan_messages
+1 -1
View File
@@ -4,7 +4,7 @@ import nextcord
from discord import TextInputStyle
from nextcord.ext import commands
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.utils import GUILDS, MAX_DISCORD_MESSAGE_LENGTH, PointType, record_points
+1 -1
View File
@@ -4,7 +4,7 @@ import nextcord
from nextcord.ext import commands
from sqlalchemy.orm import Session
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.database.sql_data_classes import Presences, engine
+1 -1
View File
@@ -3,7 +3,7 @@
import nextcord
from nextcord.ext import commands
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.utils import GUILDS
+1 -1
View File
@@ -5,7 +5,7 @@ from nextcord.ext import application_checks, commands
from dakiny_bot.classes.election import Election
from dakiny_bot.cogs.loops import daily_loop
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.utils import GUILDS, get_active_election_cycle, get_quarter_name
ME = 206602713511886849
+1 -1
View File
@@ -11,7 +11,7 @@ from sqlalchemy.orm import Session
from dakiny_bot.app import birthday_list
from dakiny_bot.classes.election import Election
from dakiny_bot.DakinySettings import settings
from dakiny_bot.dakiny_settings import settings
from dakiny_bot.database.sql_data_classes import UserBirthday, engine
from dakiny_bot.logger import dakiny_logger
from dakiny_bot.utils import get_active_election_cycle
@@ -83,4 +83,5 @@ class DakinySettings(YAMLWizard):
self.to_yaml_file(CONFIG_LOCATION)
settings = DakinySettings.from_yaml_file(CONFIG_LOCATION)
tmp = DakinySettings.from_yaml_file(CONFIG_LOCATION)
settings: DakinySettings = tmp[0] if isinstance(tmp, list) else tmp
-13
View File
@@ -1,13 +0,0 @@
"""Small script to create the database if it doesn't already exist."""
import sqlite3
from pathlib import Path
if not Path("database/dakiny.db").exists():
with sqlite3.connect("database/dakiny.db") as con:
cur = con.cursor()
with Path("dakiny_bot/database/database.sql").open() as file:
database_script = file.read()
cur.executescript(database_script)
con.commit()
+13
View File
@@ -0,0 +1,13 @@
"""Simple file to set up the sqlmodel connection to database."""
from sqlmodel import SQLModel, create_engine
from dakiny_bot.logger import dakiny_logger
from . import models # noqa: F401 - Need this import for creating the models.
url = "sqlite:///database/dakiny.db"
dakiny_logger.info("Connected to local dev database.")
engine = create_engine(url)
SQLModel.metadata.create_all(engine)
+218
View File
@@ -0,0 +1,218 @@
"""File holds all model definitions of SQL tables."""
from sqlalchemy.dialects.mysql import BIGINT, BOOLEAN, INTEGER, VARCHAR
from sqlmodel import Column, Field, ForeignKey, Relationship, SQLModel
class ElectionInformation(SQLModel, table=True):
"""
Represents all required information for an election.
Attributes:
name: Name of the election.
thread_id: Thread of where all the election related messages take place.
council_vote_msg_id: Message where the council vote is presented.
high_council_vote_msg_id: Message where the high council vote is presented.
council_nomination_msg_id: Message where council nomination button is held.
high_council_nomination_msg_id: Message where high council nomination button is held.
council_members: List of council members who ran during this election.
votes: All votes cast during this election.
"""
__tablename__: str = "ElectionInformation"
name: str = Field(sa_column=Column("ElectionName", VARCHAR, primary_key=True, unique=True), max_length=30)
thread_id: int = Field(sa_column=Column("ThreadId", BIGINT(unsigned=True), nullable=False))
council_vote_msg_id: int | None = Field(
sa_column=Column("CouncilVoteMsgId", BIGINT(unsigned=True), nullable=True), default=None
)
high_council_vote_msg_id: int | None = Field(
sa_column=Column("HighCouncilVoteMsgId", BIGINT(unsigned=True), nullable=True), default=None
)
council_nomination_msg_id: int | None = Field(
sa_column=Column("CouncilNominationMsgId", BIGINT(unsigned=True), nullable=True), default=None
)
high_council_nomination_msg_id: int | None = Field(
sa_column=Column("HighCouncilNominationMsgId", BIGINT(unsigned=True), nullable=True), default=None
)
council_members: list["CouncilMember"] = Relationship(back_populates="election", cascade_delete=True)
votes: list["Vote"] = Relationship(back_populates="election", cascade_delete=True)
class CouncilMember(SQLModel, table=True):
"""
Represents members involved in a given election.
Records speech message ids for general election and high council position. Booleans record if the user was elected
to a council/high council position.
Attributes:
member_id: User that is running for council's discord id.
speech_msg_id: Message id of user's speech.
elected: Whether the user got elected to council.
discord_manager: Whether the user got elected to the Discord Manager position.
clan_leader: Whether the user got elected to the Clan Leader position.
discord_manager_speech_id: Message id of the user's Discord Manager speech.
clan_leader_speech_id: Message id of the user's Clan Leader speech.
election: The election this user object is for.
votes: A list of votes for this user.
"""
__tablename__: str = "CouncilMembers"
election_name: str = Field(
sa_column=Column(
"ElectionName",
VARCHAR,
ForeignKey("ElectionInformation.ElectionName", ondelete="CASCADE"),
primary_key=True,
),
max_length=30,
)
member_id: int = Field(sa_column=Column("MemberId", BIGINT(unsigned=True), primary_key=True, nullable=False))
speech_msg_id: int | None = Field(
sa_column=Column("SpeechMsgId", BIGINT(unsigned=True), nullable=False), default=None
)
elected: bool = Field(sa_column=Column("Elected", BOOLEAN), default=False)
discord_manager: bool = Field(sa_column=Column("DiscordManager", BOOLEAN), default=False)
clan_leader: bool = Field(sa_column=Column("ClanLeader", BOOLEAN), default=False)
discord_manager_speech_id: int | None = Field(
sa_column=Column("DiscordManagerSpeechId", BIGINT(unsigned=True), nullable=True), default=None
)
clan_leader_speech_id: int | None = Field(
sa_column=Column("ClanLeaderSpeechId", BIGINT(unsigned=True), nullable=True), default=None
)
election: ElectionInformation | None = Relationship(back_populates="council_members")
votes: list["Vote"] = Relationship(back_populates="council_member")
class Vote(SQLModel, table=True):
"""
Represents a vote cast during an election.
Attributes:
election_name: Election this vote was cast in.
voter_id: User id that cast the vote.
voted_for_id: User id that was voted for.
type: Type of election, council, discordmanager, or clanleader.
election: A link to the ElectionInformation object that the vote was cast in.
council_member: A link to the CouncilMember object that the vote is for.
"""
__tablename__: str = "Votes"
election_name: str = Field(
sa_column=Column(
"ElectionName",
VARCHAR,
ForeignKey("ElectionInformation.ElectionName", ondelete="CASCADE"),
primary_key=True,
),
max_length=30,
)
voter_id: int = Field(sa_column=Column("VoterId", BIGINT(unsigned=True), primary_key=True, nullable=False))
# might have to set this foreign key later with alembic migration...
voted_for_id: int | None = Field(
sa_column=Column("VotedForId", BIGINT(unsigned=True), ForeignKey("CouncilMembers.MemberId"), nullable=True)
)
type: str = Field(
sa_column=Column("Type", VARCHAR, primary_key=True, nullable=False, default="council"), max_length=14
)
election: ElectionInformation | None = Relationship(back_populates="votes")
council_member: CouncilMember | None = Relationship(back_populates="votes")
class UserBirthday(SQLModel, table=True):
"""
Represents a user's birth month and day.
Attributes:
id: User's discord id.
birthday: Month/day that is a user's birthday.
"""
id: int = Field(sa_column=Column("UserId", BIGINT(unsigned=True), primary_key=True, nullable=False))
# TODO(imcompiling): split into month and day. Also relies on Alembic migration.
# https://gitea.cheezers.org/imcompiling/dakiny-bot/issues/93
birthday: str = Field(sa_column=Column("Birthday", VARCHAR, nullable=False), max_length=5)
class Presence(SQLModel, table=True):
"""
Stores presences for the bot to pull and use.
Attributes:
id: Auto-incremented id for each entry.
presence: The presence itself.
"""
__tablename__: str = "Presences"
id: int | None = Field(sa_column=Column("Id", INTEGER, primary_key=True), default=None)
presence: str = Field(sa_column=Column("Presence", VARCHAR, nullable=False), max_length=100)
class Points(SQLModel, table=True):
"""
Stores activity points a user can gain by participating in clan activities.
Event points and clan points were separated out.
Attributes:
quarter_name: Name of the quarter the points were earned in.
user_id: The user that earned them. Is a discord id if the user is a discord member, otherwise their rsn.
discord_member: Boolean on whether the user is a discord member or not. Used to know what the user_id
represents.
event_points: Event points earned during the quarter.
clan_points: Clan points earned during the quarter.
"""
quarter_name: str = Field(sa_column=Column("QuarterName", VARCHAR, primary_key=True, nullable=False), max_length=30)
user_id: str = Field(sa_column=Column("UserId", VARCHAR, primary_key=True, nullable=False), max_length=32)
discord_member: bool = Field(sa_column=Column("DiscordMember", BOOLEAN, nullable=False))
event_points: int = Field(sa_column=Column("EventPoints", INTEGER(unsigned=True), nullable=False), default=0)
clan_points: int = Field(sa_column=Column("ClanPoints", INTEGER(unsigned=True), nullable=False), default=0)
class Message(SQLModel, table=True):
"""
Table is used to map folders and files to channels and messages in discord.
If folder name is stored in path, the corresponding id is a channel id. If the path is to a file, the id is for a
message.
Attributes:
path: Either directory or file pathname.
id: Channel or message id depending on the path.
"""
__tablename__: str = "Messages"
path: str = Field(sa_column=Column("Path", VARCHAR, primary_key=True, nullable=False), max_length=100)
id: int = Field(sa_column=Column("Id", BIGINT(unsigned=True), nullable=False))
class PointsLimit(SQLModel, table=True):
"""
Table tracks how many points a user has gained in a week.
Council didn't want users spamming points, so they added a limit to how many can be gained in a week. This table
tracks point gain per week.
Attributes:
user_id: The user that earned points. Is a discord id if the user is a discord member, otherwise their rsn.
week: week number/year representation of the week. Ex: 04/2025.
event_points: Number of event points earned during this week.
clan_points: Number of clan points earned during this week.
"""
user_id: str = Field(sa_column=Column("UserId", VARCHAR, primary_key=True, nullable=False), max_length=32)
# Maybe should break this out into two columns, week and year. Better data validation and more clear.
week: str = Field(sa_column=Column("Week", VARCHAR, primary_key=True, nullable=False), max_length=7)
event_points: int = Field(sa_column=Column("EventPoints", INTEGER(unsigned=True), nullable=False), default=0)
clan_points: int = Field(sa_column=Column("ClanPoints", INTEGER(unsigned=True), nullable=False), default=0)
-20
View File
@@ -1,20 +0,0 @@
"""Simple file to set up the sqlalchemy connection to database."""
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
# connect with sql alchemy and autoload schema
URL = "sqlite+pysqlite:///database/dakiny.db"
engine = create_engine(URL)
Base = automap_base()
Base.prepare(autoload_with=engine)
# define the classes
Points = Base.classes.Points
PointsLimit = Base.classes.PointsLimit
CouncilMembers = Base.classes.CouncilMembers
ElectionInformation = Base.classes.ElectionInformation
Messages = Base.classes.Messages
Presences = Base.classes.Presences
UserBirthday = Base.classes.UserBirthday
Votes = Base.classes.Votes
+104 -85
View File
@@ -1,7 +1,7 @@
"""File contains util functions."""
import calendar
import os
import pathlib
from collections.abc import Sequence
from datetime import UTC, datetime
from enum import StrEnum
@@ -9,20 +9,15 @@ from pathlib import Path
import aiofiles
import nextcord
from sqlalchemy import select, true, update
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from sqlmodel import col
from dakiny_bot.database.sql_data_classes import (
CouncilMembers,
Messages,
Points,
PointsLimit,
Votes,
engine,
)
from dakiny_bot.database.db import engine
from dakiny_bot.database.models import CouncilMember, Message, Points, PointsLimit, Vote
from dakiny_bot.logger import dakiny_logger
from .DakinySettings import settings
from .dakiny_settings import settings
NOMINEE_SPLITTER = "========================================\n\n"
REPO_DIR = "./dakiny-messages"
@@ -35,7 +30,9 @@ VoteType = StrEnum("VoteType", ["COUNCIL", "DISCORDMANAGER", "CLANLEADER"])
PointType = StrEnum("PointType", ["CLAN", "EVENT"])
def get_datetime(month_day: str) -> datetime:
# TODO(imcompiling): resolve returning None from this function
# https://gitea.cheezers.org/imcompiling/dakiny-bot/issues/102
def get_datetime(month_day: str) -> datetime: # pyright: ignore[reportReturnType]
"""
Takes in a string month and day and returns a datetime object of that Month/Day this year.
@@ -129,7 +126,9 @@ def get_quarter_cycle() -> int:
return cycle
dakiny_logger.debug("Quarter cycle is None.")
return None
# TODO(imcompiling) Add None to return signature or find better return value
# https://gitea.cheezers.org/imcompiling/dakiny-bot/issues/102
return None # pyright: ignore[reportReturnType]
def build_votes_str(guild: nextcord.Guild) -> str:
@@ -147,19 +146,20 @@ def build_votes_str(guild: nextcord.Guild) -> str:
election_name = get_election_name()
with Session(engine) as session:
stmt = select(CouncilMembers).where(CouncilMembers.ElectionName == election_name)
stmt = select(CouncilMember).where(col(CouncilMember.election_name == election_name))
for nominee in sorted(
session.scalars(stmt),
key=lambda nominee: guild.get_member(nominee.MemberId).display_name.lower(),
# Unsure how to None check in the lambda.
key=lambda nominee: guild.get_member(nominee.member_id).display_name.lower(), # pyright: ignore[reportOptionalMemberAccess]
):
votes[nominee.MemberId] = 0
votes[nominee.member_id] = 0
stmt = select(Votes).where(Votes.ElectionName == election_name).where(Votes.Type == VoteType.COUNCIL)
stmt = select(Vote).where(col(Vote.election_name == election_name)).where(col(Vote.type == VoteType.COUNCIL))
for vote in session.scalars(stmt):
if vote.VotedForId is not None:
votes[vote.VotedForId] += 1
if vote.voted_for_id is not None:
votes[vote.voted_for_id] += 1
votes_str: str = "===================="
votes_str += user_vote_str(votes)
@@ -184,46 +184,52 @@ def build_highcouncil_votes_str(guild: nextcord.Guild) -> str:
with Session(engine) as session:
stmt = (
select(CouncilMembers)
.where(CouncilMembers.ElectionName == election_name)
.filter(CouncilMembers.ClanLeaderSpeechId.is_not(None))
select(CouncilMember)
.where(col(CouncilMember.election_name == election_name))
.filter(col(CouncilMember.clan_leader_speech_id is not None))
)
for nominee in sorted(
session.scalars(stmt),
key=lambda nominee: guild.get_member(nominee.MemberId).display_name.lower(),
# Unsure how to None check in the lambda.
key=lambda nominee: guild.get_member(nominee.member_id).display_name.lower(), # pyright: ignore[reportOptionalMemberAccess]
):
cl_votes[nominee.MemberId] = 0
cl_votes[nominee.member_id] = 0
stmt = select(Votes).where(Votes.ElectionName == election_name).where(Votes.Type == VoteType.CLANLEADER)
stmt = select(Vote).where(col(Vote.election_name == election_name)).where(col(Vote.type == VoteType.CLANLEADER))
for vote in session.scalars(stmt):
if vote.VotedForId is not None:
cl_votes[vote.VotedForId] += 1
if vote.voted_for_id is not None:
cl_votes[vote.voted_for_id] += 1
stmt = (
select(CouncilMembers)
.where(CouncilMembers.ElectionName == election_name)
.filter(CouncilMembers.DiscordManagerSpeechId.is_not(None))
select(CouncilMember)
.where(col(CouncilMember.election_name == election_name))
.filter(col(CouncilMember.discord_manager_speech_id is not None))
)
for nominee in sorted(
session.scalars(stmt),
key=lambda nominee: guild.get_member(nominee.MemberId).display_name.lower(),
# Unsure how to None check in the lambda.
key=lambda nominee: guild.get_member(nominee.member_id).display_name.lower(), # pyright: ignore[reportOptionalMemberAccess]
):
dm_votes[nominee.MemberId] = 0
dm_votes[nominee.member_id] = 0
stmt = select(Votes).where(Votes.ElectionName == election_name).where(Votes.Type == VoteType.DISCORDMANAGER)
stmt = (
select(Vote)
.where(col(Vote.election_name == election_name))
.where(col(Vote.type == VoteType.DISCORDMANAGER))
)
for vote in session.scalars(stmt):
if vote.VotedForId is not None:
dm_votes[vote.VotedForId] += 1
if vote.voted_for_id is not None:
dm_votes[vote.voted_for_id] += 1
# build the votes string
votes_str: str = "Clan Leader Votes\n===================="
votes_str: str = "Clan Leader Vote\n===================="
votes_str += user_vote_str(cl_votes)
votes_str += "\n\nDiscord Manager Votes\n===================="
votes_str += "\n\nDiscord Manager Vote\n===================="
votes_str += user_vote_str(dm_votes)
return votes_str
@@ -317,7 +323,7 @@ def record_points(users: Sequence[str], add_points: int, point_type: PointType,
quarter_name = get_quarter_name()
with Session(engine) as session:
for user in users:
stmt = select(Points).where(Points.UserId == user).where(Points.QuarterName == quarter_name)
stmt = select(Points).where(col(Points.user_id == user)).where(col(Points.quarter_name == quarter_name))
points_obj = session.scalar(stmt)
add_points = get_allowed_points(session, point_type, user, add_points)
@@ -325,16 +331,16 @@ def record_points(users: Sequence[str], add_points: int, point_type: PointType,
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,
EventPoints=add_event_points,
ClanPoints=add_clan_points,
quarter_name=quarter_name,
user_id=user,
discord_member=is_member,
event_points=add_event_points,
clan_points=add_clan_points,
)
session.add(new_points)
else:
points_obj.EventPoints += add_event_points
points_obj.ClanPoints += add_clan_points
points_obj.event_points += add_event_points
points_obj.clan_points += add_clan_points
session.commit()
@@ -364,7 +370,7 @@ def get_allowed_points(session: Session, point_type: PointType, user: str, point
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)
stmt = select(PointsLimit).where(col(PointsLimit.user_id == user)).where(col(PointsLimit.week == this_week))
# if under limit, can add up to however many points would make the current limit equal to the
# allowed limit.
@@ -372,16 +378,16 @@ def get_allowed_points(session: Session, point_type: PointType, user: str, point
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)
new_limit = PointsLimit(user_id=user, week=this_week, event_points=event_points, clan_points=clan_points)
add_points = points
session.add(new_limit)
else:
curr_points = limit_obj.EventPoints if point_type == PointType.EVENT else limit_obj.ClanPoints
curr_points = limit_obj.event_points if point_type == PointType.EVENT else limit_obj.clan_points
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
limit_obj.event_points += add_points
else:
limit_obj.ClanPoints += add_points
limit_obj.clan_points += add_points
session.commit()
@@ -410,8 +416,8 @@ async def update_clan_messages(guild: nextcord.Guild, channel_updates: Sequence[
dir_path = f"{MESSAGES_DIR}/{dir_name}"
channel = await get_clan_message_channel(session, dir_name, guild)
sorted_files = sorted(
os.listdir(dir_path),
key=lambda filename: int(filename.split(".")[0]),
pathlib.Path(dir_path).iterdir(),
key=lambda file: int(file.name.split(".")[0]),
)
for file_name in sorted_files:
@@ -440,41 +446,49 @@ async def get_clan_message_channel(session: Session, channel_name: str, guild: n
Returns:
nextcord.TextChannel: Channel object with name channel_name.
"""
stmt = select(Messages.Id).where(Messages.Path == channel_name)
stmt = select(col(Message.id)).where(col(Message.path == channel_name))
channel_id = session.scalar(stmt)
ret_channel = None
if channel_id is None:
ret_channel = None
# channel is not tracked. see if it exists
channels = await guild.fetch_channels()
for channel in channels:
if channel.name == channel_name and channel.__class__ is nextcord.TextChannel:
if channel.name == channel_name and isinstance(channel, nextcord.TextChannel):
ret_channel = channel
if ret_channel is None:
# channel doesn't exist, we must create it
ret_channel = await guild.create_text_channel(
channel_name,
reason="Creating channel as required for by design of Dakiny-Messages repo.",
reason="Creating channel as required for by design of Dakiny-Message repo.",
)
# record channel information
new_item = Messages(Path=channel_name, Id=ret_channel.id)
new_item = Message(path=channel_name, id=ret_channel.id)
session.add(new_item)
session.commit()
return ret_channel
try:
return await guild.fetch_channel(channel_id)
except nextcord.NotFound:
# the channel was deleted for some reason
ret_channel = await guild.create_text_channel(
channel_name,
reason="Creating channel as required for by design of Dakiny-Messages repo.",
)
stmt = update(Messages).where(Messages.Path == channel_name).values(Id=ret_channel.id)
session.execute(stmt)
session.commit()
return ret_channel
else:
try:
ret_channel = await guild.fetch_channel(channel_id)
if not isinstance(ret_channel, nextcord.TextChannel):
dakiny_logger.warning(
"Channel %s is not a text channel. Does not work for clan messages.", ret_channel.name
)
# TODO(imcompiling) Figure out how to handle returning None here. Maybe delete channel and remake it?
# https://gitea.cheezers.org/imcompiling/dakiny-bot/issues/102
return None # pyright: ignore[reportReturnType]
except nextcord.NotFound:
# the channel was deleted for some reason
ret_channel = await guild.create_text_channel(
channel_name,
reason="Creating channel as required for by design of Dakiny-Message repo.",
)
stmt = update(Message).where(col(Message.path == channel_name)).values(id=ret_channel.id)
session.execute(stmt)
session.commit()
return ret_channel
async def edit_clan_message(
@@ -496,21 +510,21 @@ async def edit_clan_message(
message_name (str): Name of the message. Corresponds to the file that contains message content.
message_content (str): Content of the message to edit/send.
"""
stmt = select(Messages.Id).where(Messages.Path == message_name)
stmt = select(col(Message.id)).where(col(Message.path == message_name))
msg_id = session.scalar(stmt)
if msg_id is None:
# don't have a message for this file
msg = await channel.send(message_content)
new_message = Messages(Path=message_name, Id=msg.id)
new_message = Message(path=message_name, id=msg.id)
session.add(new_message)
session.commit()
else:
try:
msg: nextcord.Message = await channel.fetch_message(msg_id)
await msg.edit(message_content)
await msg.edit(content=message_content)
except nextcord.NotFound:
msg = await channel.send(message_content)
stmt = update(Messages).where(Messages.Path == message_name).values(Id=msg.id)
stmt = update(Message).where(col(Message.path == message_name)).values(id=msg.id)
session.execute(stmt)
session.commit()
@@ -522,30 +536,35 @@ async def edit_clan_council_info(guild: nextcord.Guild) -> None:
Args:
guild (nextcord.Guild): Guild object that to use to get channel.
"""
clan_info_channel: nextcord.TextChannel = await guild.fetch_channel(settings.channel_ids.clan_info)
clan_info_channel = await guild.fetch_channel(settings.channel_ids.clan_info)
if not isinstance(clan_info_channel, nextcord.TextChannel):
return
election_name = get_election_name()
with Session(engine) as session:
stmt = (
select(CouncilMembers.MemberId)
.where(CouncilMembers.ElectionName == election_name)
.where(CouncilMembers.DiscordManager == true())
select(col(CouncilMember.member_id))
.where(col(CouncilMember.election_name == election_name))
.where(col(CouncilMember.discord_manager is True))
)
discord_manager = session.scalar(stmt)
stmt = (
select(CouncilMembers.MemberId)
.where(CouncilMembers.ElectionName == election_name)
.where(CouncilMembers.ClanLeader == true())
select(col(CouncilMember.member_id))
.where(col(CouncilMember.election_name == election_name))
.where(col(CouncilMember.clan_leader is True))
)
clan_leader = session.scalar(stmt)
stmt = (
select(CouncilMembers.MemberId)
.where(CouncilMembers.ElectionName == election_name)
.where(CouncilMembers.Elected == true())
select(col(CouncilMember.member_id))
.where(col(CouncilMember.election_name == election_name))
.where(col(CouncilMember.elected is True))
)
council_member_ids = sorted(
session.scalars(stmt), key=lambda user_id: guild.get_member(user_id).display_name.lower()
session.scalars(stmt),
# Unsure how to None check in the lambda.
key=lambda user_id: guild.get_member(user_id).display_name.lower(), # pyright: ignore[reportOptionalMemberAccess]
)
council_members_strs = [
+2 -1
View File
@@ -9,10 +9,11 @@ dependencies = [
"pytz<2025.3,>=2025.2",
"sqlalchemy<3.0.0,>=2.0.30",
"aiofiles<24.0.0,>=23.2.1",
"setuptools<80.8.1,>=80.8.0",
"setuptools<80.9.1,>=80.9.0",
"dataclass-wizard[yaml]>=0.22.3,<1.0.0",
"uvicorn>=0.34.0",
"audioop-lts>=0.2.1",
"sqlmodel>=0.0.24",
]
name = "dakiny-bot"
version = "0.1.0"
+12 -3
View File
@@ -1,8 +1,11 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"lockFileMaintenance": {
"automerge": true,
"enabled": true
"automerge": true
},
"major": {
"automerge": false,
"automergeType": "pr"
},
"minor": {
"automerge": true,
@@ -16,5 +19,11 @@
"automerge": true,
"automergeType": "branch"
},
"ignoreTests": true
"ignoreTests": true,
"dockerfile": {
"minor": {
"automerge": false,
"automergeType": "pr"
}
}
}
Generated
+19 -4
View File
@@ -170,6 +170,7 @@ dependencies = [
{ name = "pytz" },
{ name = "setuptools" },
{ name = "sqlalchemy" },
{ name = "sqlmodel" },
{ name = "uvicorn" },
]
@@ -188,8 +189,9 @@ requires-dist = [
{ name = "nextcord", specifier = ">=2.6.0,<3.0.0" },
{ name = "pandas", specifier = ">=2.2.2,<3.0.0" },
{ name = "pytz", specifier = ">=2025.2,<2025.3" },
{ name = "setuptools", specifier = ">=80.8.0,<80.8.1" },
{ name = "setuptools", specifier = ">=80.9.0,<80.9.1" },
{ name = "sqlalchemy", specifier = ">=2.0.30,<3.0.0" },
{ name = "sqlmodel", specifier = ">=0.0.24" },
{ name = "uvicorn", specifier = ">=0.34.0" },
]
@@ -508,11 +510,11 @@ wheels = [
[[package]]
name = "setuptools"
version = "80.8.0"
version = "80.9.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8d/d2/ec1acaaff45caed5c2dedb33b67055ba9d4e96b091094df90762e60135fe/setuptools-80.8.0.tar.gz", hash = "sha256:49f7af965996f26d43c8ae34539c8d99c5042fbff34302ea151eaa9c207cd257", size = 1319720 }
sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/58/29/93c53c098d301132196c3238c312825324740851d77a8500a2462c0fd888/setuptools-80.8.0-py3-none-any.whl", hash = "sha256:95a60484590d24103af13b686121328cc2736bee85de8936383111e421b9edc0", size = 1201470 },
{ url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486 },
]
[[package]]
@@ -562,6 +564,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b8/49/21633706dd6feb14cd3f7935fc00b60870ea057686035e1a99ae6d9d9d53/SQLAlchemy-2.0.36-py3-none-any.whl", hash = "sha256:fddbe92b4760c6f5d48162aef14824add991aeda8ddadb3c31d56eb15ca69f8e", size = 1883787 },
]
[[package]]
name = "sqlmodel"
version = "0.0.24"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
{ name = "sqlalchemy" },
]
sdist = { url = "https://files.pythonhosted.org/packages/86/4b/c2ad0496f5bdc6073d9b4cef52be9c04f2b37a5773441cc6600b1857648b/sqlmodel-0.0.24.tar.gz", hash = "sha256:cc5c7613c1a5533c9c7867e1aab2fd489a76c9e8a061984da11b4e613c182423", size = 116780 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/16/91/484cd2d05569892b7fef7f5ceab3bc89fb0f8a8c0cde1030d383dbc5449c/sqlmodel-0.0.24-py3-none-any.whl", hash = "sha256:6778852f09370908985b667d6a3ab92910d0d5ec88adcaf23dbc242715ff7193", size = 28622 },
]
[[package]]
name = "starlette"
version = "0.41.3"