From fccf4efa1f1be5474aaaa1658bdec3be5c2f1145 Mon Sep 17 00:00:00 2001 From: Stijn De Clercq Date: Mon, 29 Nov 2021 21:37:04 +0100 Subject: [PATCH] Add commands for deadlines --- .gitignore | 1 + cogs/events.py | 4 ++ cogs/school.py | 10 +++- cogs/slash/db_slash.py | 87 +++++++++++++++++++++++++++++++++++ cogs/slash/school_slash.py | 6 +++ data/embeds/deadlines.py | 68 +++++++++++++++++++++++++++ files/default/deadlines.json | 1 + files/help.json | 2 + functions/stringFormatters.py | 5 ++ startup/init_files.py | 2 +- 10 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 cogs/slash/db_slash.py create mode 100644 data/embeds/deadlines.py create mode 100644 files/default/deadlines.json diff --git a/.gitignore b/.gitignore index 9b3c80f..fb266ea 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ files/lastTasks.json files/c4.json +files/deadlines.json files/hangman.json files/stats.json files/lost.json diff --git a/cogs/events.py b/cogs/events.py index 28be9c5..70809b1 100644 --- a/cogs/events.py +++ b/cogs/events.py @@ -5,6 +5,7 @@ from data.snipe import Snipe, Action, should_snipe import datetime import discord from discord.ext import commands +from dislash.application_commands.errors import InteractionCheckFailure from functions import checks, easterEggResponses, stringFormatters from functions.database import stats, muttn, custom_commands, commands as command_stats import pytz @@ -136,6 +137,9 @@ class Events(commands.Cog): if self.client.user.id != int(constants.didierId): raise err + if isinstance(err, InteractionCheckFailure): + return await interaction.reply("Je hebt geen toegang tot dit commando.", ephemeral=True) + usage = stringFormatters.format_slash_command_usage(interaction) await self.sendErrorEmbed(err, "Slash Command", usage) diff --git a/cogs/school.py b/cogs/school.py index a8c00cd..4eefb70 100644 --- a/cogs/school.py +++ b/cogs/school.py @@ -1,12 +1,13 @@ from data import schedule +from data.embeds.deadlines import Deadlines from data.embeds.food import Menu from decorators import help import discord from discord.ext import commands from enums.help_categories import Category -from functions import config, eten, les +from functions import config, les from functions.stringFormatters import capitalize -from functions.timeFormatters import intToWeekday, skip_weekends +from functions.timeFormatters import skip_weekends class School(commands.Cog): @@ -70,6 +71,11 @@ class School(commands.Cog): await message.pin(reason="Didier Pin door {}".format(ctx.author.display_name)) await ctx.message.add_reaction("✅") + @commands.command(name="Deadlines", aliases=["dl"]) + @help.Category(category=Category.School) + async def deadlines(self, ctx): + await ctx.send(embed=Deadlines().to_embed()) + def setup(client): client.add_cog(School(client)) diff --git a/cogs/slash/db_slash.py b/cogs/slash/db_slash.py new file mode 100644 index 0000000..bed6213 --- /dev/null +++ b/cogs/slash/db_slash.py @@ -0,0 +1,87 @@ +import datetime +import json + +from discord.ext import commands +from dislash import SlashInteraction, slash_command, Option, OptionType, check +from functions.checks import isMe +from functions.timeFormatters import fromString +from startup.didier import Didier + + +class Slash(commands.Cog): + def __init__(self, client: Didier): + self.client: Didier = client + + @slash_command(name="db") + @check(isMe) + async def _db_slash(self, interaction: SlashInteraction): + pass + + @_db_slash.sub_command_group(name="add") + async def _add_slash(self, interaction: SlashInteraction): + pass + + @_add_slash.sub_command( + name="deadline", + options=[ + Option( + "year", + description="Year (1-based)", + type=OptionType.INTEGER, + required=True + ), + Option( + "course", + description="Course (abbreviated)", + type=OptionType.STRING, + required=True + ), + Option( + "name", + description="Name of the deadline/project", + type=OptionType.STRING, + required=True + ), + Option( + "date", + description="Date (DD/MM)", + type=OptionType.STRING, + required=True + ), + Option( + "time", + description="Timestamp (HH:MM or HH:MM:SS)", + type=OptionType.STRING, + required=False + ) + ] + ) + async def _add_deadline_slash(self, interaction: SlashInteraction, year: int, course: str, name: str, date: str, time: str = "00:00:00"): + with open("files/deadlines.json", "r") as f: + deadlines = json.load(f) + + date += "/" + str(datetime.datetime.now().year) + + # Fix format + if time.count(":") == 1: + time += ":00" + + dt = fromString(f"{date} {time}", formatString="%d/%m/%Y %H:%M:%S") + + # Add year & course if necessary + if str(year) not in deadlines: + deadlines[str(year)] = {} + + if course not in deadlines[str(year)]: + deadlines[str(year)][course] = {} + + deadlines[str(year)][course][name] = round(dt.timestamp()) + + with open("files/deadlines.json", "w") as f: + json.dump(deadlines, f) + + await interaction.reply("Addition successful", ephemeral=True) + + +def setup(client: Didier): + client.add_cog(Slash(client)) diff --git a/cogs/slash/school_slash.py b/cogs/slash/school_slash.py index e94a562..6be3ea5 100644 --- a/cogs/slash/school_slash.py +++ b/cogs/slash/school_slash.py @@ -2,6 +2,7 @@ from discord.ext import commands from dislash import SlashInteraction, slash_command, Option, OptionType from data.embeds.food import Menu +from data.embeds.deadlines import Deadlines from startup.didier import Didier @@ -24,6 +25,11 @@ class SchoolSlash(commands.Cog): embed = Menu(dag).to_embed() await interaction.reply(embed=embed) + @slash_command(name="deadlines", description="Aanstaande deadlines") + async def _deadlines_slash(self, interaction: SlashInteraction): + embed = Deadlines().to_embed() + await interaction.reply(embed=embed) + def setup(client: Didier): client.add_cog(SchoolSlash(client)) diff --git a/data/embeds/deadlines.py b/data/embeds/deadlines.py new file mode 100644 index 0000000..59bcb74 --- /dev/null +++ b/data/embeds/deadlines.py @@ -0,0 +1,68 @@ +import json +import time +from dataclasses import dataclass + +from discord import Embed, Colour +from functions.stringFormatters import get_edu_year +from typing import Dict + +""" +Sample json structure: +{ + "1": { + "ad1": { + "proj1": 123456789 + } + } +} +""" + + +@dataclass +class Deadline: + course: str + name: str + t: int + passed: bool + + def __str__(self) -> str: + v = f"{self.course} - {self.name}: " + + if self.passed: + v = f"~~v~~" + + return v + + +class Deadlines: + data: Dict + + def __init__(self): + with open("files/deadlines.json") as f: + self.data = json.load(f) + + def to_embed(self) -> Embed: + embed = Embed(colour=Colour.dark_gold()) + embed.set_author(name="Aanstaande Deadlines") + + now = time.time() + + if not self.data: + embed.description = "Er staan geen deadlines gepland." + return embed + + courses: Dict + for year, courses in self.data.items(): + content = [] + + deadlines: Dict[str, int] + for course, deadlines in courses.items(): + for deadline, t in deadlines.items(): + content.append(Deadline(course, deadline, t, t < now)) + + content.sort(key=lambda x: x.t) + content = map(lambda x: str(x), content) + + embed.add_field(name=get_edu_year(int(year)), value="\n".join(content)) + + return embed diff --git a/files/default/deadlines.json b/files/default/deadlines.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/files/default/deadlines.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/files/help.json b/files/help.json index 5738649..86cfdfe 100644 --- a/files/help.json +++ b/files/help.json @@ -35,10 +35,12 @@ "corona vaccinations": "Vaccinatiecijfers voor België.", "custom": "Geeft een lijst van custom commands. Didier > Dyno confirmed once more.", "dadjoke": "Didier vertelt een dad joke.", + "deadlines": "Toont de (gekende) deadlines voor dit semester.", "define": "Geeft de definitie van [Woord] zoals het in de Urban Dictionary staat.\nZoektermen met spaties moeten **niet** tussen aanhalingstekens staan.", "detect": "Didier probeert de taal van [Tekst] te detecteren.", "dice": "Gok op de uitkomst van een dobbelsteen.", "dinks": "Bekijk jouw huidige aantal Dinks.", + "eten": "Geeft het menu voor [dag] weer in de UGent resto's.", "faq": "Stuurt een lijst van alle FAQ's in [Categorie] naar jouw DM's.\nGeef geen categorie op om een lijst van categorieën te krijgen.\nIndien je een of meerdere personen tagt, wordt de lijst naar hun DM's gestuurd in plaats van de jouwe.", "faq add": "Voegt een vraag & antwoord toe aan FAQ [Categorie].\nIndien je geen vraag & antwoord opgeeft, maakt het een categorie aan.", "faq quote": "Stuurt een specifieke entry uit de FAQ in het huidige channel in plaats van de hele lijst naar iemand's DM's.", diff --git a/functions/stringFormatters.py b/functions/stringFormatters.py index f8eb20f..f34e242 100644 --- a/functions/stringFormatters.py +++ b/functions/stringFormatters.py @@ -44,6 +44,7 @@ def format_command_usage(ctx: Context) -> str: def format_slash_command_usage(interaction: SlashInteraction) -> str: # Create a string with the options used + # TODO look into the format used by the lib because it's terrible options = " ".join(list(map( lambda option: f"{option.name}: \"{option.value}\"", interaction.data.options.values() @@ -51,3 +52,7 @@ def format_slash_command_usage(interaction: SlashInteraction) -> str: command = f"{interaction.slash_command.name} {options or ''}" return f"{interaction.author.display_name} in {_format_error_location(interaction)}: /{command}" + + +def get_edu_year(index: int) -> str: + return ["1ste Bachelor", "2de Bachelor", "3de Bachelor", "1ste Master", "2de Master"][index - 1] diff --git a/startup/init_files.py b/startup/init_files.py index 451ad0a..ad67bdd 100644 --- a/startup/init_files.py +++ b/startup/init_files.py @@ -3,7 +3,7 @@ from os import path def check_all(): - files = ["hangman", "lastTasks", "locked", "lost", "stats", "ufora_notifications"] + files = ["deadlines", "hangman", "lastTasks", "locked", "lost", "stats", "ufora_notifications"] for f in files: if not path.isfile(path.join(f"files/{f}.json")):