~denisebitca/esmeralde

88b741758b9b77b6b3e362a27514066220577aef — Rafael Bitca 2 years ago a13e695
Changed file names and replaced some config refs
8 files changed, 94 insertions(+), 34 deletions(-)

M README.md
M src/Crawler.ts
A src/DB.ts
D src/Database.ts
M src/FollowupFunctions.ts
M src/commands/delconf.ts
M src/commands/edt.ts
M src/index.ts
M README.md => README.md +1 -2
@@ 6,7 6,6 @@ src/config.json :
{
    "token": "12345",
    "CLIENTID": "12345",
    "GUILDID": ["12345", ...],
    "userList": []
    "GUILDID": ["12345", ...]
}
```
\ No newline at end of file

M src/Crawler.ts => src/Crawler.ts +0 -1
@@ 2,7 2,6 @@ import cheerio, { CheerioAPI } from 'cheerio';
import https from 'https';

export interface userInfo {
    id: string;
    group: string;
    subgroup: string;
}

A src/DB.ts => src/DB.ts +70 -0
@@ 0,0 1,70 @@
import Database from 'better-sqlite3';


export class DB{
    public static db: Database.Database;
    constructor(){
        DB.db = new Database('database.db');
        if(!DB.checkIfDatabaseInitialised()){
            DB.init();
        }
    }

    // Create table preference with user id, group info and sub group info
    public static init(){
        DB.db.prepare(`CREATE TABLE IF NOT EXISTS preference (
            id INTEGER PRIMARY KEY,
            group VARCHAR(150) NOT NULL,
            subgroup VARCHAR(150) NOT NULL
        )`).run();
    }

    public static checkIfDatabaseInitialised(){
        try{
            if(DB.db.prepare(`SELECT * FROM preference`).get() === 0 || DB.db.prepare(`SELECT * FROM preference`)){
                return true;
            } else {
                return false;
            }
        } catch(e) {
            console.log(e);
            return false;
        }
    }

    public static checkIfUserExists(id: string){
        try {
            return DB.db.prepare(`SELECT * FROM preference WHERE id = ?`).get(id);
        } catch (e) {
            console.log(e);
            return false;
        }
    }

    public static addUser(id: string, group: string, subgroup: string){
        try{
            if(DB.checkIfUserExists(id)){
                return false;
            } else {
                return DB.db.prepare(`INSERT INTO preference (id, group, subgroup) VALUES (?, ?, ?)`).run(id, group, subgroup);
            }
        } catch(e){
            console.log(e);
            return false;
        }
    }

    public static removeUser(id: string){
        try{
            DB.db.prepare(`DELETE FROM preference WHERE id = ?`).run(id);
        } catch(e){
            console.log(e);
            return false;
        }
        return true;
    }


}

export default DB;
\ No newline at end of file

D src/Database.ts => src/Database.ts +0 -5
@@ 1,5 0,0 @@
const db = require('better-sqlite3')('database.sqlite');

export class Database{
    
}
\ No newline at end of file

M src/FollowupFunctions.ts => src/FollowupFunctions.ts +10 -13
@@ 2,12 2,12 @@
These functions are used to follow up on commands
that have already been started.
*/

import { DB } from './DB';
import * as Discord from 'discord.js';
import fs from 'fs';
import path from 'path';
import { Group, userInfo, Crawler, SubGroup } from './Crawler';
var config = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json"), "utf8"));
//var config = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json"), "utf8"));

export class FollowupFunctions{
    public static async followUpActionMenu1_edt(interaction: Discord.SelectMenuInteraction){


@@ 29,7 29,6 @@ export class FollowupFunctions{

        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)
            }


@@ 40,7 39,7 @@ export class FollowupFunctions{
            list.push(newUser);
        }

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

        const menu = new Discord.MessageSelectMenu();
        menu.setCustomId("select3");


@@ 56,16 55,14 @@ export class FollowupFunctions{
    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])
        }
        fs.writeFileSync(path.join(__dirname, "config.json"), JSON.stringify(configCopy, null, 2), {encoding: "utf-8"});
        let newGroup : string = newUser.group;
        let newSubGroup : string = newUser.subgroup;
        fs.rmSync(path.join(__dirname, interaction.user.id + ".json"));
        await interaction.update({content: "Ton emploi du temps a été enregistré !", embeds: [], components: []});
        if(DB.addUser(interaction.user.id, newGroup, newSubGroup)){
            await interaction.update({content: "Ton emploi du temps a été enregistré !", embeds: [], components: []});
        } else {
            await interaction.update({content: "Erreur avec la sauvegarde, contacte denise#2798 !", embeds: [], components: []});
        }
    }

    public static async followUpNextPage(interaction: Discord.ButtonInteraction){

M src/commands/delconf.ts => src/commands/delconf.ts +7 -7
@@ 3,19 3,19 @@ import { SlashCommandBuilder } from '@discordjs/builders';
import { Command } from '../index';
import fs from 'fs';
import path from "path";
import DB from "../DB";

let obj : Command = {
	data: new SlashCommandBuilder()
		.setName('delconf')
		.setDescription('Supprime la configuration de ton emploi du temps.'),
	async execute(interaction : CommandInteraction) {
        let config = JSON.parse(fs.readFileSync(path.join(__dirname, "../config.json"), {encoding: "utf-8"}));
        //@ts-ignore
        if(config.userList.filter(user => user.id === interaction.user.id).length === 1){
            //@ts-ignore
            config.userList = config.userList.filter(user => user.id !== interaction.user.id);
            fs.writeFileSync(path.join(__dirname, "../config.json"), JSON.stringify(config, null, 2));
            return interaction.reply({content:"Tu as bien supprimé ton emploi du temps.", ephemeral: true});
        if(DB.checkIfUserExists(interaction.user.id)){
            if(DB.removeUser(interaction.user.id)){
                return interaction.reply({content:"Tu as bien supprimé ton emploi du temps.", ephemeral: true});
            } else {
                return interaction.reply({content:"Erreur avec la suppréssion de tes données ! Contacte denise#2798.", ephemeral: true});
            }
        } else {
            return interaction.reply({content: "Tu n'es pas dans la liste des utilisateurs qui ont configuré leur emploi du temps.", ephemeral: true});
        }

M src/commands/edt.ts => src/commands/edt.ts +3 -6
@@ 6,6 6,7 @@ import fs from 'fs';
import dayjs from 'dayjs';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import path from "path";
import DB from "../DB";
dayjs.extend(weekOfYear);

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


@@ 33,12 34,8 @@ let obj : Command = {

        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({content: edtLink(JSON.parse(presenceCheck[0].subgroup).id), ephemeral: true});

        if(DB.getUser(interaction.user.id)){
            //return interaction.reply({content: edtLink(JSON.parse(presenceCheck[0].subgroup).id), ephemeral: true});
        }

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

M src/index.ts => src/index.ts +3 -0
@@ 13,6 13,9 @@ import { Routes } from 'discord-api-types/v9';

//other
import {FollowupFunctions} from './FollowupFunctions';
import { DB } from './DB';
new DB();


export interface Command {
	data: Omit<SlashCommandBuilder, "addSubcommand" | "addSubcommandGroup">,