test 4345

This commit is contained in:
Lou 2025-11-20 20:48:18 +01:00
parent 6f7616823f
commit 2b0a93c39f
4 changed files with 104 additions and 84 deletions

112
db.js
View file

@ -1,8 +1,8 @@
import Database from 'better-sqlite3'; import fs from 'fs';
// Initialisation (crée le fichier s'il n'existe pas) const DB_PATH = './db.json';
export const db = new Database('./db.sqlite');
// Valeurs par défaut
const settingsDefaultValues = { const settingsDefaultValues = {
quoiAnswerPercentage: 100, quoiAnswerPercentage: 100,
quoicoubehAnswerPercentage: 100, quoicoubehAnswerPercentage: 100,
@ -12,73 +12,81 @@ const settingsDefaultValues = {
ignoredRoleId: null, ignoredRoleId: null,
}; };
function initDb() { // Structure de base de la DB en mémoire
// .exec pour les scripts sans paramètres let dbData = {
db.exec(` ignoredChannels: [], // Liste d'objets { channelId, guildId }
CREATE TABLE IF NOT EXISTS IgnoredChannels ( configs: {} // Objet : guildId -> { settings }
channelId VARCHAR PRIMARY KEY, };
guildId VARCHAR
);
`);
db.exec(` // --- Fonctions internes (Sauvegarde/Chargement) ---
CREATE TABLE IF NOT EXISTS Config (
guildId VARCHAR PRIMARY KEY, function loadDb() {
quoiAnswerPercentage INTEGER NOT NULL DEFAULT ${settingsDefaultValues.quoiAnswerPercentage}, if (!fs.existsSync(DB_PATH)) {
quoicoubehAnswerPercentage INTEGER NOT NULL DEFAULT ${settingsDefaultValues.quoicoubehAnswerPercentage}, saveDb(); // Crée le fichier s'il n'existe pas
feurAnswerPercentage INTEGER NOT NULL DEFAULT ${settingsDefaultValues.feurAnswerPercentage}, return;
mentionAnswerPercentage INTEGER NOT NULL DEFAULT ${settingsDefaultValues.mentionAnswerPercentage}, }
forcedAnswerRoleId VARCHAR, try {
ignoredRoleId VARCHAR const raw = fs.readFileSync(DB_PATH, 'utf-8');
); dbData = JSON.parse(raw);
`);
// Sécurité : s'assurer que les structures existent
if (!dbData.ignoredChannels) dbData.ignoredChannels = [];
if (!dbData.configs) dbData.configs = {};
} catch (e) {
console.error("Erreur lecture DB, réinitialisation :", e);
saveDb();
}
} }
function saveDb() {
fs.writeFileSync(DB_PATH, JSON.stringify(dbData, null, 2), 'utf-8');
}
// Initialisation au démarrage
loadDb();
// --- Fonctions exportées (Même signature que l'ancien db.js) ---
export function addChannelToIgnoreList(channelId, guildId) { export function addChannelToIgnoreList(channelId, guildId) {
return db.prepare(` // Vérifier si déjà présent
INSERT INTO IgnoredChannels (channelId, guildId) const exists = dbData.ignoredChannels.some(c => c.channelId === channelId);
VALUES (?, ?) if (!exists) {
ON CONFLICT(channelId) DO NOTHING dbData.ignoredChannels.push({ channelId, guildId });
`).run(channelId, guildId); saveDb();
}
} }
export function getIgnoredChannels(guildId) { export function getIgnoredChannels(guildId) {
return db.prepare(` return dbData.ignoredChannels.filter(c => c.guildId === guildId);
SELECT channelId
FROM IgnoredChannels
WHERE guildId = ?
`).all(guildId);
} }
export function removeChannelFromIgnoreList(channelId) { export function removeChannelFromIgnoreList(channelId) {
return db.prepare(` const initialLength = dbData.ignoredChannels.length;
DELETE FROM IgnoredChannels dbData.ignoredChannels = dbData.ignoredChannels.filter(c => c.channelId !== channelId);
WHERE channelId = ?
`).run(channelId); if (dbData.ignoredChannels.length !== initialLength) {
saveDb();
}
} }
export function setSetting(guildId, setting, value) { export function setSetting(guildId, setting, value) {
// ${setting} est injecté directement (nom de colonne) // Initialiser la config de la guilde si inexistante
return db.prepare(` if (!dbData.configs[guildId]) {
INSERT INTO Config (guildId, ${setting}) dbData.configs[guildId] = { ...settingsDefaultValues };
VALUES (?, ?) }
ON CONFLICT(guildId) DO UPDATE SET ${setting} = ?
`).run(guildId, value, value); // Mettre à jour la valeur
dbData.configs[guildId][setting] = value;
saveDb();
} }
export function getSetting(guildId, setting) { export function getSetting(guildId, setting) {
// .pluck() permet de récupérer directement la valeur au lieu d'un objet { colonne: valeur } const config = dbData.configs[guildId];
const result = db.prepare(`
SELECT ${setting}
FROM Config
WHERE guildId = ?
`).pluck().get(guildId);
if (result === undefined) { if (!config) {
return settingsDefaultValues[setting]; return settingsDefaultValues[setting];
} }
return result; const val = config[setting];
return val === undefined ? settingsDefaultValues[setting] : val;
} }
initDb();

View file

@ -1,7 +1,7 @@
import Detector from "./Detector.js"; import Detector from "./Detector.js";
import compromise from 'fr-compromise'; import compromise from 'fr-compromise';
import conj from 'conjugation-fr'; import conj from 'conjugation-fr';
import { toInfinitive } from "../data.js"; // check path ?? import { toInfinitive } from "../data/index.js";
import { cleanMessageContent } from "../utils/strings.js"; import { cleanMessageContent } from "../utils/strings.js";
/*check the pronoun / subject of the question to answer properly by conjugating /*check the pronoun / subject of the question to answer properly by conjugating
@ -12,9 +12,7 @@ const suffixes = [
', mon gars', ', mon gars',
', mec', ', mec',
", je crois", ", je crois",
'', '', '', ''
'',
''
]; ];
export default class withPronounDetector extends Detector { export default class withPronounDetector extends Detector {
@ -22,9 +20,11 @@ export default class withPronounDetector extends Detector {
const reference = await message.fetchReference().catch(() => null); const reference = await message.fetchReference().catch(() => null);
const isSelfTarget = (reference && reference.author.id === message.client.user?.id) ?? false; const isSelfTarget = (reference && reference.author.id === message.client.user?.id) ?? false;
const compromiseMatch = compromise(cleanMessageContent(message).toLowerCase()).match('(#Pronoun|ça|ca|tu) (#Verb|fait) #Infinitive? quoi [<suffix>!Verb{0,3}]$'); const text = cleanMessageContent(message).toLowerCase();
const compromiseMatch = compromise(text).match('(#Pronoun|ça|ca|tu) (#Verb|fait) #Infinitive? quoi [<suffix>!Verb{0,3}]$');
if (compromiseMatch == null || compromiseMatch.length === 0) { if (compromiseMatch == null || compromiseMatch.length === 0) {
// console.log("DEBUG: Pas de structure 'Sujet + Verbe + Quoi' détectée.");
return null; return null;
} }
@ -37,26 +37,41 @@ export default class withPronounDetector extends Detector {
const replySuffix = compromiseMatch.groups('suffix')?.text().trim() ?? ''; const replySuffix = compromiseMatch.groups('suffix')?.text().trim() ?? '';
if (result == null) { if (result == null) return '';
const verbTerm = result.terms[1];
if (!verbTerm) {
console.log("DEBUG: Structure détectée mais verbe introuvable.");
return ''; return '';
} }
// warning : result.terms[1] can't exist if the compromise structure change const verbText = verbTerm.text.toLowerCase();
const verbTerm = result.terms[1];
if (!verbTerm) return '';
const verbInfinitive = toInfinitive[verbTerm.text]; // Debug: On vérifie ce qu'il cherche
if (!verbInfinitive) return ''; // safety check if the verb is in the list const verbInfinitive = toInfinitive[verbText];
if (!verbInfinitive) {
console.log(`DEBUG: ÉCHEC - Le verbe '${verbText}' n'est pas dans toInfinitive.json`);
return ''; //drop et initialise perroquet (suffixDetector ou basicDetector)
}
let conjugated = ''; let conjugated = '';
const tenseTag = verbTerm.tags.find(t => t.endsWith('Tense')) ?? 'Present'; const tenseTag = verbTerm.tags.find(t => t.endsWith('Tense')) ?? 'Present';
const getConjugation = (pronoun) => { const getConjugation = (pronoun) => {
try {
const tenseData = conj.findTense(verbInfinitive, tenseTag); const tenseData = conj.findTense(verbInfinitive, tenseTag);
return tenseData.find(c => c.pronoun === pronoun)?.verb; return tenseData.find(c => c.pronoun === pronoun)?.verb;
} catch (e) {
console.error(`DEBUG: Erreur conjugation-fr pour ${verbInfinitive}:`, e);
return null;
}
}; };
switch (result.terms[0].text.toLowerCase()) { // Logique d'inversion des pronoms
const subjectText = result.terms[0].text.toLowerCase();
switch (subjectText) {
case 'je': case 'je':
case "j'": case "j'":
conjugated = `tu ${getConjugation('tu')}`; conjugated = `tu ${getConjugation('tu')}`;
@ -70,16 +85,13 @@ export default class withPronounDetector extends Detector {
} }
break; break;
case 'il': case 'il':
conjugated = `il ${getConjugation('il')}`; case 'on':
case 'ça':
case 'ca':
conjugated = `${subjectText} ${getConjugation('il')}`;
break; break;
case 'elle': case 'elle':
conjugated = `elle ${getConjugation('il')}`; // 'elle' utilise la conjugaison 'il' dans cette lib souvent conjugated = `elle ${getConjugation('il')}`;
break;
case 'on':
conjugated = `on ${getConjugation('il')}`;
break;
case 'ça':
conjugated = `ça ${getConjugation('il')}`;
break; break;
case 'nous': case 'nous':
conjugated = `nous ${getConjugation('nous')}`; conjugated = `nous ${getConjugation('nous')}`;
@ -94,8 +106,13 @@ export default class withPronounDetector extends Detector {
conjugated = `elles ${getConjugation('ils')}`; conjugated = `elles ${getConjugation('ils')}`;
break; break;
default: default:
conjugated = ''; console.log(`DEBUG: Pronom '${subjectText}' non géré.`);
break; return '';
}
if (!conjugated || conjugated.includes('undefined')) {
console.log(`DEBUG: Échec conjugaison finale.`);
return '';
} }
const infinitiveVerb = result.terms.find(t => t.tags.includes('Infinitive'))?.text ?? ''; const infinitiveVerb = result.terms.find(t => t.tags.includes('Infinitive'))?.text ?? '';

3
package-lock.json generated
View file

@ -1,12 +1,9 @@
{ {
"name": "genius-troll", "name": "genius-troll",
"version": "1.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "genius-troll",
"version": "1.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"conjugation-fr": "^0.3.4", "conjugation-fr": "^0.3.4",

View file

@ -16,7 +16,5 @@
"discord.js": "^14.25.0", "discord.js": "^14.25.0",
"dotenv": "^17.2.3", "dotenv": "^17.2.3",
"fr-compromise": "^0.2.8", "fr-compromise": "^0.2.8",
"better-sqlite3": "^11.0.0"
} }
} }