Skip to content

Commit

Permalink
Merge pull request #29 from crackhex/setname
Browse files Browse the repository at this point in the history
Setname and setteamname overhaul + other fixes/improvements
  • Loading branch information
kierio04 authored Dec 18, 2024
2 parents dcae2bb + a3332b6 commit 06d4d55
Show file tree
Hide file tree
Showing 13 changed files with 187 additions and 162 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
*.pyc
.env
/venv
downloads/*
downloads/*
aliases.csv
3 changes: 2 additions & 1 deletion api/db_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ class Tasks(Base):

class Submissions(Base):
__tablename__ = "submissions"
user_id = Column('user_id', Integer, primary_key=True)
index = Column('index', Integer, autoincrement=True, primary_key=True)
user_id = Column('user_id', Integer)
task = Column('task', Integer)
name = Column('name', String)
url = Column('url', String)
Expand Down
43 changes: 41 additions & 2 deletions api/submissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,44 @@ async def update_submission_list(last_message, id, name):
return await last_message.edit(content=new_content)


async def generate_submission_list(self):
""" Edits the submission list in the submission channel.
Takes bot (self) as an argument -- so that the bot may retrieve the channel & message.
"""
submission_channel = await get_submission_channel(DEFAULT)
channel = self.bot.get_channel(submission_channel)
async for message in channel.history(limit=3):
# Check if the message was sent by the bot
if message.author == self.bot.user:
message_to_edit = message


async with get_session() as session:

active_task = (await session.scalars(select(Submissions.task))).first()
submissions = (await session.scalars(select(Submissions).where(Submissions.task == active_task)))
formatted_submissions = "**__Current Submissions:__**"

# Update submission list for a solo submission
for submission in submissions:
if not await is_in_team(submission.user_id):
formatted_submissions += f"\n{submission.index}. {await get_display_name(submission.user_id)} ||<@{submission.user_id}>||"


# Generate submission list for a team submission
else:
ids = await get_team_ids(submission.user_id)
members = await get_team_members(ids)
team_name = await get_team_name(submission.user_id)
mentions = ' '.join([f'<@{user_id}>' for user_id in ids])

formatted_submissions += (
f"\n{submission.index}. {team_name} ({' & '.join(members)}) ||{mentions}||"
)

return await message_to_edit.edit(content=formatted_submissions)



async def handle_submissions(message, self):
author = message.author
Expand Down Expand Up @@ -197,16 +235,17 @@ async def handle_submissions(message, self):
author_id = await get_leader(author_id)
author_display_name = await get_display_name(author_id)

# New entry to the list in #submissions
if last_message:

# Add a new line only if it's a new user ID submitting
if await first_time_submission(author_id):

await update_submission_list(last_message, author_id, author_display_name)


else:
# There are no submissions (brand-new task); send a message on the first submission -> this is for blank
# channels
# There are no submissions (brand-new task); send a message on the first submission
await post_submission_list(channel, author_id, author_display_name)

##################################################################
Expand Down
7 changes: 5 additions & 2 deletions api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from urllib.parse import urlparse
from discord.ext import commands
from sqlalchemy import select, insert, update, inspect, or_
from api.db_classes import Money, Tasks, Teams, HostRole, SubmitterRole, get_session, TasksChannel, AnnouncementsChannel
from api.db_classes import Money, Tasks, Teams, HostRole, SubmitterRole, get_session, TasksChannel, \
AnnouncementsChannel
from dotenv import load_dotenv

load_dotenv()
Expand Down Expand Up @@ -150,7 +151,6 @@ def float_to_readable(seconds):
async def is_task_currently_running():
"""Check if a task is currently running. Returns a list with the parameters of active task, if so."""
# Is a task running?
# Does this need to be a function even?
async with get_session() as session:
active = (await session.execute(select(Tasks.task, Tasks.year, Tasks.is_active, Tasks.team_size,
Tasks.speed_task, Tasks.multiple_tracks, Tasks.deadline, Tasks.is_released)
Expand Down Expand Up @@ -220,3 +220,6 @@ def hash_file(filename: str):
"""
with open(filename, 'rb', buffering=0) as f:
return hashlib.file_digest(f, 'sha256')



57 changes: 57 additions & 0 deletions commands/db/admin/setname.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import discord
from discord.ext import commands
from api.db_classes import Userbase, get_session
from api.submissions import get_submission_channel, generate_submission_list
from sqlalchemy import select, update
import os
from dotenv import load_dotenv

load_dotenv()
DEFAULT = os.getenv('DEFAULT')



class Setname(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot

@commands.hybrid_command(name="setname", description="Set your displayed name in the submission list",
with_app_command=True)
@commands.has_permissions(administrator=True)
async def command(self, ctx, user: discord.Member, *, new_name: commands.clean_content):

if '@' in new_name:
return await ctx.reply("You may not use @ in your name.")

if len(new_name) > 120:
return await ctx.reply("Your name is too long!")

# Gets his old display_name
async with get_session() as session:

user_id = user.id

old_display_name = (
await session.scalars(select(Userbase.display_name).where(Userbase.user_id == user_id))).first()

if old_display_name is None:
return await ctx.send("This person has never submitted. Please submit first!")

else:
# Detect illegal name change (2 identical names)
if (await session.scalars(select(Userbase.display_name).where(Userbase.display_name == new_name))).first():
return await ctx.reply("The name is already in use by another user.")

# Update name in database
stmt = update(Userbase).values(display_name=new_name).where(Userbase.user_id == user_id)
await session.execute(stmt)
await session.commit()

# Update submission list
await generate_submission_list(self)

await ctx.send(f"Sucessfully set <@{user_id}>'s name to **{new_name}**.")


async def setup(bot) -> None:
await bot.add_cog(Setname(bot))
36 changes: 17 additions & 19 deletions commands/db/host/deletesubmission.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from discord.ext import commands
from api.utils import has_host_role
from api.db_classes import Submissions, get_session, Tasks
from api.submissions import get_submission_channel, get_display_name
from api.submissions import get_submission_channel, get_display_name, generate_submission_list
from sqlalchemy import select, delete
import os
from dotenv import load_dotenv
Expand All @@ -11,25 +11,19 @@
DEFAULT = os.getenv('DEFAULT')


async def remove_from_submission_list(self, name_to_remove):
submission_channel = await get_submission_channel(DEFAULT)
channel = self.bot.get_channel(submission_channel)
async def reorder_primary_keys():
async with get_session() as session:

async for message in channel.history(limit=3):
# Check if the message was sent by the bot
if message.author == self.bot.user:
lines = message.content.split('\n')
new_lines = [lines[0]] # Preserve the first line as is ("Current submissions")
# Retrieve the submissions
query = select(Submissions).order_by(Submissions.index)
result = await session.execute(query)
submissions = result.scalars().all()

for line in lines[1:]:
if name_to_remove not in line:
new_lines.append(line)

new_content = '\n'.join(new_lines)
if new_content != message.content:
await message.edit(content=new_content)
break # Stop after finding the last bot message
# Reassign indexes
for idx, submission in enumerate(submissions, start=1):
submission.index = idx

await session.commit()

class DeleteSubmission(commands.Cog):
def __init__(self, bot) -> None:
Expand All @@ -54,8 +48,12 @@ async def command(self, ctx, user: discord.Member):
await session.execute(delete(Submissions).where(Submissions.user_id == user.id))
await session.commit()

name = await get_display_name(user.id)
await remove_from_submission_list(self, name)

# Re-arrange the indexes in the submission table so that they are no gaps between numbers
await reorder_primary_keys()

# Update submission list
await generate_submission_list(self)


await ctx.send(f"{user.display_name}'s submission has been deleted.")
Expand Down
4 changes: 3 additions & 1 deletion commands/db/host/submit.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from discord.ext import commands
import discord
from api.utils import is_task_currently_running, readable_to_float, has_host_role
from api.submissions import first_time_submission
from api.submissions import first_time_submission, generate_submission_list
from api.mkwii.mkwii_utils import get_lap_time, get_character, get_vehicle
from api.db_classes import Submissions, get_session
from sqlalchemy import insert, update
Expand Down Expand Up @@ -64,6 +64,8 @@ async def submit(self, ctx, user: discord.Member, file: discord.Attachment):
await session.execute(query)
await session.commit()

await generate_submission_list(self)

await ctx.reply(f"A submission has been added for {user.name}!")


Expand Down
88 changes: 0 additions & 88 deletions commands/db/setname.py

This file was deleted.

12 changes: 12 additions & 0 deletions commands/db/team/collab.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,18 @@ async def user_response(self, ctx, author_id, user, accepted):
user4=accepted_users[2] if len(accepted_users) > 2 else None
)
)

# Add any new users to Userbase db
for id in accepted_users:
if await new_competitor(id):
await session.execute(
insert(Userbase).values(
user_id=id,
user=self.bot.get_user(id).name,
display_name=self.bot.get_user(id).display_name
)
)

await session.commit()

await ctx.send(f"<@{author_id}> is now collaborating with {user_mentions}!")
Expand Down
18 changes: 18 additions & 0 deletions commands/db/team/hostdissolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,21 @@
from api.utils import has_host_role
from sqlalchemy import select, delete

async def reorder_primary_keys():
async with get_session() as session:

# Retrieve the teams
query = select(Teams).order_by(Teams.index)
result = await session.execute(query)
teams = result.scalars().all()

# Reassign indexes
for idx, team in enumerate(teams, start=1):
team.index = idx

await session.commit()


class HostDissolve(commands.Cog):
def __init__(self, bot):
self.bot = bot
Expand All @@ -21,6 +36,9 @@ async def hostdissolve(self, ctx, index: int):

await session.execute(delete(Teams).where(Teams.index == index))
await session.commit()

await reorder_primary_keys()

await ctx.send("The team has been deleted.")


Expand Down
Loading

0 comments on commit 06d4d55

Please sign in to comment.