added a way to get what room is available at a given time
This commit is contained in:
Simon Lancelin 2024-11-22 23:47:13 +01:00
parent c1ce0b8d08
commit 8044a7600a
5 changed files with 202 additions and 55 deletions

BIN
edt salles.xlsx Normal file

Binary file not shown.

170
main.py
View File

@ -2,6 +2,7 @@ from datetime import datetime
import discord
from discord import app_commands
from parse_colles import create_colloscope
from parse_salles import create_edt, parse_edt
import os
from dotenv import load_dotenv, dotenv_values
@ -9,24 +10,51 @@ from dotenv import load_dotenv, dotenv_values
# Créer une instance du bot
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client( intents=intents)
bot = discord.Client(intents=intents)
tree = app_commands.CommandTree(bot)
exclusions = ["dire", "dis", "disons", "dites", "dîtes", "dit"]
load_dotenv()
# Événement lorsque le bot est prêt
@bot.event
async def on_ready():
await tree.sync(guild=discord.Object(id=1292935532472565852))
print(f'Connecté en tant que {bot.user.name}')
print(f"Connecté en tant que {bot.user.name}")
botactivity = discord.Streaming(url="https://twitch.tv/marsisus", name=" l'exiiistence.")
botactivity = discord.Streaming(
url="https://twitch.tv/marsisus", name=" l'exiiistence."
)
await bot.change_presence(activity=botactivity)
async def hour_autocomplete(
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
hours = ["8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"]
return [
app_commands.Choice(name=hour, value=hour)
for hour in hours
if current.lower() in hour.lower()
]
async def day_autocomplete(
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
days = ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"]
return [
app_commands.Choice(name=day, value=day)
for day in days
if current.lower() in day.lower()
]
# réagir a un message
@bot.event
@ -36,18 +64,24 @@ async def on_message(message):
if "quoi" in message.content[-10:].lower():
await message.channel.send(f"quoicoubeh {message.author.mention} !")
if "j'aime" in message.content.lower()[:6]:
await message.author.edit(nick=f'{message.content[6:]}')
await message.author.edit(nick=f"{message.content[6:]}")
for i in range(len(message.content.split())):
if message.content.lower().split()[i] in exclusions:
continue;
continue
if len(message.content.split()[i]) < 4:
continue
if "dis" in message.content.lower().split()[i][:3] or "dit" in message.content.lower().split()[i][:3]:
if (
"dis" in message.content.lower().split()[i][:3]
or "dit" in message.content.lower().split()[i][:3]
):
await message.channel.send(f"{message.content.split()[i][3:]}")
elif "cri" in message.content.lower().split()[i][:3]:
await message.channel.send(f"{message.content.upper().split()[i][3:]}")
elif "di" in message.content.lower().split()[i][:2] or "dy" in message.content.lower().split()[i][:2]:
elif (
"di" in message.content.lower().split()[i][:2]
or "dy" in message.content.lower().split()[i][:2]
):
await message.channel.send(f"{message.content.split()[i][2:]}")
@ -55,80 +89,124 @@ async def on_message(message):
@tree.command(
name="parse_colles",
description="Récupérer un fichier en .ics contenant vos colles du S1",
guild=discord.Object(id=1292935532472565852)
guild=discord.Object(id=1292935532472565852),
)
@app_commands.describe(group = "Votre Groupe de Colles. (1-16)")
@app_commands.describe(timezone = "Le fuseau Horaire UTC+n (laisser vide si vous ne savez pas), UTC+2 par défaut")
async def recup_colles(interaction:discord.Interaction, group:str, timezone:str = "Europe/Paris"):
if 0<int(group)<17:
@app_commands.describe(group="Votre Groupe de Colles. (1-16)")
@app_commands.describe(
timezone="Le fuseau Horaire UTC+n (laisser vide si vous ne savez pas), UTC+2 par défaut"
)
async def recup_colles(
interaction: discord.Interaction, group: str, timezone: str = "Europe/Paris"
):
if 0 < int(group) < 17:
create_colloscope(int(group), timezone)
await interaction.response.send_message(content=f"Voici le fichier de colles parsé pour le groupe {group} ! ", file=discord.File("output.ics", filename=f"groupe{group}.ics") )
await interaction.response.send_message(
content=f"Voici le fichier de colles parsé pour le groupe {group} ! ",
file=discord.File("output.ics", filename=f"groupe{group}.ics"),
)
else:
await interaction.response.send_message(content="Ce groupe n'existe pas banane !")
await interaction.response.send_message(
content="Ce groupe n'existe pas banane !"
)
@tree.command(
name="free_rooms",
description="Trouver les salles libres à un moment donné",
guild=discord.Object(id=1292935532472565852),
)
@app_commands.describe(hour="L'heure de la journée (par défault maintenant) (sans le h)")
@app_commands.autocomplete(hour=hour_autocomplete)
@app_commands.describe(day="Le jour de la semaine (par défault aujourd'hui)")
@app_commands.autocomplete(day=day_autocomplete)
async def recup_edt(
interaction: discord.Interaction,
day: str = datetime.now().strftime("%A"),
hour: str = datetime.now().strftime("%H"),
):
if 8 <= int(hour) <= 18:
free_rooms = create_edt(int(hour), 1, day.capitalize())
embeds = parse_edt(sorted(free_rooms), hour, day.capitalize())
await interaction.response.send_message(embed=embeds[0])
if len(embeds) == 2:
await interaction.followup.send(embed=embeds[1])
else:
await interaction.response.send_message(
content=f"Je ne connais pas {hour} heure(s)..."
)
# Slash command to get help
@tree.command(
name="help",
description="Afficher l'aide",
guild=discord.Object(id=1292935532472565852)
guild=discord.Object(id=1292935532472565852),
)
async def help(interaction:discord.Interaction):
embed = discord.Embed(title="Le Bot des MP2I[3]",
async def help(interaction: discord.Interaction):
embed = discord.Embed(
title="Le Bot des MP2I[3]",
url="https://staticky.marsisus.me",
description="""
Bienvenue sur la page d'aide du bot !
Voici les commandes disponibles :
- `/parse_colles [groupe] {timezone}`
: Récupérer un fichier en .ics contenant vos colles du S1
- `/free_rooms {jour} {heure}`
: Trouver les salles libres à un moment donné
- `/help` : Afficher l'aide""",
colour=0x00b0f4,
timestamp=datetime.now())
colour=0x00B0F4,
timestamp=datetime.now(),
)
embed.set_author(name="Staticky",
url="https://staticky.marsisus.me",)
embed.set_author(
name="Staticky",
url="https://staticky.marsisus.me",
)
await interaction.response.send_message(embed=embed, ephemeral=True)
async def hour_autocomplete(
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
hours = ["13", "14", "15", "16", "17", '18']
return [
app_commands.Choice(name=hour, value=hour)
for hour in hours if current.lower() in hour.lower()
]
# Slash command to add a colle to the marketplace
@tree.command(
name="add_colle",
description="!!NE FONCTIONNE PAS !! Ajoute une collle au marketplace",
guild=discord.Object(id=1292935532472565852)
guild=discord.Object(id=1292935532472565852),
)
@app_commands.describe(group = "Votre Groupe de Colles. (1-16)")
@app_commands.describe(day = "Format: JJ/MM/AAAA, bien réspécter le format")
@app_commands.describe(hour = "L'heure de la colle, sans le \"h\"")
@app_commands.describe(group="Votre Groupe de Colles. (1-16)")
@app_commands.describe(day="Format: JJ/MM/AAAA, bien réspécter le format")
@app_commands.describe(hour='L\'heure de la colle, sans le "h"')
@app_commands.autocomplete(hour=hour_autocomplete)
@app_commands.describe(teacher = "Le nom du professeur")
@app_commands.describe(subject = "La matière de la colle (Maths, Physique, Anglais, Lettres)")
@app_commands.describe(teacher="Le nom du professeur")
@app_commands.describe(
subject="La matière de la colle (Maths, Physique, Anglais, Lettres)"
)
# @app_commands.autocomplete(subject=["Maths", "Physique", "Anglais", "Lettres"])
@app_commands.describe(room = "La salle de la colle")
@app_commands.describe(room="La salle de la colle")
# @app_commands.autocomplete(group=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"])
async def add_colle(interaction:discord.Interaction, group:str, day:str, hour:str, teacher:str, subject:str, room:str):
async def add_colle(
interaction: discord.Interaction,
group: str,
day: str,
hour: str,
teacher: str,
subject: str,
room: str,
):
# "ASSERTIONS" A IMPLEMENTER !!!!
embed = discord.Embed(title=f"Colle de {subject}",
embed = discord.Embed(
title=f"Colle de {subject}",
description=f"Date : {day} {hour}h00\nProfesseur : {teacher}\nSalle : {room}\n Groupe : {group}\n\n! ENCORE EN PHASE DE TEST ! NON FONCTIONNEL !",
colour=0xf50083,
timestamp=datetime.now())
colour=0xF50083,
timestamp=datetime.now(),
)
embed.set_author(name=f"{interaction.user.name}")
await interaction.response.send_message(embed=embed)
# Lancer le bot
bot.run(os.getenv('BOT_TOKEN'))
bot.run(os.getenv("BOT_TOKEN"))

View File

@ -52,7 +52,11 @@ def create_colloscope(groupe:int, timezone:str = "Europe/Paris"):
continue
day_sem = str(day_sem).split(" ")[0]
days = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
days_english = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
try:
day_number_sem = days.index(day_sem)
except ValueError:
day_number_sem = days_english.index(day_sem)
# Combine day_number_sem with date
new_days = day_number_sem + date.day;

65
parse_salles.py Normal file
View File

@ -0,0 +1,65 @@
import openpyxl
from datetime import datetime, timedelta, timezone
import discord
from discord import app_commands, Embed
def create_edt(heure:int, semestre:int, day:int) -> list[int]:
days = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
days_english = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
try:
day_number_sem = days.index(day)
except ValueError:
day_number_sem = days_english.index(day)
workbook = openpyxl.load_workbook('edt salles.xlsx')
sheet = workbook['EDT']
# Retrieve all coordinates where the cell value is 10
coordinates = []
for cell in sheet[3 + (heure - 8) + 11*day_number_sem][1:]:
val = cell.value
if val is None or ("0" not in val and "O" not in val and "S1" not in val):
try:
temp = sheet.cell(row=1, column=cell.column).value
if temp is not None:
coordinates.append((temp, sheet.cell(row=2, column=cell.column).value))
except Exception as e:
print(f"Error: {e}")
return coordinates
def set_value(type, hour) -> str:
if type == "sci":
return ":test_tube: :white_check_mark:"
if type == "info":
return ":desktop: :no_entry:"
if type == "colle":
return "<:colle:1309644102345949295> :grey_question:"
if type == "classe":
return ":mortar_board: :white_check_mark:"
else : return ""
def parse_edt(coordinates, hour, day):
embeds = []
embed1 = discord.Embed(title=f"EDT : {hour}h - {day}",
url="https://staticky.marsisus.me",
description=f"Liste des Salles disponibles à {hour}h",
timestamp=datetime.now())
for i in range(min(25, len(coordinates))):
embed1.add_field(name=f"**{coordinates[i][0]}**", inline=True, value=set_value(coordinates[i][1], hour))
embed1.set_footer(text="Made by Marsisus, Magos, Hugo, Gabriel... ")
embeds.append(embed1)
if len(coordinates) > 25:
embed2 = discord.Embed(
timestamp=datetime.now())
for i in range(25, len(coordinates)):
embed2.add_field(name=f"**{coordinates[i][0]}**", value=set_value(coordinates[i][1], hour), inline=True)
embed2.set_footer(text="Made by Marsisus, Magos, Hugo, Gabriel... ")
embeds.append(embed2)
return embeds

BIN
~$edt salles.xlsx Normal file

Binary file not shown.