Skip to content

Commit 06d4d55

Browse files
authored
Merge pull request #29 from crackhex/setname
Setname and setteamname overhaul + other fixes/improvements
2 parents dcae2bb + a3332b6 commit 06d4d55

13 files changed

Lines changed: 187 additions & 162 deletions

File tree

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@
55
*.pyc
66
.env
77
/venv
8-
downloads/*
8+
downloads/*
9+
aliases.csv

api/db_classes.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ class Tasks(Base):
4242

4343
class Submissions(Base):
4444
__tablename__ = "submissions"
45-
user_id = Column('user_id', Integer, primary_key=True)
45+
index = Column('index', Integer, autoincrement=True, primary_key=True)
46+
user_id = Column('user_id', Integer)
4647
task = Column('task', Integer)
4748
name = Column('name', String)
4849
url = Column('url', String)

api/submissions.py

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,44 @@ async def update_submission_list(last_message, id, name):
161161
return await last_message.edit(content=new_content)
162162

163163

164+
async def generate_submission_list(self):
165+
""" Edits the submission list in the submission channel.
166+
Takes bot (self) as an argument -- so that the bot may retrieve the channel & message.
167+
"""
168+
submission_channel = await get_submission_channel(DEFAULT)
169+
channel = self.bot.get_channel(submission_channel)
170+
async for message in channel.history(limit=3):
171+
# Check if the message was sent by the bot
172+
if message.author == self.bot.user:
173+
message_to_edit = message
174+
175+
176+
async with get_session() as session:
177+
178+
active_task = (await session.scalars(select(Submissions.task))).first()
179+
submissions = (await session.scalars(select(Submissions).where(Submissions.task == active_task)))
180+
formatted_submissions = "**__Current Submissions:__**"
181+
182+
# Update submission list for a solo submission
183+
for submission in submissions:
184+
if not await is_in_team(submission.user_id):
185+
formatted_submissions += f"\n{submission.index}. {await get_display_name(submission.user_id)} ||<@{submission.user_id}>||"
186+
187+
188+
# Generate submission list for a team submission
189+
else:
190+
ids = await get_team_ids(submission.user_id)
191+
members = await get_team_members(ids)
192+
team_name = await get_team_name(submission.user_id)
193+
mentions = ' '.join([f'<@{user_id}>' for user_id in ids])
194+
195+
formatted_submissions += (
196+
f"\n{submission.index}. {team_name} ({' & '.join(members)}) ||{mentions}||"
197+
)
198+
199+
return await message_to_edit.edit(content=formatted_submissions)
200+
201+
164202

165203
async def handle_submissions(message, self):
166204
author = message.author
@@ -197,16 +235,17 @@ async def handle_submissions(message, self):
197235
author_id = await get_leader(author_id)
198236
author_display_name = await get_display_name(author_id)
199237

238+
# New entry to the list in #submissions
200239
if last_message:
201240

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

205244
await update_submission_list(last_message, author_id, author_display_name)
206245

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

212251
##################################################################

api/utils.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
from urllib.parse import urlparse
66
from discord.ext import commands
77
from sqlalchemy import select, insert, update, inspect, or_
8-
from api.db_classes import Money, Tasks, Teams, HostRole, SubmitterRole, get_session, TasksChannel, AnnouncementsChannel
8+
from api.db_classes import Money, Tasks, Teams, HostRole, SubmitterRole, get_session, TasksChannel, \
9+
AnnouncementsChannel
910
from dotenv import load_dotenv
1011

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

commands/db/admin/setname.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import discord
2+
from discord.ext import commands
3+
from api.db_classes import Userbase, get_session
4+
from api.submissions import get_submission_channel, generate_submission_list
5+
from sqlalchemy import select, update
6+
import os
7+
from dotenv import load_dotenv
8+
9+
load_dotenv()
10+
DEFAULT = os.getenv('DEFAULT')
11+
12+
13+
14+
class Setname(commands.Cog):
15+
def __init__(self, bot) -> None:
16+
self.bot = bot
17+
18+
@commands.hybrid_command(name="setname", description="Set your displayed name in the submission list",
19+
with_app_command=True)
20+
@commands.has_permissions(administrator=True)
21+
async def command(self, ctx, user: discord.Member, *, new_name: commands.clean_content):
22+
23+
if '@' in new_name:
24+
return await ctx.reply("You may not use @ in your name.")
25+
26+
if len(new_name) > 120:
27+
return await ctx.reply("Your name is too long!")
28+
29+
# Gets his old display_name
30+
async with get_session() as session:
31+
32+
user_id = user.id
33+
34+
old_display_name = (
35+
await session.scalars(select(Userbase.display_name).where(Userbase.user_id == user_id))).first()
36+
37+
if old_display_name is None:
38+
return await ctx.send("This person has never submitted. Please submit first!")
39+
40+
else:
41+
# Detect illegal name change (2 identical names)
42+
if (await session.scalars(select(Userbase.display_name).where(Userbase.display_name == new_name))).first():
43+
return await ctx.reply("The name is already in use by another user.")
44+
45+
# Update name in database
46+
stmt = update(Userbase).values(display_name=new_name).where(Userbase.user_id == user_id)
47+
await session.execute(stmt)
48+
await session.commit()
49+
50+
# Update submission list
51+
await generate_submission_list(self)
52+
53+
await ctx.send(f"Sucessfully set <@{user_id}>'s name to **{new_name}**.")
54+
55+
56+
async def setup(bot) -> None:
57+
await bot.add_cog(Setname(bot))

commands/db/host/deletesubmission.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from discord.ext import commands
33
from api.utils import has_host_role
44
from api.db_classes import Submissions, get_session, Tasks
5-
from api.submissions import get_submission_channel, get_display_name
5+
from api.submissions import get_submission_channel, get_display_name, generate_submission_list
66
from sqlalchemy import select, delete
77
import os
88
from dotenv import load_dotenv
@@ -11,25 +11,19 @@
1111
DEFAULT = os.getenv('DEFAULT')
1212

1313

14-
async def remove_from_submission_list(self, name_to_remove):
15-
submission_channel = await get_submission_channel(DEFAULT)
16-
channel = self.bot.get_channel(submission_channel)
14+
async def reorder_primary_keys():
15+
async with get_session() as session:
1716

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

24-
for line in lines[1:]:
25-
if name_to_remove not in line:
26-
new_lines.append(line)
27-
28-
new_content = '\n'.join(new_lines)
29-
if new_content != message.content:
30-
await message.edit(content=new_content)
31-
break # Stop after finding the last bot message
22+
# Reassign indexes
23+
for idx, submission in enumerate(submissions, start=1):
24+
submission.index = idx
3225

26+
await session.commit()
3327

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

57-
name = await get_display_name(user.id)
58-
await remove_from_submission_list(self, name)
51+
52+
# Re-arrange the indexes in the submission table so that they are no gaps between numbers
53+
await reorder_primary_keys()
54+
55+
# Update submission list
56+
await generate_submission_list(self)
5957

6058

6159
await ctx.send(f"{user.display_name}'s submission has been deleted.")

commands/db/host/submit.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from discord.ext import commands
22
import discord
33
from api.utils import is_task_currently_running, readable_to_float, has_host_role
4-
from api.submissions import first_time_submission
4+
from api.submissions import first_time_submission, generate_submission_list
55
from api.mkwii.mkwii_utils import get_lap_time, get_character, get_vehicle
66
from api.db_classes import Submissions, get_session
77
from sqlalchemy import insert, update
@@ -64,6 +64,8 @@ async def submit(self, ctx, user: discord.Member, file: discord.Attachment):
6464
await session.execute(query)
6565
await session.commit()
6666

67+
await generate_submission_list(self)
68+
6769
await ctx.reply(f"A submission has been added for {user.name}!")
6870

6971

commands/db/setname.py

Lines changed: 0 additions & 88 deletions
This file was deleted.

commands/db/team/collab.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,18 @@ async def user_response(self, ctx, author_id, user, accepted):
247247
user4=accepted_users[2] if len(accepted_users) > 2 else None
248248
)
249249
)
250+
251+
# Add any new users to Userbase db
252+
for id in accepted_users:
253+
if await new_competitor(id):
254+
await session.execute(
255+
insert(Userbase).values(
256+
user_id=id,
257+
user=self.bot.get_user(id).name,
258+
display_name=self.bot.get_user(id).display_name
259+
)
260+
)
261+
250262
await session.commit()
251263

252264
await ctx.send(f"<@{author_id}> is now collaborating with {user_mentions}!")

commands/db/team/hostdissolve.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,21 @@
33
from api.utils import has_host_role
44
from sqlalchemy import select, delete
55

6+
async def reorder_primary_keys():
7+
async with get_session() as session:
8+
9+
# Retrieve the teams
10+
query = select(Teams).order_by(Teams.index)
11+
result = await session.execute(query)
12+
teams = result.scalars().all()
13+
14+
# Reassign indexes
15+
for idx, team in enumerate(teams, start=1):
16+
team.index = idx
17+
18+
await session.commit()
19+
20+
621
class HostDissolve(commands.Cog):
722
def __init__(self, bot):
823
self.bot = bot
@@ -21,6 +36,9 @@ async def hostdissolve(self, ctx, index: int):
2136

2237
await session.execute(delete(Teams).where(Teams.index == index))
2338
await session.commit()
39+
40+
await reorder_primary_keys()
41+
2442
await ctx.send("The team has been deleted.")
2543

2644

0 commit comments

Comments
 (0)