Turned on all ruff rules. Formatted all files.

This commit is contained in:
2024-05-22 15:06:39 -04:00
parent 3ac164ab65
commit 796b052bfc
18 changed files with 161 additions and 469 deletions
+29 -89
View File
@@ -55,15 +55,9 @@ class ElectionCycle:
self.term_end: datetime = get_datetime(self.election_cycle.term_end) self.term_end: datetime = get_datetime(self.election_cycle.term_end)
self.voting_start: datetime = get_datetime(self.election_cycle.voting_start) self.voting_start: datetime = get_datetime(self.election_cycle.voting_start)
self.voting_end: datetime = get_datetime(self.election_cycle.voting_end) self.voting_end: datetime = get_datetime(self.election_cycle.voting_end)
self.highcouncil_election_announce: datetime = get_datetime( self.highcouncil_election_announce: datetime = get_datetime(self.election_cycle.highcouncil_election_announce)
self.election_cycle.highcouncil_election_announce self.highcouncil_election_start: datetime = get_datetime(self.election_cycle.highcouncil_election_start)
) self.highcouncil_election_end: datetime = get_datetime(self.election_cycle.highcouncil_election_end)
self.highcouncil_election_start: datetime = get_datetime(
self.election_cycle.highcouncil_election_start
)
self.highcouncil_election_end: datetime = get_datetime(
self.election_cycle.highcouncil_election_end
)
self.guild: nextcord.Guild = guild self.guild: nextcord.Guild = guild
self.election_over: bool = False self.election_over: bool = False
@@ -76,15 +70,11 @@ class ElectionCycle:
long. long.
""" """
with open( with open(f"{TEMPLATES_DIR}/election_announcement.txt", mode="r", encoding="utf8") as file:
f"{TEMPLATES_DIR}/election_announcement.txt", mode="r", encoding="utf8"
) as file:
message = file.read() message = file.read()
next_election = get_datetime( next_election = get_datetime(
self.config.election_cycles[ self.config.election_cycles[(self.cycle + 1) % len(self.config.election_cycles)].election_start
(self.cycle + 1) % len(self.config.election_cycles)
].election_start
) )
message = message.format( message = message.format(
@@ -109,22 +99,14 @@ class ElectionCycle:
str: Message to send. str: Message to send.
""" """
with open( with open(f"{TEMPLATES_DIR}/highcouncil_election.txt", mode="r", encoding="utf8") as file:
f"{TEMPLATES_DIR}/highcouncil_election.txt", mode="r", encoding="utf8"
) as file:
message = file.read() message = file.read()
return message.format( return message.format(
clan_council_elect_role_id=self.config.params.clan_council_elect_role_id, clan_council_elect_role_id=self.config.params.clan_council_elect_role_id,
highcouncil_election_announce=self.highcouncil_election_announce.strftime( highcouncil_election_announce=self.highcouncil_election_announce.strftime("%B %d"),
"%B %d" highcouncil_election_start=self.highcouncil_election_start.strftime("%B %d"),
), highcouncil_election_end=self.highcouncil_election_end.strftime("%B %d"),
highcouncil_election_start=self.highcouncil_election_start.strftime(
"%B %d"
),
highcouncil_election_end=self.highcouncil_election_end.strftime(
"%B %d"
),
term_start=self.term_start.strftime("%B %d"), term_start=self.term_start.strftime("%B %d"),
) )
@@ -136,9 +118,7 @@ class ElectionCycle:
str: Message to send. str: Message to send.
""" """
with open( with open(f"{TEMPLATES_DIR}/highcouncil_vote.txt", mode="r", encoding="utf8") as file:
f"{TEMPLATES_DIR}/highcouncil_vote.txt", mode="r", encoding="utf8"
) as file:
message = file.read() message = file.read()
return message.format( return message.format(
@@ -156,9 +136,7 @@ class ElectionCycle:
with open(f"{TEMPLATES_DIR}/vote_start.txt", mode="r", encoding="utf8") as file: with open(f"{TEMPLATES_DIR}/vote_start.txt", mode="r", encoding="utf8") as file:
message = file.read() message = file.read()
vote_end: datetime = get_datetime( vote_end: datetime = get_datetime(self.config.election_cycles[self.cycle].voting_end)
self.config.election_cycles[self.cycle].voting_end
)
return message.format( return message.format(
clan_member_id=self.config.params.clan_member_role_id, clan_member_id=self.config.params.clan_member_role_id,
@@ -177,11 +155,7 @@ class ElectionCycle:
await self.election_start_action() await self.election_start_action()
elif today.date() == self.voting_start.date(): elif today.date() == self.voting_start.date():
await self.voting_start_action() await self.voting_start_action()
elif ( elif (self.voting_end - timedelta(3)).date() <= today.date() < self.voting_end.date():
(self.voting_end - timedelta(3)).date()
<= today.date()
< self.voting_end.date()
):
await self.election_reminder() await self.election_reminder()
elif today.date() == self.voting_end.date(): elif today.date() == self.voting_end.date():
await self.voting_end_action() await self.voting_end_action()
@@ -195,16 +169,12 @@ class ElectionCycle:
Performs required actions for when the election cycle starts. Performs required actions for when the election cycle starts.
""" """
# create new channel for election # create new channel for election
parent: nextcord.TextChannel = self.guild.get_channel( parent: nextcord.TextChannel = self.guild.get_channel(self.config.params.voting_parent_id)
self.config.params.voting_parent_id
)
quarter_name: str = get_election_name(self.config) quarter_name: str = get_election_name(self.config)
thread_msg: nextcord.Message = await parent.send(content=quarter_name) thread_msg: nextcord.Message = await parent.send(content=quarter_name)
thread: nextcord.Thread = await parent.create_thread( thread: nextcord.Thread = await parent.create_thread(name=quarter_name, message=thread_msg)
name=quarter_name, message=thread_msg
)
# post message announcing election # post message announcing election
# election start message is returned as an array of string because it is too long. send each string # election start message is returned as an array of string because it is too long. send each string
@@ -213,9 +183,7 @@ class ElectionCycle:
for index, message in enumerate(messages): for index, message in enumerate(messages):
# if last item, add the nominate button # if last item, add the nominate button
if index + 1 == len(messages): if index + 1 == len(messages):
nominate_msg: nextcord.Message = await thread.send( nominate_msg: nextcord.Message = await thread.send(message, view=NominateView(self.config, self.guild))
message, view=NominateView(self.config, self.guild)
)
else: else:
await thread.send(message) await thread.send(message)
@@ -235,9 +203,7 @@ class ElectionCycle:
Removes write permission from the general clan member role. Removes write permission from the general clan member role.
""" """
message = self.build_vote_start() message = self.build_vote_start()
election_thread: nextcord.Thread = self.guild.get_thread( election_thread: nextcord.Thread = self.guild.get_thread(self.get_election_info().ThreadId)
self.get_election_info().ThreadId
)
await election_thread.send(message) await election_thread.send(message)
vote_msg = await election_thread.send( vote_msg = await election_thread.send(
build_votes_str(self.config, self.guild), build_votes_str(self.config, self.guild),
@@ -253,9 +219,7 @@ class ElectionCycle:
session.commit() session.commit()
thread: nextcord.Thread = self.guild.get_thread(info.ThreadId) thread: nextcord.Thread = self.guild.get_thread(info.ThreadId)
nominate_msg: nextcord.Message = await thread.fetch_message( nominate_msg: nextcord.Message = await thread.fetch_message(info.CouncilNominationMsgId)
info.CouncilNominationMsgId
)
await nominate_msg.edit(view=None) await nominate_msg.edit(view=None)
async def voting_end_action(self) -> None: async def voting_end_action(self) -> None:
@@ -264,12 +228,8 @@ class ElectionCycle:
""" """
message = self.build_highcouncil_election_announce() message = self.build_highcouncil_election_announce()
council_elect_role: nextcord.Role = self.guild.get_role( council_elect_role: nextcord.Role = self.guild.get_role(self.config.params.clan_council_elect_role_id)
self.config.params.clan_council_elect_role_id election_thread: nextcord.Thread = self.guild.get_thread(self.get_election_info().ThreadId)
)
election_thread: nextcord.Thread = self.guild.get_thread(
self.get_election_info().ThreadId
)
nominate_msg: nextcord.Message = await election_thread.send( nominate_msg: nextcord.Message = await election_thread.send(
message, view=NominateHighCouncilView(self.config, self.guild) message, view=NominateHighCouncilView(self.config, self.guild)
@@ -279,13 +239,9 @@ class ElectionCycle:
with Session(engine) as session: with Session(engine) as session:
# remove vote button from vote message # remove vote button from vote message
stmt = select(ElectionInformation).where( stmt = select(ElectionInformation).where(ElectionInformation.ElectionCycle == election_name)
ElectionInformation.ElectionCycle == election_name
)
info = session.scalar(stmt) info = session.scalar(stmt)
vote_msg: nextcord.Message = await election_thread.fetch_message( vote_msg: nextcord.Message = await election_thread.fetch_message(info.CouncilVoteMsgId)
info.CouncilVoteMsgId
)
await vote_msg.edit(view=None) await vote_msg.edit(view=None)
# add the highcouncil nomination message to election information # add the highcouncil nomination message to election information
@@ -324,9 +280,7 @@ class ElectionCycle:
""" """
message = self.build_highcouncil_vote_start() message = self.build_highcouncil_vote_start()
election_thread: nextcord.Thread = self.guild.get_thread( election_thread: nextcord.Thread = self.guild.get_thread(self.get_election_info().ThreadId)
self.get_election_info().ThreadId
)
await election_thread.send(message) await election_thread.send(message)
vote_msg = await election_thread.send( vote_msg = await election_thread.send(
build_highcouncil_votes_str(self.config, self.guild), build_highcouncil_votes_str(self.config, self.guild),
@@ -342,9 +296,7 @@ class ElectionCycle:
session.commit() session.commit()
# remove highcouncil nomination view # remove highcouncil nomination view
nomination_msg: nextcord.Message = await election_thread.fetch_message( nomination_msg: nextcord.Message = await election_thread.fetch_message(info.HighCouncilNominationMsgId)
info.HighCouncilNominationMsgId
)
await nomination_msg.edit(view=None) await nomination_msg.edit(view=None)
async def term_start_action(self) -> None: async def term_start_action(self) -> None:
@@ -354,12 +306,8 @@ class ElectionCycle:
self.election_over = True self.election_over = True
elect_role: nextcord.Role = self.guild.get_role( elect_role: nextcord.Role = self.guild.get_role(self.config.params.clan_council_elect_role_id)
self.config.params.clan_council_elect_role_id council_role: nextcord.Role = self.guild.get_role(self.config.params.clan_council_role_id)
)
council_role: nextcord.Role = self.guild.get_role(
self.config.params.clan_council_role_id
)
election_cycle = get_election_name(self.config) election_cycle = get_election_name(self.config)
@@ -422,9 +370,7 @@ class ElectionCycle:
session.commit() session.commit()
election_thread: nextcord.Thread = self.guild.get_thread( election_thread: nextcord.Thread = self.guild.get_thread(self.get_election_info().ThreadId)
self.get_election_info().ThreadId
)
# clear view from vote message # clear view from vote message
stmt = select(ElectionInformation.HighCouncilVoteMsgId).where( stmt = select(ElectionInformation.HighCouncilVoteMsgId).where(
@@ -434,15 +380,11 @@ class ElectionCycle:
vote_msg: nextcord.Message = await election_thread.fetch_message(vote_msg_id) vote_msg: nextcord.Message = await election_thread.fetch_message(vote_msg_id)
await vote_msg.edit(view=None) await vote_msg.edit(view=None)
highcouncil_msg: str = ( highcouncil_msg: str = f"Congratulations for our high council members!\nClan Leader: <@{cl_winner}>\n"
f"Congratulations for our high council members!\nClan Leader: <@{cl_winner}>\n"
)
highcouncil_msg += f"Discord Manager: <@{dm_winner}>" highcouncil_msg += f"Discord Manager: <@{dm_winner}>"
await election_thread.send(highcouncil_msg) await election_thread.send(highcouncil_msg)
await election_thread.send( await election_thread.send("This election cycle is now over. Thank you everyone for participating!")
"This election cycle is now over. Thank you everyone for participating!"
)
await election_thread.edit(archived=True, locked=True) await election_thread.edit(archived=True, locked=True)
await edit_clan_council_info(self.guild, self.config) await edit_clan_council_info(self.guild, self.config)
@@ -466,9 +408,7 @@ class ElectionCycle:
Sends a message to general chat reminder clan about election. Sends a message to general chat reminder clan about election.
""" """
general: nextcord.TextChannel = self.guild.get_channel( general: nextcord.TextChannel = self.guild.get_channel(self.config.params.general_channel_id)
self.config.params.general_channel_id
)
message = f"Reminder to <@&{self.config.params.clan_member_role_id}>! Clan elections are happening! Head over " message = f"Reminder to <@&{self.config.params.clan_member_role_id}>! Clan elections are happening! Head over "
message += f"to <#{self.get_election_info().ThreadId}> to cast your vote!" message += f"to <#{self.get_election_info().ThreadId}> to cast your vote!"
+11 -39
View File
@@ -74,14 +74,8 @@ class NominateDMModal(nextcord.ui.Modal):
council_elect.DiscordManagerSpeechId = msg.id council_elect.DiscordManagerSpeechId = msg.id
session.commit() session.commit()
else: else:
msg: nextcord.Message = await interaction.channel.fetch_message( msg: nextcord.Message = await interaction.channel.fetch_message(council_elect.DiscordManagerSpeechId)
council_elect.DiscordManagerSpeechId await msg.edit(content=decorate_dm_nomination(interaction.user.id, self.speech.value))
)
await msg.edit(
content=decorate_dm_nomination(
interaction.user.id, self.speech.value
)
)
class NominateCLModal(nextcord.ui.Modal): class NominateCLModal(nextcord.ui.Modal):
@@ -141,14 +135,8 @@ class NominateCLModal(nextcord.ui.Modal):
council_elect.ClanLeaderSpeechId = msg.id council_elect.ClanLeaderSpeechId = msg.id
session.commit() session.commit()
else: else:
msg: nextcord.Message = await interaction.channel.fetch_message( msg: nextcord.Message = await interaction.channel.fetch_message(council_elect.ClanLeaderSpeechId)
council_elect.ClanLeaderSpeechId await msg.edit(content=decorate_cl_nomination(interaction.user.id, self.speech.value))
)
await msg.edit(
content=decorate_cl_nomination(
interaction.user.id, self.speech.value
)
)
class NominateHighCouncilView(nextcord.ui.View): class NominateHighCouncilView(nextcord.ui.View):
@@ -166,9 +154,7 @@ class NominateHighCouncilView(nextcord.ui.View):
style=nextcord.ButtonStyle.primary, style=nextcord.ButtonStyle.primary,
custom_id="nominate-dm", custom_id="nominate-dm",
) )
async def nominate_dm( async def nominate_dm(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None:
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
) -> None:
""" """
Gathers previous information about the user if they have already nominated themselves, then launches Gathers previous information about the user if they have already nominated themselves, then launches
the nomination modal to get their speech. the nomination modal to get their speech.
@@ -179,10 +165,7 @@ class NominateHighCouncilView(nextcord.ui.View):
""" """
# enforce council elect only # enforce council elect only
if ( if self.guild.get_role(self.config.params.clan_council_elect_role_id) not in interaction.user.roles:
self.guild.get_role(self.config.params.clan_council_elect_role_id)
not in interaction.user.roles
):
await interaction.response.send_message( await interaction.response.send_message(
f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.", f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.",
ephemeral=True, ephemeral=True,
@@ -203,15 +186,11 @@ class NominateHighCouncilView(nextcord.ui.View):
# user needs to exist to get here anyways... # user needs to exist to get here anyways...
if obj.DiscordManagerSpeechId is not None: if obj.DiscordManagerSpeechId is not None:
usr_nominated = True usr_nominated = True
msg = await interaction.channel.fetch_message( msg = await interaction.channel.fetch_message(obj.DiscordManagerSpeechId)
obj.DiscordManagerSpeechId
)
speech_content = msg.content.split(NOMINEE_SPLITTER)[1] speech_content = msg.content.split(NOMINEE_SPLITTER)[1]
await interaction.response.send_modal( await interaction.response.send_modal(
NominateDMModal( NominateDMModal(self.config, interaction.user.id, usr_nominated, speech_content)
self.config, interaction.user.id, usr_nominated, speech_content
)
) )
@nextcord.ui.button( @nextcord.ui.button(
@@ -219,9 +198,7 @@ class NominateHighCouncilView(nextcord.ui.View):
style=nextcord.ButtonStyle.primary, style=nextcord.ButtonStyle.primary,
custom_id="nominate-cl", custom_id="nominate-cl",
) )
async def nominate_cl( async def nominate_cl(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None:
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
) -> None:
""" """
Gathers previous information about the user if they have already nominated themselves, then launches Gathers previous information about the user if they have already nominated themselves, then launches
the nomination modal to get their speech. the nomination modal to get their speech.
@@ -232,10 +209,7 @@ class NominateHighCouncilView(nextcord.ui.View):
""" """
# enforce council elect only # enforce council elect only
if ( if self.guild.get_role(self.config.params.clan_council_elect_role_id) not in interaction.user.roles:
self.guild.get_role(self.config.params.clan_council_elect_role_id)
not in interaction.user.roles
):
await interaction.response.send_message( await interaction.response.send_message(
f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.", f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.",
ephemeral=True, ephemeral=True,
@@ -260,7 +234,5 @@ class NominateHighCouncilView(nextcord.ui.View):
speech_content = msg.content.split(NOMINEE_SPLITTER)[1] speech_content = msg.content.split(NOMINEE_SPLITTER)[1]
await interaction.response.send_modal( await interaction.response.send_modal(
NominateCLModal( NominateCLModal(self.config, interaction.user.id, usr_nominated, speech_content)
self.config, interaction.user.id, usr_nominated, speech_content
)
) )
+5 -16
View File
@@ -74,12 +74,8 @@ class NominateModal(nextcord.ui.Modal):
) )
obj = session.scalar(stmt) obj = session.scalar(stmt)
msg: nextcord.Message = await interaction.channel.fetch_message( msg: nextcord.Message = await interaction.channel.fetch_message(obj.SpeechMsgId)
obj.SpeechMsgId await msg.edit(content=decorate_nomination(interaction.user.id, self.speech.value))
)
await msg.edit(
content=decorate_nomination(interaction.user.id, self.speech.value)
)
class NominateView(nextcord.ui.View): class NominateView(nextcord.ui.View):
@@ -97,9 +93,7 @@ class NominateView(nextcord.ui.View):
style=nextcord.ButtonStyle.primary, style=nextcord.ButtonStyle.primary,
custom_id="nominate", custom_id="nominate",
) )
async def nominate( async def nominate(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None:
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
) -> None:
""" """
Gathers previous information about the user if they have already nominated themselves, then launches Gathers previous information about the user if they have already nominated themselves, then launches
the nomination modal to get their speech. the nomination modal to get their speech.
@@ -110,10 +104,7 @@ class NominateView(nextcord.ui.View):
""" """
# enforce members only # enforce members only
if ( if self.guild.get_role(self.config.params.clan_member_role_id) not in interaction.user.roles:
self.guild.get_role(self.config.params.clan_member_role_id)
not in interaction.user.roles
):
await interaction.response.send_message( await interaction.response.send_message(
f"You must have the <@&{self.config.params.clan_member_role_id}> role to vote.", f"You must have the <@&{self.config.params.clan_member_role_id}> role to vote.",
ephemeral=True, ephemeral=True,
@@ -136,7 +127,5 @@ class NominateView(nextcord.ui.View):
speech_content = msg.content.split(NOMINEE_SPLITTER)[1] speech_content = msg.content.split(NOMINEE_SPLITTER)[1]
await interaction.response.send_modal( await interaction.response.send_modal(
NominateModal( NominateModal(self.config, interaction.user.id, usr_nominated, speech_content)
self.config, interaction.user.id, usr_nominated, speech_content
)
) )
+7 -25
View File
@@ -21,9 +21,7 @@ from utils import VoteType, build_highcouncil_votes_str, get_election_name
class VoteSelect(nextcord.ui.StringSelect): class VoteSelect(nextcord.ui.StringSelect):
def __init__( def __init__(self, options: List["SelectOption"], config: DakinyConfig, election_type: str) -> None:
self, options: List["SelectOption"], config: DakinyConfig, election_type: str
) -> None:
super().__init__( super().__init__(
placeholder="Choose 1", placeholder="Choose 1",
min_values=1, min_values=1,
@@ -71,9 +69,7 @@ class VoteSelect(nextcord.ui.StringSelect):
session.commit() session.commit()
vote_message_str = build_highcouncil_votes_str(self.config, interaction.guild) vote_message_str = build_highcouncil_votes_str(self.config, interaction.guild)
vote_msg: nextcord.Message = await interaction.channel.fetch_message( vote_msg: nextcord.Message = await interaction.channel.fetch_message(vote_msg_id)
vote_msg_id
)
await vote_msg.edit(content=vote_message_str) await vote_msg.edit(content=vote_message_str)
if voted_for is not None: if voted_for is not None:
@@ -99,9 +95,7 @@ class VoteHighcouncilView(nextcord.ui.View):
style=nextcord.ButtonStyle.primary, style=nextcord.ButtonStyle.primary,
custom_id="vote-cl", custom_id="vote-cl",
) )
async def vote_cl( async def vote_cl(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None:
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
) -> None:
""" """
Enforces only council elect vote. Gets election cycle, creates voting Enforces only council elect vote. Gets election cycle, creates voting
options for clan leader (checking if user has voted already), options for clan leader (checking if user has voted already),
@@ -113,10 +107,7 @@ class VoteHighcouncilView(nextcord.ui.View):
""" """
# enforce council elect only # enforce council elect only
if ( if self.guild.get_role(self.config.params.clan_council_elect_role_id) not in interaction.user.roles:
self.guild.get_role(self.config.params.clan_council_elect_role_id)
not in interaction.user.roles
):
await interaction.response.send_message( await interaction.response.send_message(
f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.", f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.",
ephemeral=True, ephemeral=True,
@@ -162,11 +153,7 @@ class VoteHighcouncilView(nextcord.ui.View):
) )
view = nextcord.ui.View() view = nextcord.ui.View()
view.add_item( view.add_item(VoteSelect(options=options, config=self.config, election_type=VoteType.CLANLEADER))
VoteSelect(
options=options, config=self.config, election_type=VoteType.CLANLEADER
)
)
await interaction.response.send_message( await interaction.response.send_message(
content="Please vote for a Clan Leader!", content="Please vote for a Clan Leader!",
@@ -179,9 +166,7 @@ class VoteHighcouncilView(nextcord.ui.View):
style=nextcord.ButtonStyle.primary, style=nextcord.ButtonStyle.primary,
custom_id="vote-dm", custom_id="vote-dm",
) )
async def vote_dm( async def vote_dm(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None:
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
) -> None:
""" """
Enforces only council elect vote. Gets election cycle, creates voting Enforces only council elect vote. Gets election cycle, creates voting
options for discord manager (checking if user has voted already), options for discord manager (checking if user has voted already),
@@ -193,10 +178,7 @@ class VoteHighcouncilView(nextcord.ui.View):
""" """
# enforce council elect only # enforce council elect only
if ( if self.guild.get_role(self.config.params.clan_council_elect_role_id) not in interaction.user.roles:
self.guild.get_role(self.config.params.clan_council_elect_role_id)
not in interaction.user.roles
):
await interaction.response.send_message( await interaction.response.send_message(
f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.", f"You must have the <@&{self.config.params.clan_council_elect_role_id}> role to vote.",
ephemeral=True, ephemeral=True,
+5 -16
View File
@@ -67,9 +67,7 @@ class VoteSelect(nextcord.ui.StringSelect):
session.commit() session.commit()
vote_message_str = build_votes_str(self.config, interaction.guild) vote_message_str = build_votes_str(self.config, interaction.guild)
vote_msg: nextcord.Message = await interaction.channel.fetch_message( vote_msg: nextcord.Message = await interaction.channel.fetch_message(vote_msg_id)
vote_msg_id
)
await vote_msg.edit(content=vote_message_str) await vote_msg.edit(content=vote_message_str)
if voted_for is not None: if voted_for is not None:
@@ -90,12 +88,8 @@ class VoteView(nextcord.ui.View):
self.config = config self.config = config
self.guild = guild self.guild = guild
@nextcord.ui.button( @nextcord.ui.button(label="Vote", style=nextcord.ButtonStyle.primary, custom_id="vote")
label="Vote", style=nextcord.ButtonStyle.primary, custom_id="vote" async def vote(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None:
)
async def vote(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
) -> None:
""" """
Enforces only members vote. Gets election cycle, creates voting options (checking if user has voted already), Enforces only members vote. Gets election cycle, creates voting options (checking if user has voted already),
then sends the voting view. then sends the voting view.
@@ -106,10 +100,7 @@ class VoteView(nextcord.ui.View):
""" """
# enforce members only # enforce members only
if ( if self.guild.get_role(self.config.params.clan_member_role_id) not in interaction.user.roles:
self.guild.get_role(self.config.params.clan_member_role_id)
not in interaction.user.roles
):
await interaction.response.send_message( await interaction.response.send_message(
f"You must have the <@&{self.config.params.clan_member_role_id}> role to vote.", f"You must have the <@&{self.config.params.clan_member_role_id}> role to vote.",
ephemeral=True, ephemeral=True,
@@ -127,9 +118,7 @@ class VoteView(nextcord.ui.View):
) )
voted_for = session.scalar(stmt) voted_for = session.scalar(stmt)
stmt = select(CouncilMembers.MemberId).where( stmt = select(CouncilMembers.MemberId).where(CouncilMembers.ElectionCycle == election)
CouncilMembers.ElectionCycle == election
)
options = [ options = [
SelectOption( SelectOption(
+6 -20
View File
@@ -47,19 +47,11 @@ class ClanMessages(commands.Cog, name="Clan Messages"):
# Get all modified/added files # Get all modified/added files
modified_files: list[str] = [ modified_files: list[str] = [
file file for list in [commit.modified + commit.added for commit in hook_info.commits] for file in list
for list in [commit.modified + commit.added for commit in hook_info.commits]
for file in list
] ]
template_updates = { template_updates = {file.split("/")[1] for file in modified_files if "message_templates" in file}
file.split("/")[1] for file in modified_files if "message_templates" in file channel_updates = {file.split("/")[1] for file in modified_files if file.split("/")[1] not in template_updates}
}
channel_updates = {
file.split("/")[1]
for file in modified_files
if file.split("/")[1] not in template_updates
}
self.origin.pull() self.origin.pull()
guild: nextcord.Guild = self.bot.get_guild(self.config.params.guild_id) guild: nextcord.Guild = self.bot.get_guild(self.config.params.guild_id)
@@ -68,9 +60,7 @@ class ClanMessages(commands.Cog, name="Clan Messages"):
# if the council members template has changed, update the message # if the council members template has changed, update the message
if "council_members.txt" in template_updates: if "council_members.txt" in template_updates:
await edit_clan_council_info( await edit_clan_council_info(self.bot.get_guild(self.config.params.guild_id), self.config)
self.bot.get_guild(self.config.params.guild_id), self.config
)
return {"message": "Successfully updated all discord messages."} return {"message": "Successfully updated all discord messages."}
@@ -87,13 +77,9 @@ class ClanMessages(commands.Cog, name="Clan Messages"):
self.origin = self.repo.remote("origin") self.origin = self.repo.remote("origin")
if self.config.params.git_branch == "test": if self.config.params.git_branch == "test":
self.repo.create_head("test", self.origin.refs.test).set_tracking_branch( self.repo.create_head("test", self.origin.refs.test).set_tracking_branch(self.origin.refs.test).checkout()
self.origin.refs.test
).checkout()
else: else:
self.repo.create_head("main", self.origin.refs.main).set_tracking_branch( self.repo.create_head("main", self.origin.refs.main).set_tracking_branch(self.origin.refs.main).checkout()
self.origin.refs.main
).checkout()
self.origin.pull() self.origin.pull()
+12 -37
View File
@@ -32,9 +32,7 @@ class RecordCog(commands.Cog, name="Record Commands"):
async def event( async def event(
self, self,
interaction: nextcord.Interaction, interaction: nextcord.Interaction,
name: str = nextcord.SlashOption( name: str = nextcord.SlashOption(required=True, description="Name of the event that was hosted."),
required=True, description="Name of the event that was hosted."
),
host: nextcord.Member = nextcord.SlashOption( host: nextcord.Member = nextcord.SlashOption(
required=False, required=False,
description="An alternative host if you are recording event for someone else.", description="An alternative host if you are recording event for someone else.",
@@ -51,10 +49,7 @@ class RecordCog(commands.Cog, name="Record Commands"):
""" """
# check role # check role
if ( if interaction.guild.get_role(self.bot.config.params.event_host_role_id) not in interaction.user.roles:
interaction.guild.get_role(self.bot.config.params.event_host_role_id)
not in interaction.user.roles
):
await interaction.response.send_message( await interaction.response.send_message(
f"You must have the <@&{self.bot.config.params.event_host_role_id}> role to record an event.", f"You must have the <@&{self.bot.config.params.event_host_role_id}> role to record an event.",
ephemeral=True, ephemeral=True,
@@ -95,15 +90,11 @@ class EventView(nextcord.ui.View):
self.add_item(self.event_participants) self.add_item(self.event_participants)
@nextcord.ui.button(label="Cancel", style=nextcord.ButtonStyle.red, row=1) @nextcord.ui.button(label="Cancel", style=nextcord.ButtonStyle.red, row=1)
async def cancel( async def cancel(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
""" """
Cancels event submission. Removes embed and view. Cancels event submission. Removes embed and view.
""" """
await interaction.response.edit_message( await interaction.response.edit_message("Canceled", ephemeral=True, embed=None, view=None)
"Canceled", ephemeral=True, embed=None, view=None
)
self.stop() self.stop()
@nextcord.ui.button(label="Edit", style=nextcord.ButtonStyle.blurple, row=1) @nextcord.ui.button(label="Edit", style=nextcord.ButtonStyle.blurple, row=1)
@@ -111,14 +102,10 @@ class EventView(nextcord.ui.View):
""" """
Calls modal to update the text input information of the event. Calls modal to update the text input information of the event.
""" """
await interaction.response.send_modal( await interaction.response.send_modal(ParticipantModal(interaction.message.embeds[0]))
ParticipantModal(interaction.message.embeds[0])
)
@nextcord.ui.button(label="Confirm", style=nextcord.ButtonStyle.green, row=1) @nextcord.ui.button(label="Confirm", style=nextcord.ButtonStyle.green, row=1)
async def confirm( async def confirm(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
""" """
Submits the event embed to the event channel. Removes view and embed from recording message. Submits the event embed to the event channel. Removes view and embed from recording message.
Sends point information to database. Sends point information to database.
@@ -126,9 +113,7 @@ class EventView(nextcord.ui.View):
discord_users = self.event_participants.values.members discord_users = self.event_participants.values.members
if discord_users: if discord_users:
discord_users_list: list[str] = [ discord_users_list: list[str] = [str(user.id) for user in discord_users if user.id is not self.host_id]
str(user.id) for user in discord_users if user.id is not self.host_id
]
record_event_points( record_event_points(
self.config, self.config,
discord_users_list, discord_users_list,
@@ -146,17 +131,11 @@ class EventView(nextcord.ui.View):
self.config.params.event_participate_points, self.config.params.event_participate_points,
) )
record_event_points( record_event_points(self.config, [self.host_id], True, self.config.params.event_host_points)
self.config, [self.host_id], True, self.config.params.event_host_points
)
event_channel: nextcord.TextChannel = interaction.guild.get_channel( event_channel: nextcord.TextChannel = interaction.guild.get_channel(self.config.params.event_post_channel_id)
self.config.params.event_post_channel_id
)
await event_channel.send(embed=interaction.message.embeds[0]) await event_channel.send(embed=interaction.message.embeds[0])
await interaction.response.edit_message( await interaction.response.edit_message(content="Event has been submitted.", view=None, embed=None)
content="Event has been submitted.", view=None, embed=None
)
self.stop() self.stop()
@@ -201,9 +180,7 @@ class ParticipantModal(nextcord.ui.Modal):
async def callback(self, interaction: nextcord.Interaction): async def callback(self, interaction: nextcord.Interaction):
self.embed.title = self.name.value self.embed.title = self.name.value
self.embed.description = self.description.value self.embed.description = self.description.value
self.embed.set_field_at( self.embed.set_field_at(index=1, name="Non-Discord Participants", value=self.participants.value)
index=1, name="Non-Discord Participants", value=self.participants.value
)
await interaction.response.edit_message(embed=self.embed) await interaction.response.edit_message(embed=self.embed)
@@ -223,8 +200,6 @@ class ParticipantSelect(nextcord.ui.UserSelect):
async def callback(self, interaction: nextcord.Interaction): async def callback(self, interaction: nextcord.Interaction):
embed: nextcord.Embed = interaction.message.embeds[0] embed: nextcord.Embed = interaction.message.embeds[0]
participants: str = "\n".join( participants: str = "\n".join([f"<@{participant.id}>" for participant in self.values.members])
[f"<@{participant.id}>" for participant in self.values.members]
)
embed.set_field_at(0, name="Participants", value=participants) embed.set_field_at(0, name="Participants", value=participants)
await interaction.response.edit_message(embed=embed) await interaction.response.edit_message(embed=embed)
+3 -9
View File
@@ -22,9 +22,7 @@ class RefreshCog(commands.Cog, name="Refresh Commands"):
super().__init__() super().__init__()
self.bot: commands.Bot = bot self.bot: commands.Bot = bot
@nextcord.slash_command( @nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
default_member_permissions=nextcord.Permissions(administrator=True)
)
async def refresh(self, interaction: nextcord.Interaction): async def refresh(self, interaction: nextcord.Interaction):
""" """
Parent slash command for refresh. Never called. Parent slash command for refresh. Never called.
@@ -50,9 +48,7 @@ class RefreshCog(commands.Cog, name="Refresh Commands"):
if channel is None: if channel is None:
channel_updates = [ channel_updates = [
dir_name dir_name for dir_name in os.listdir(MESSAGES_DIR) if os.path.isdir(f"{MESSAGES_DIR}/{dir_name}")
for dir_name in os.listdir(MESSAGES_DIR)
if os.path.isdir(f"{MESSAGES_DIR}/{dir_name}")
] ]
else: else:
channel_updates = [channel.name] channel_updates = [channel.name]
@@ -69,6 +65,4 @@ class RefreshCog(commands.Cog, name="Refresh Commands"):
interaction (nextcord.Interaction): Interaction with the command. interaction (nextcord.Interaction): Interaction with the command.
""" """
await edit_clan_council_info(interaction.guild, self.bot.config) await edit_clan_council_info(interaction.guild, self.bot.config)
await interaction.response.send_message( await interaction.response.send_message("Clan Council Info message updated.", ephemeral=True)
"Clan Council Info message updated.", ephemeral=True
)
+5 -15
View File
@@ -32,9 +32,7 @@ class RemoveCog(commands.Cog, name="Remove Commands"):
async def presence( async def presence(
self, self,
interaction: nextcord.Interaction, interaction: nextcord.Interaction,
presence_str: str = nextcord.SlashOption( presence_str: str = nextcord.SlashOption(description="The presence to remove", required=True),
description="The presence to remove", required=True
),
): ):
""" """
Deletes the given presence id from the database. Deletes the given presence id from the database.
@@ -53,9 +51,7 @@ class RemoveCog(commands.Cog, name="Remove Commands"):
await interaction.response.send_message("Presence deleted.", ephemeral=True) await interaction.response.send_message("Presence deleted.", ephemeral=True)
@presence.on_autocomplete("presence_str") @presence.on_autocomplete("presence_str")
async def presence_autocomplete( async def presence_autocomplete(self, interaction: nextcord.Interaction, presence_str: str):
self, interaction: nextcord.Interaction, presence_str: str
):
""" """
Collects all presences that start with the presence string. Collects all presences that start with the presence string.
Sends autocomplete dict {Presence Name, Presence Id} Sends autocomplete dict {Presence Name, Presence Id}
@@ -67,20 +63,14 @@ class RemoveCog(commands.Cog, name="Remove Commands"):
with Session(engine) as session: with Session(engine) as session:
stmt = select(Presences) stmt = select(Presences)
presences_dict: "dict[str,str]" = { presences_dict: "dict[str,str]" = {pres.Presence: str(pres.Id) for pres in session.scalars(stmt)}
pres.Presence: str(pres.Id) for pres in session.scalars(stmt)
}
# if empty compare string # if empty compare string
if not presence_str: if not presence_str:
await interaction.response.send_autocomplete( await interaction.response.send_autocomplete(dict(list(presences_dict.items())[:25]))
dict(list(presences_dict.items())[:25])
)
return return
autofilled_presences: "dict[str,str]" = { autofilled_presences: "dict[str,str]" = {
pres: pres_id pres: pres_id for pres, pres_id in presences_dict.items() if presence_str.lower() in pres.lower()
for pres, pres_id in presences_dict.items()
if presence_str.lower() in pres.lower()
} }
await interaction.response.send_autocomplete(autofilled_presences[:25]) await interaction.response.send_autocomplete(autofilled_presences[:25])
+10 -31
View File
@@ -27,9 +27,7 @@ class RequestCog(commands.Cog, name="Request Commands"):
Parent slash command for request. Never called. Parent slash command for request. Never called.
""" """
@request.subcommand( @request.subcommand(description="Request to add a presence to the bot's presence list.")
description="Request to add a presence to the bot's presence list."
)
async def add_presence( async def add_presence(
self, self,
interaction: nextcord.Interaction, interaction: nextcord.Interaction,
@@ -51,12 +49,8 @@ class RequestCog(commands.Cog, name="Request Commands"):
config: DakinyConfig = self.bot.config config: DakinyConfig = self.bot.config
content = f'<@{interaction.user.id}> would like to add presence "{presence}."' content = f'<@{interaction.user.id}> would like to add presence "{presence}."'
view = PresenceChange(presence) view = PresenceChange(presence)
await self.bot.get_channel(config.params.admin_channel_id).send( await self.bot.get_channel(config.params.admin_channel_id).send(content=content, view=view)
content=content, view=view await interaction.response.send_message("Request sent to admins.", ephemeral=True)
)
await interaction.response.send_message(
"Request sent to admins.", ephemeral=True
)
@request.subcommand(description="Request to change your Dakiny nickname") @request.subcommand(description="Request to change your Dakiny nickname")
async def change_nickname( async def change_nickname(
@@ -80,12 +74,8 @@ class RequestCog(commands.Cog, name="Request Commands"):
config: DakinyConfig = self.bot.config config: DakinyConfig = self.bot.config
content = f'<@{interaction.user.id}> would like to change their username to "{new_nickname}."' content = f'<@{interaction.user.id}> would like to change their username to "{new_nickname}."'
view = UsernameRequest(interaction.user.id, new_nickname) view = UsernameRequest(interaction.user.id, new_nickname)
await self.bot.get_channel(config.params.admin_channel_id).send( await self.bot.get_channel(config.params.admin_channel_id).send(content=content, view=view)
content=content, view=view await interaction.response.send_message("Request sent to admins.", ephemeral=True)
)
await interaction.response.send_message(
"Request sent to admins.", ephemeral=True
)
class UsernameRequest(nextcord.ui.View): class UsernameRequest(nextcord.ui.View):
@@ -103,9 +93,7 @@ class UsernameRequest(nextcord.ui.View):
self.new_nickname = new_nickname self.new_nickname = new_nickname
@nextcord.ui.button(label="Approve", style=nextcord.ButtonStyle.green) @nextcord.ui.button(label="Approve", style=nextcord.ButtonStyle.green)
async def approve( async def approve(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
""" """
Approve button for a nickname change request. Changes the target's nickname to self.new_nickname. Approve button for a nickname change request. Changes the target's nickname to self.new_nickname.
Catches an error if the target as a higher role than the bot. Catches an error if the target as a higher role than the bot.
@@ -119,10 +107,7 @@ class UsernameRequest(nextcord.ui.View):
if user is not None: if user is not None:
try: try:
await user.edit(nick=self.new_nickname) await user.edit(nick=self.new_nickname)
content = ( content = interaction.message.content + f"\nApproved by <@{interaction.user.id}>."
interaction.message.content
+ f"\nApproved by <@{interaction.user.id}>."
)
await interaction.response.edit_message(content=content, view=None) await interaction.response.edit_message(content=content, view=None)
except nextcord.errors.Forbidden: except nextcord.errors.Forbidden:
await interaction.response.send_message( await interaction.response.send_message(
@@ -133,9 +118,7 @@ class UsernameRequest(nextcord.ui.View):
interaction.message.content interaction.message.content
+ "\n\nFailed. User has too high permissions for bot to change nickname." + "\n\nFailed. User has too high permissions for bot to change nickname."
) )
await interaction.followup.edit_message( await interaction.followup.edit_message(interaction.message.id, content=content, view=None)
interaction.message.id, content=content, view=None
)
else: else:
await interaction.response.edit_message( await interaction.response.edit_message(
content="An error occured while changing the user's nickname.", content="An error occured while changing the user's nickname.",
@@ -168,9 +151,7 @@ class PresenceChange(nextcord.ui.View):
self.presence = presence self.presence = presence
@nextcord.ui.button(label="Approve", style=nextcord.ButtonStyle.green) @nextcord.ui.button(label="Approve", style=nextcord.ButtonStyle.green)
async def approve( async def approve(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
):
""" """
Approve button for a presence add request. Adds the presence to the database. Approve button for a presence add request. Adds the presence to the database.
Removes the view from the interaction message. Removes the view from the interaction message.
@@ -184,9 +165,7 @@ class PresenceChange(nextcord.ui.View):
session.add(Presences(Presence=self.presence)) session.add(Presences(Presence=self.presence))
session.commit() session.commit()
content = ( content = interaction.message.content + f"\nApproved by <@{interaction.user.id}>."
interaction.message.content + f"\nApproved by <@{interaction.user.id}>."
)
await interaction.response.edit_message(content=content, view=None) await interaction.response.edit_message(content=content, view=None)
@nextcord.ui.button(label="Deny", style=nextcord.ButtonStyle.red) @nextcord.ui.button(label="Deny", style=nextcord.ButtonStyle.red)
+8 -24
View File
@@ -30,18 +30,12 @@ class setCog(commands.Cog, name="Set Commands"):
Parent slash command for set. Never called. Parent slash command for set. Never called.
""" """
@set.subcommand( @set.subcommand(description="Sets your birth month and day for the Birthday Fun. Use 0/0 to remove yourself.")
description="Sets your birth month and day for the Birthday Fun. Use 0/0 to remove yourself."
)
async def birthday( async def birthday(
self, self,
interaction: nextcord.Interaction, interaction: nextcord.Interaction,
month: int = nextcord.SlashOption( month: int = nextcord.SlashOption(required=True, min_value=0, max_value=12, description="Your birth month."),
required=True, min_value=0, max_value=12, description="Your birth month." day: int = nextcord.SlashOption(required=True, min_value=0, max_value=31, description="Your birth day."),
),
day: int = nextcord.SlashOption(
required=True, min_value=0, max_value=31, description="Your birth day."
),
): ):
""" """
Sets a user's birthday in the database. Removes on input 0/0. If birthday is today, adds to the birthday_list. Sets a user's birthday in the database. Removes on input 0/0. If birthday is today, adds to the birthday_list.
@@ -56,9 +50,7 @@ class setCog(commands.Cog, name="Set Commands"):
await interaction.response.defer(ephemeral=True) await interaction.response.defer(ephemeral=True)
if month == 0 and day == 0: if month == 0 and day == 0:
stmt = delete(UserBirthday).where( stmt = delete(UserBirthday).where(UserBirthday.UserId == interaction.user.id)
UserBirthday.UserId == interaction.user.id
)
with Session(engine) as session: with Session(engine) as session:
session.execute(stmt) session.execute(stmt)
session.commit() session.commit()
@@ -70,18 +62,14 @@ class setCog(commands.Cog, name="Set Commands"):
try: try:
birthday = datetime(today.year, month, day) birthday = datetime(today.year, month, day)
except ValueError: except ValueError:
await interaction.followup.send( await interaction.followup.send(f"Invalid date: {month}/{day}.", ephemeral=True)
f"Invalid date: {month}/{day}.", ephemeral=True
)
return return
# If the birthday is today, add to birthday_list # If the birthday is today, add to birthday_list
if today.date() == birthday.date(): if today.date() == birthday.date():
birthday_list.append(interaction.user.id) birthday_list.append(interaction.user.id)
new_birthday = UserBirthday( new_birthday = UserBirthday(UserId=interaction.user.id, Birthday=f"{month}/{day}")
UserId=interaction.user.id, Birthday=f"{month}/{day}"
)
with Session(engine) as session: with Session(engine) as session:
try: try:
session.add(new_birthday) session.add(new_birthday)
@@ -89,13 +77,9 @@ class setCog(commands.Cog, name="Set Commands"):
except IntegrityError: except IntegrityError:
# User already has birthday, change it instead. # User already has birthday, change it instead.
session.rollback() session.rollback()
stmt = select(UserBirthday).where( stmt = select(UserBirthday).where(UserBirthday.UserId == interaction.user.id)
UserBirthday.UserId == interaction.user.id
)
new_birthday = session.scalar(stmt) new_birthday = session.scalar(stmt)
new_birthday.Birthday = f"{month}/{day}" new_birthday.Birthday = f"{month}/{day}"
session.commit() session.commit()
await interaction.followup.send( await interaction.followup.send(f"Birthday set to {month}/{day}.", ephemeral=True)
f"Birthday set to {month}/{day}.", ephemeral=True
)
+13 -50
View File
@@ -60,9 +60,7 @@ class ViewCog(commands.Cog, name="View Commands"):
) )
if df.empty: if df.empty:
await interaction.followup.send( await interaction.followup.send(f'Quarter "{quarter_name}" is invalid.', ephemeral=True)
f'Quarter "{quarter_name}" is invalid.', ephemeral=True
)
return return
cycles = df.groupby("Cycle") cycles = df.groupby("Cycle")
@@ -74,32 +72,19 @@ class ViewCog(commands.Cog, name="View Commands"):
non_members = unsorted_all.get_group(False) non_members = unsorted_all.get_group(False)
sorted_members = members.sort_values( sorted_members = members.sort_values(
by="UserId", by="UserId",
key=lambda user_ids: ( key=lambda user_ids: ([interaction.guild.get_member(int(id)).display_name for id in user_ids]),
[
interaction.guild.get_member(int(id)).display_name
for id in user_ids
]
),
) )
sorted_non_members = non_members.sort_values(by="UserId") sorted_non_members = non_members.sort_values(by="UserId")
sorted_all = pd.concat( sorted_all = pd.concat([sorted_members, sorted_non_members], ignore_index=True, sort=False)
[sorted_members, sorted_non_members], ignore_index=True, sort=False
)
for row in sorted_all.itertuples(): for row in sorted_all.itertuples():
userid = row.UserId userid = row.UserId
points = row.Points points = row.Points
discord_member = row.DiscordMember discord_member = row.DiscordMember
content += ( content += f"<@{userid}>: {points}\n" if discord_member else f"{userid}: {points}\n"
f"<@{userid}>: {points}\n"
if discord_member
else f"{userid}: {points}\n"
)
content += "\n" content += "\n"
if len(content) > 2000: if len(content) > 2000:
await interaction.followup.send( await interaction.followup.send("Message length is too long, please select search to limit results.")
"Message length is too long, please select search to limit results."
)
return return
await interaction.followup.send(content=content, ephemeral=True) await interaction.followup.send(content=content, ephemeral=True)
@@ -128,21 +113,13 @@ class ViewCog(commands.Cog, name="View Commands"):
presences = session.scalars(stmt) presences = session.scalars(stmt)
if search: if search:
message = "\n".join( message = "\n".join([presence for presence in presences if search.lower() in presence.lower()])
[
presence
for presence in presences
if search.lower() in presence.lower()
]
)
else: else:
message = "\n".join(list(presences)) message = "\n".join(list(presences))
await interaction.followup.send(content=message, ephemeral=True) await interaction.followup.send(content=message, ephemeral=True)
@view.subcommand( @view.subcommand(description="Shows all voters and who they voted for in a given election.")
description="Shows all voters and who they voted for in a given election."
)
async def votes( async def votes(
self, self,
interaction: nextcord.Interaction, interaction: nextcord.Interaction,
@@ -165,18 +142,12 @@ class ViewCog(commands.Cog, name="View Commands"):
election_name (str): Is SlashOption. The name of the election to view votes for. election_name (str): Is SlashOption. The name of the election to view votes for.
""" """
stmt = ( stmt = select(Votes).where(Votes.ElectionCycle == election_name).where(Votes.Type == election_type)
select(Votes)
.where(Votes.ElectionCycle == election_name)
.where(Votes.Type == election_type)
)
with Session(engine) as session: with Session(engine) as session:
# Check if election exists. # Check if election exists.
if session.scalar(stmt) is None: if session.scalar(stmt) is None:
await interaction.response.send_message( await interaction.response.send_message(f"Invalid election: {election_name}.", ephemeral=True)
f"Invalid election: {election_name}.", ephemeral=True
)
return return
votes = session.scalars(stmt) votes = session.scalars(stmt)
@@ -191,9 +162,7 @@ class ViewCog(commands.Cog, name="View Commands"):
await interaction.response.send_message(content=content, ephemeral=True) await interaction.response.send_message(content=content, ephemeral=True)
@votes.on_autocomplete("election_name") @votes.on_autocomplete("election_name")
async def election_autocomplete( async def election_autocomplete(self, interaction: nextcord.Interaction, election_name: str):
self, interaction: nextcord.Interaction, election_name: str
):
""" """
Collects all elections that start with the election string. Collects all elections that start with the election string.
@@ -212,16 +181,12 @@ class ViewCog(commands.Cog, name="View Commands"):
return return
autofilled_elections: "list[str]" = [ autofilled_elections: "list[str]" = [
election election for election in elections if election.lower().startswith(election_name.lower())
for election in elections
if election.lower().startswith(election_name.lower())
] ]
await interaction.response.send_autocomplete(autofilled_elections[:25]) await interaction.response.send_autocomplete(autofilled_elections[:25])
@event_points.on_autocomplete("quarter_name") @event_points.on_autocomplete("quarter_name")
async def event_points_autocomplete( async def event_points_autocomplete(self, interaction: nextcord.Interaction, quarter_name: str):
self, interaction: nextcord.Interaction, quarter_name: str
):
""" """
Collects all elections that start with the election string. Collects all elections that start with the election string.
@@ -240,8 +205,6 @@ class ViewCog(commands.Cog, name="View Commands"):
return return
autofilled_quarters: "list[str]" = [ autofilled_quarters: "list[str]" = [
quarter quarter for quarter in quarters if quarter.lower().startswith(quarter_name.lower())
for quarter in quarters
if quarter.lower().startswith(quarter_name.lower())
] ]
await interaction.response.send_autocomplete(autofilled_quarters[:25]) await interaction.response.send_autocomplete(autofilled_quarters[:25])
+3 -9
View File
@@ -17,9 +17,7 @@ class BotPresence(commands.Cog, name="Bot Presence"):
self.bot = bot self.bot = bot
@commands.Cog.listener() @commands.Cog.listener()
async def on_guild_join( async def on_guild_join(self, guild: nextcord.Guild): # pylint: disable=unused-argument
self, guild: nextcord.Guild
): # pylint: disable=unused-argument
"""Listener for Guild Join. Updated presence on guild join.""" """Listener for Guild Join. Updated presence on guild join."""
await self.change_presence() await self.change_presence()
@@ -39,10 +37,6 @@ class BotPresence(commands.Cog, name="Bot Presence"):
"""Randomly chooses a presence and updates bot's presence.""" """Randomly chooses a presence and updates bot's presence."""
with Session(engine) as session: with Session(engine) as session:
presence = session.scalar( presence = session.scalar(select(Presences.Presence).order_by(func.random()))
select(Presences.Presence).order_by(func.random())
)
await self.bot.change_presence( await self.bot.change_presence(activity=nextcord.CustomActivity(name="Custom Status", state=presence))
activity=nextcord.CustomActivity(name="Custom Status", state=presence)
)
+2 -6
View File
@@ -111,14 +111,10 @@ class DailyLoop(commands.Cog, name="Daily Loop"):
today = datetime.today() today = datetime.today()
guild: nextcord.Guild = self.bot.get_guild(self.bot.config.params.guild_id) guild: nextcord.Guild = self.bot.get_guild(self.bot.config.params.guild_id)
announce_channel: nextcord.TextChannel = guild.get_channel( announce_channel: nextcord.TextChannel = guild.get_channel(self.bot.config.params.general_channel_id)
self.bot.config.params.general_channel_id
)
cakedays: list[nextcord.Member] = [ cakedays: list[nextcord.Member] = [
human human for human in guild.humans if human.joined_at.month == today.month and human.joined_at.day == today.day
for human in guild.humans
if human.joined_at.month == today.month and human.joined_at.day == today.day
] ]
for member in cakedays: for member in cakedays:
+1 -3
View File
@@ -39,7 +39,5 @@ async def birthday_action(message: nextcord.Message) -> None:
message (nextcord.Message): The message to check for a birthday person. message (nextcord.Message): The message to check for a birthday person.
""" """
if message.author.id in birthday_list or bool( if message.author.id in birthday_list or bool(set(message.raw_mentions) & set(birthday_list)):
set(message.raw_mentions) & set(birthday_list)
):
await message.add_reaction("🎂") await message.add_reaction("🎂")
+1 -3
View File
@@ -22,9 +22,7 @@ birthday_list: list[int] = []
logger = logging.getLogger("nextcord") logger = logging.getLogger("nextcord")
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8", mode="w") handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8", mode="w")
handler.setFormatter( handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s")
)
logger.addHandler(handler) logger.addHandler(handler)
+20 -2
View File
@@ -63,8 +63,26 @@ target-version = "py38"
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default. # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or # Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default. # McCabe complexity (`C901`) by default.
select = ["E4", "E7", "E9", "F", "D100", "D1"] select = ["ALL"]
ignore = ["D107"] ignore = [
"D107",
"W191",
"E111",
"E114",
"E117",
"D203",
"D206",
"D212",
"D300",
"Q000",
"Q001",
"Q002",
"Q003",
"COM812",
"COM819",
"ISC001",
"ISC002",
]
# Allow fix for all enabled rules (when `--fix`) is provided. # Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"] fixable = ["ALL"]
+20 -75
View File
@@ -149,9 +149,7 @@ def build_votes_str(config: DakinyConfig, guild: nextcord.Guild) -> str:
election_name = get_election_name(config) election_name = get_election_name(config)
with Session(engine) as session: with Session(engine) as session:
stmt = select(CouncilMembers).where( stmt = select(CouncilMembers).where(CouncilMembers.ElectionCycle == election_name)
CouncilMembers.ElectionCycle == election_name
)
for nominee in sorted( for nominee in sorted(
session.scalars(stmt), session.scalars(stmt),
@@ -159,11 +157,7 @@ def build_votes_str(config: DakinyConfig, guild: nextcord.Guild) -> str:
): ):
votes[nominee.MemberId] = 0 votes[nominee.MemberId] = 0
stmt = ( stmt = select(Votes).where(Votes.ElectionCycle == election_name).where(Votes.Type == VoteType.COUNCIL)
select(Votes)
.where(Votes.ElectionCycle == election_name)
.where(Votes.Type == VoteType.COUNCIL)
)
for vote in session.scalars(stmt): for vote in session.scalars(stmt):
if vote.VotedForId is not None: if vote.VotedForId is not None:
@@ -205,11 +199,7 @@ def build_highcouncil_votes_str(config: DakinyConfig, guild: nextcord.Guild) ->
): ):
cl_votes[nominee.MemberId] = 0 cl_votes[nominee.MemberId] = 0
stmt = ( stmt = select(Votes).where(Votes.ElectionCycle == election_name).where(Votes.Type == VoteType.CLANLEADER)
select(Votes)
.where(Votes.ElectionCycle == election_name)
.where(Votes.Type == VoteType.CLANLEADER)
)
for vote in session.scalars(stmt): for vote in session.scalars(stmt):
if vote.VotedForId is not None: if vote.VotedForId is not None:
@@ -227,11 +217,7 @@ def build_highcouncil_votes_str(config: DakinyConfig, guild: nextcord.Guild) ->
): ):
dm_votes[nominee.MemberId] = 0 dm_votes[nominee.MemberId] = 0
stmt = ( stmt = select(Votes).where(Votes.ElectionCycle == election_name).where(Votes.Type == VoteType.DISCORDMANAGER)
select(Votes)
.where(Votes.ElectionCycle == election_name)
.where(Votes.Type == VoteType.DISCORDMANAGER)
)
for vote in session.scalars(stmt): for vote in session.scalars(stmt):
if vote.VotedForId is not None: if vote.VotedForId is not None:
@@ -318,9 +304,7 @@ def decorate_dm_nomination(user_id: int, speech: str) -> str:
return msg return msg
def record_event_points( def record_event_points(config: DakinyConfig, users: Sequence[str], is_member: bool, add_points: int):
config: DakinyConfig, users: Sequence[str], is_member: bool, add_points: int
):
""" """
Adds event points to all users listed. Checks if they don't exist in order to make a new entry, otherwise Adds event 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.
@@ -343,9 +327,7 @@ def record_event_points(
points = session.scalar(stmt) points = session.scalar(stmt)
if points is None: if points is None:
add_points = get_allowed_points( add_points = get_allowed_points(session, config.params.event_points_weekly_limit, user, add_points)
session, config.params.event_points_weekly_limit, user, add_points
)
new_points = ParticipationPoints( new_points = ParticipationPoints(
Cycle=quarter_name, Cycle=quarter_name,
UserId=user, UserId=user,
@@ -354,17 +336,13 @@ def record_event_points(
) )
session.add(new_points) session.add(new_points)
else: else:
add_points = get_allowed_points( add_points = get_allowed_points(session, config.params.event_points_weekly_limit, user, add_points)
session, config.params.event_points_weekly_limit, user, add_points
)
points.Points += add_points points.Points += add_points
session.commit() session.commit()
def get_allowed_points( def get_allowed_points(session: Session, points_limit: int, user: str, points: int) -> int:
session: Session, points_limit: int, user: str, points: int
) -> int:
""" """
Gets the maximum number of points a user can be given. Searches how many points they have been given Gets the maximum number of points a user can be given. Searches how many points they have been given
this week and subtracts that from the weekly limit. If under, returns up to "points" number of points (will not this week and subtracts that from the weekly limit. If under, returns up to "points" number of points (will not
@@ -380,14 +358,8 @@ def get_allowed_points(
int: how many points are allowed to be given to the user. int: how many points are allowed to be given to the user.
""" """
# check for limit # check for limit
this_week = ( this_week = f"{datetime.today().isocalendar().year}-{datetime.today().isocalendar().week}"
f"{datetime.today().isocalendar().year}-{datetime.today().isocalendar().week}" stmt = select(EventPointsLimit).where(EventPointsLimit.UserId == user).where(EventPointsLimit.Week == this_week)
)
stmt = (
select(EventPointsLimit)
.where(EventPointsLimit.UserId == user)
.where(EventPointsLimit.Week == this_week)
)
# if under limit, can add up to however many points would make the current limit equal to the # if under limit, can add up to however many points would make the current limit equal to the
# allowed limit. # allowed limit.
@@ -424,11 +396,7 @@ async def update_clan_messages(guild: nextcord.Guild, channel_updates: Sequence[
channel_updates: (Sequence[str]): a sequence of the channels to update. channel_updates: (Sequence[str]): a sequence of the channels to update.
""" """
dirs = [ dirs = [dir_name for dir_name in channel_updates if os.path.isdir(f"{MESSAGES_DIR}/{dir_name}")]
dir_name
for dir_name in channel_updates
if os.path.isdir(f"{MESSAGES_DIR}/{dir_name}")
]
with Session(engine) as session: with Session(engine) as session:
for dir_name in dirs: for dir_name in dirs:
@@ -443,14 +411,10 @@ async def update_clan_messages(guild: nextcord.Guild, channel_updates: Sequence[
message_name = f"{dir_name}/{file_name}" message_name = f"{dir_name}/{file_name}"
file_path = f"{dir_path}/{file_name}" file_path = f"{dir_path}/{file_name}"
with open(file_path, "r", encoding="utf8") as reader: with open(file_path, "r", encoding="utf8") as reader:
await edit_clan_message( await edit_clan_message(session, channel, message_name, reader.read(2000))
session, channel, message_name, reader.read(2000)
)
async def get_clan_message_channel( async def get_clan_message_channel(session: Session, channel_name: str, guild: nextcord.Guild) -> nextcord.TextChannel:
session: Session, channel_name: str, guild: nextcord.Guild
) -> nextcord.TextChannel:
""" """
Used to obtain a channel from the guild object. Searches database for an id to get the channel. If that is not Used to obtain a channel from the guild object. Searches database for an id to get the channel. If that is not
found, then searches through all channels in the guild to find one with a matching name. If that also doesn't found, then searches through all channels in the guild to find one with a matching name. If that also doesn't
@@ -472,10 +436,7 @@ async def get_clan_message_channel(
# channel is not tracked. see if it exists # channel is not tracked. see if it exists
channels = await guild.fetch_channels() channels = await guild.fetch_channels()
for channel in channels: for channel in channels:
if ( if channel.name == channel_name and channel.__class__ is nextcord.TextChannel:
channel.name == channel_name
and channel.__class__ is nextcord.TextChannel
):
ret_channel = channel ret_channel = channel
if ret_channel is None: if ret_channel is None:
@@ -499,11 +460,7 @@ async def get_clan_message_channel(
channel_name, channel_name,
reason="Creating channel as required for by design of Dakiny-Messages repo.", reason="Creating channel as required for by design of Dakiny-Messages repo.",
) )
stmt = ( stmt = update(Messages).where(Messages.Path == channel_name).values(Id=ret_channel.id)
update(Messages)
.where(Messages.Path == channel_name)
.values(Id=ret_channel.id)
)
session.execute(stmt) session.execute(stmt)
session.commit() session.commit()
return ret_channel return ret_channel
@@ -540,9 +497,7 @@ async def edit_clan_message(
await msg.edit(message_content) await msg.edit(message_content)
except nextcord.NotFound: except nextcord.NotFound:
msg = await channel.send(message_content) msg = await channel.send(message_content)
stmt = ( stmt = update(Messages).where(Messages.Path == message_name).values(Id=msg.id)
update(Messages).where(Messages.Path == message_name).values(Id=msg.id)
)
session.execute(stmt) session.execute(stmt)
session.commit() session.commit()
@@ -555,9 +510,7 @@ async def edit_clan_council_info(guild: nextcord.Guild, config: DakinyConfig):
guild (nextcord.Guild): Guild object that to use to get channel. guild (nextcord.Guild): Guild object that to use to get channel.
config (DakinyConfig): Configs config (DakinyConfig): Configs
""" """
clan_info_channel: nextcord.TextChannel = await guild.fetch_channel( clan_info_channel: nextcord.TextChannel = await guild.fetch_channel(config.params.clan_info_channel_id)
config.params.clan_info_channel_id
)
election = get_election_name(config) election = get_election_name(config)
with Session(engine) as session: with Session(engine) as session:
@@ -579,17 +532,11 @@ async def edit_clan_council_info(guild: nextcord.Guild, config: DakinyConfig):
.where(CouncilMembers.Elected == true()) .where(CouncilMembers.Elected == true())
) )
council_members_strs = [ council_members_strs = [f"<@{id}>" for id in session.scalars(stmt) if id not in (discord_manager, clan_leader)]
f"<@{id}>"
for id in session.scalars(stmt)
if id not in (discord_manager, clan_leader)
]
quarter = get_quarter_name(config) quarter = get_quarter_name(config)
with open( with open(f"{TEMPLATES_DIR}/council_members.txt", mode="r", encoding="utf8") as file:
f"{TEMPLATES_DIR}/council_members.txt", mode="r", encoding="utf8"
) as file:
message = file.read() message = file.read()
message = message.format( message = message.format(
quarter=quarter, quarter=quarter,
@@ -598,6 +545,4 @@ async def edit_clan_council_info(guild: nextcord.Guild, config: DakinyConfig):
discord_manager=discord_manager, discord_manager=discord_manager,
) )
await edit_clan_message( await edit_clan_message(session, clan_info_channel, "council_members.txt", message)
session, clan_info_channel, "council_members.txt", message
)