~denisebitca/esmeralde

600a3d2f68c643b5d52ce9da2887c2d2b1fbd4ca — Rafael Bitca 2 years ago a76ae8a
I am terrible at committing oh no
4 files changed, 106 insertions(+), 32 deletions(-)

M src/Crawler.ts
A src/FollowupFunctions.ts
M src/commands/edt.ts
M src/index.ts
M src/Crawler.ts => src/Crawler.ts +10 -15
@@ 1,25 1,20 @@
import cheerio, { CheerioAPI } from 'cheerio';
import https from 'https';
import { Snowflake } from 'discord.js';

var groups : Group[] = [];
var crawler : Crawler;
var $ : CheerioAPI;

export interface userInfo {
    id: Snowflake;
    group: Group;
    subGroup: SubGroup;
    id: string;
    group: string;
    subgroup: string;
}

export interface Group {
    name: string;
    id: number;
    id: string;
}

export interface SubGroup {
    name: string;
    id: number;
    id: string;
}

export class Crawler{


@@ 28,9 23,9 @@ export class Crawler{
        this.DOM = dom;
    }

    public static async newCrawler() : Promise<Crawler>{
    public static async newCrawler(url : string) : Promise<Crawler>{
        return new Promise((resolve, reject) => {
            const req = https.get("https://edt.iut-orsay.fr/edt_invite.php", (res) => {
            const req = https.get(url, (res) => {
                let data = "";
                res.on("data", (chunk) => {
                    data += chunk;


@@ 52,14 47,14 @@ export class Crawler{
            if(this.DOM != null && this.DOM(elem).attr('value') != "TOUS"){
                groups.push({
                    name: this.DOM(elem).text(),
                    id: Number(this.DOM(elem).attr('value'))
                    id: String(this.DOM(elem).attr('value'))
                });
            }
        });
        return groups;
    }

    public updateDOMUrl(group: Group, sub?: SubGroup) : string{
    public static updateDOMUrl(group: Group, sub?: SubGroup) : string{
        let url = "https://edt.iut-orsay.fr/edt_invite.php?selec_groupe=" + group.id + "&hau=1000&lar=1500";
        if(sub != undefined){
            let url = "https://edt.iut-orsay.fr/edt_invite.php?selec_groupe=" + group.id + "&groupes_multi[]=" + sub.id + "&hau=1000&lar=1500";


@@ 77,7 72,7 @@ export class Crawler{
            if(this.DOM != null && this.DOM(elem).attr('value') != "TOUS"){
                subGroups.push({
                    name: this.DOM(elem).text(),
                    id: Number(this.DOM(elem).attr('value'))
                    id: String(this.DOM(elem).attr('value'))
                });
            }
        });

A src/FollowupFunctions.ts => src/FollowupFunctions.ts +73 -0
@@ 0,0 1,73 @@
/*
These functions are used to follow up on commands
that have already been started.
*/

import * as Discord from 'discord.js';
import fs from 'fs';
import path from 'path';
import { Group, userInfo, Crawler, SubGroup } from './Crawler';
import * as config from './config.json'

export class FollowupFunctions{
    public static async followUpActionMenu1_edt(interaction: Discord.SelectMenuInteraction){
        
        let groupName : string = interaction.values[0].split("///")[0];
        let groupId : string = interaction.values[0].split("///")[1];
        let newGroup : Group = {
            name: groupName,
            id: groupId
        };
        
        let newCrawler : Crawler = await Crawler.newCrawler(Crawler.updateDOMUrl(newGroup));
        let subGroups : SubGroup[] = newCrawler.getSubGroups();

        const row = new Discord.MessageActionRow();
        let options : Discord.MessageSelectOptionData[] = [];

        let list = [];

        for(let i = 0; i < subGroups.length; i++){
            let newUser : userInfo = {
                id: interaction.user.id,
                group: JSON.stringify(newGroup, null, 0),
                subgroup: JSON.stringify(subGroups[i], null, 0)
            }
            options.push({
                label: subGroups[i].name,
                value: String(i)
            });
            list.push(newUser);
        }

        await fs.promises.writeFile(path.join(__dirname, interaction.user.id + ".json"), JSON.stringify(list, null, 0)+"\n");

        const menu = new Discord.MessageSelectMenu();
        menu.setCustomId("select3");
        menu.setPlaceholder("Choisis ton sous-groupe");
        menu.setOptions(options);
        menu.setMinValues(1);
        menu.setMaxValues(1);

        row.addComponents(menu);

        await interaction.update({content: "Maintenant choisis ton sous-groupe !", components: [row]});
    }
    public static async followUpActionMenu2_edt(interaction: Discord.SelectMenuInteraction){
        let choiceList : userInfo[] = JSON.parse(fs.readFileSync(path.join(__dirname, interaction.user.id + ".json"), "utf8"));
        let newUser : userInfo = choiceList[parseInt(interaction.values[0])];
        let configCopy = {
            "token": config.token,
            "CLIENTID": config.CLIENTID,
            "GUILDID": config.GUILDID,
            //@ts-ignore
            "userList": config.userList.length === 0 ? [newUser] : config.userList.concat([newUser])
        }
        await fs.promises.writeFile(path.join(__dirname, "config.json"), JSON.stringify(configCopy, null, 2));
        await interaction.update({content: "Votre groupe a été enregistré !", components: []});
    }

    public static async followUpNextPage(interaction: Discord.ButtonInteraction){
        //TODO
    }
}
\ No newline at end of file

M src/commands/edt.ts => src/commands/edt.ts +15 -14
@@ 1,13 1,11 @@
import {Crawler, Group, userInfo, SubGroup} from "../Crawler";
import cheerio, {CheerioAPI} from "cheerio";
import https from "https";
import {Crawler, Group, SubGroup} from "../Crawler";
import { CommandInteraction, MessageActionRow, MessageButton, MessageEmbed, MessageSelectMenu, MessageSelectOptionData } from "discord.js";
import { SlashCommandBuilder } from '@discordjs/builders';
import { Command } from '../index';
import fs from 'fs';
import config from '../config.json';
import dayjs from 'dayjs';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import path from "path";
dayjs.extend(weekOfYear);

function edtLink(subGroupId?: SubGroup["id"]) : string{


@@ 33,15 31,18 @@ let obj : Command = {
		.setDescription('Trouver ton emploi du temps ou l`emploi du temps de ton groupe.')
		.addIntegerOption(option => option.setName('id-etudiant').setDescription('l`identifiant de l`étudiant')),
	async execute(interaction : CommandInteraction) {
        if(config.userList.filter((user : userInfo) => user.id === interaction.user.id).length === 0){
            config.userList.forEach((user : userInfo) => {
                if(user.id === interaction.user.id){
                   return interaction.reply(edtLink(user.subGroup.id));
                }
            });

        var config = JSON.parse(fs.readFileSync(path.join(__dirname, "../config.json"), {encoding: "utf-8"}));

        //@ts-ignore
        let presenceCheck = config.userList.filter(user => user.id === interaction.user.id);
        if(presenceCheck.length === 1){
            //@ts-ignore
            return interaction.reply(edtLink(JSON.parse(presenceCheck[0].subgroup).id));

        }

        let crawler = await Crawler.newCrawler();
        let crawler = await Crawler.newCrawler("https://edt.iut-orsay.fr/edt_invite.php");
        let groups : Group[] = crawler.getGroups();

        if(groups.length > 0){


@@ 53,12 54,12 @@ let obj : Command = {
                if(options.length < 25){
                    options.push({
                        label: "Groupe " + group.name,
                        value: String(group.id)
                        value: String(group.name+"///"+group.id)
                    });
                } else {
                    options2.push({
                        label: "Groupe " + group.name,
                        value: String(group.id)
                        value: String(group.name+"///"+group.id)
                    })
                }
            });


@@ 68,7 69,7 @@ let obj : Command = {
            .setTitle('Esmeralde')
            .setDescription('Je suis le bot EDT de l`IUT.\nPour commencer, tu dois selectionner ton groupe.\nPour cela, clique sur le bouton correspondant.');

            row.addComponents(new MessageSelectMenu().setCustomId("select").setPlaceholder("Pas de groupe selectionné").addOptions(options).setMinValues(1).setMaxValues(1));
            row.addComponents(new MessageSelectMenu().setCustomId("select").setPlaceholder("Pas de groupe selectionné dans la page 1").addOptions(options).setMinValues(1).setMaxValues(1));

            if(options2.length > 0){
                const row2 = new MessageActionRow();

M src/index.ts => src/index.ts +8 -3
@@ 3,7 3,7 @@ import fs from 'fs';
import path from 'path';

//config
import config from './config.json';
var config = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json"), "utf8"));

//discord
import * as Discord from 'discord.js';


@@ 12,6 12,9 @@ import { REST } from '@discordjs/rest';
import { Routes } from 'discord-api-types/v9';
const wait = require('util').promisify(setTimeout);

//other
import {FollowupFunctions} from './FollowupFunctions';

export interface Command {
	data: Omit<SlashCommandBuilder, "addSubcommand" | "addSubcommandGroup">,
	execute(interaction : Discord.CommandInteraction) : Promise<void>;


@@ 66,8 69,10 @@ client.once('ready', () => {
client.on('interactionCreate', async interaction => {
	if (interaction.isSelectMenu()){
		if (interaction.customId === 'select' || interaction.customId === 'select2') {
			console.log(interaction.values[0]);
			await interaction.update({content: "test", embeds: [], components: []});
			FollowupFunctions.followUpActionMenu1_edt(interaction);
		} else if (interaction.customId === 'select3') {
			FollowupFunctions.followUpActionMenu2_edt(interaction);
			config = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json"), {encoding: "utf-8"}));
		}
    } else if(interaction.isCommand()){
        const command = client.commands.get(interaction.commandName);