Skip to content

Commit

Permalink
Add Prometheus/Grafana metrics (#232)
Browse files Browse the repository at this point in the history
* add promhandler

* oop

* add: user/server metrics

* fix: text fill translations
  • Loading branch information
mezotv authored Nov 12, 2023
1 parent 3c921d9 commit 6dd05c1
Show file tree
Hide file tree
Showing 9 changed files with 185 additions and 28 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"moment-timezone": "^0.5.43",
"mongoose": "^7.5.0",
"profanity-check": "^0.0.3",
"prom-client": "^15.0.0",
"quickchart-js": "^3.1.3",
"topgg-autoposter": "^2.0.1",
"uuid": "^9.0.0"
Expand Down
26 changes: 26 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 3 additions & 4 deletions src/commands/settings/custom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,12 @@ const command: ChatInputCommand = {
message = interaction.options.getString("message");

let newID = makeID(6);

if (option === "wouldyourather")
generativeText = generateWYR(client, message || "", newID);
generativeText = generateWYR(client, message || "", newID, guildDb);
else if (option === "neverhaveiever")
generativeText = generateNHIE(client, message || "", newID);
generativeText = generateNHIE(client, message || "", newID, guildDb);
else if (option === "wwyd")
generativeText = generateWWYD(client, message || "", newID);
generativeText = generateWWYD(client, message || "", newID, guildDb);

typeEmbed = new EmbedBuilder()
.setTitle(
Expand Down
10 changes: 8 additions & 2 deletions src/languages/de_DE.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,13 @@
"descID": "ID",
"descMsg": "Nachricht",
"descCat": "Kategorie",
"descCont": "Inhalt"
"descCont": "Inhalt",
"descAccept": "Es scheint, als hättest du \"{type}\" nicht an den Anfang deines Textes gesetzt. Möchtest du, dass ich es automatisch hinzufüge?",
"descWYR": "Würdest du eher",
"descNHIE": "Ich habe noch nie",
"descWWYD": "Was würdest du tun",
"footerDisable": "Dieser Button wird in 30 Sekunden deaktiviert.",
"success": "Erfolgreich \"{type}\" zum Anfang des Textes hinzugefügt!"
},
"embedRemove": {
"title": "Diese Would You Nachricht wurde erfolgreich gelöscht!"
Expand Down Expand Up @@ -157,7 +163,7 @@
},
"Vote": {
"embed": {
"title": "Voten hilft **Would You** mehr Server zu erreichen. Also denk daran jeden Tag zu Voten!",
"title": "Abstimmen hilft **Würdest du** mehr Popularität unter den Nutzern auf Discord zu gewinnen! Du kannst alle 12 Stunden abstimmen und den Bot unterstützen!",
"value": "Klicke um zu Voten",
"footer": "Would You"
}
Expand Down
16 changes: 11 additions & 5 deletions src/languages/es_ES.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"turnOff": "Desactivar",
"on": "Activado",
"off": "Desactivado",
"desc": "En activant la confidentialité, ton nom d'utilisateur ne sera plus affiché sur les résultats des votes! Tes votes seront complètement anonymes si cette option est activée."
"desc": "¡Activar la privacidad removerá tu nombre de usuario de ser mostrado en los resultados! Tus votos serán completamente anónimos si esto está habilitado."
},
"wyCustom": {
"error": {
Expand Down Expand Up @@ -81,7 +81,13 @@
"descID": "ID",
"descMsg": "Mensaje",
"descCat": "Categoría",
"descCont": "Contenido"
"descCont": "Contenido",
"descAccept": "Parece que no has añadido \"{type}\" al comienzo de tu texto. ¿Quieres que lo añada automáticamente?",
"descWYR": "Prefieres",
"descNHIE": "Nunca he",
"descWWYD": "Qué harías",
"footerDisable": "Este botón se desactivará en 30 segundos.",
"success": "¡Se ha añadido con éxito \"{type}\" al comienzo del texto!"
},
"embedRemove": {
"title": "¡Se eliminó con éxito ese mensaje Would You!"
Expand All @@ -97,7 +103,7 @@
"descCatNHIE": "**Categoría**: Nunca lo he hecho nunca",
"descCatWYR": "**Categoría**: ¿Podrías más bien",
"descCatTRUTH": "**Categoría**: Verdad",
"descCatDARE": "**Categoría**: Atrévete",
"descCatDARE": "**Categoría**: Reto",
"descCatWWYD": "**Categoría**: ¿Qué harías tú"
}
}
Expand Down Expand Up @@ -142,7 +148,7 @@
"Help": {
"embed": {
"title": "Información",
"description": "**Would You** es un bot de discordia creado para aumentar la actividad del servidor de discordia. Te permite jugar a **Verdad o reto**, **Preferirías**, **Más alto o más bajo**, **Nunca lo he hecho** y **Qué harías**.",
"description": "**Would You** es un bot de discord construido para aumentar la actividad del servidor. Te permite jugar **Verdad o Reto**, **Preferías**, **Mayor o Menor**, **Nunca he** y **Qué Harías**.",
"footer": "Would You",
"Fields": {
"name": "**Mis Comandos**",
Expand All @@ -157,7 +163,7 @@
},
"Vote": {
"embed": {
"title": "¡Votar ayuda **Would You** a ganar más usuarios, asegúrate de votar todos los días!",
"title": "¡Votar ayuda a **Would You** a ganar más popularidad entre los usuarios en discord! ¡Puedes votar cada 12 horas y apoyar al bot!",
"value": "Clica para votar",
"footer": "Would You"
}
Expand Down
16 changes: 11 additions & 5 deletions src/languages/fr_FR.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,13 @@
"descID": "ID",
"descMsg": "Message",
"descCat": "Catégorie",
"descCont": "Contenue"
"descCont": "Contenue",
"descAccept": "Il semble que vous n'ayez pas ajouté \"{type}\" au début de votre texte. Souhaitez-vous que je l'ajoute automatiquement ?",
"descWYR": "Préférez-vous",
"descNHIE": "Jamais je n'ai",
"descWWYD": "Que feriez-vous",
"footerDisable": "Ce bouton sera désactivé dans 30 secondes.",
"success": "L'ajout de \"{type}\" au début du texte a été effectué avec succès !"
},
"embedRemove": {
"title": "Vous avez supprimé ce message personnalisé avec succès !"
Expand All @@ -96,8 +102,8 @@
"title": "Messages Personnalisés Préférez-vous",
"descCatNHIE": "**Catégorie**: Je n'ai jamais",
"descCatWYR": "**Catégorie**: Préférez-vous",
"descCatTRUTH": "**Catégorie**: Vérité",
"descCatDARE": "**Catégorie**: Ose",
"descCatTRUTH": "**Catégorie** : Vérité",
"descCatDARE": "**Catégorie** : Action",
"descCatWWYD": "**Catégorie**: Que feriez-vous"
}
}
Expand Down Expand Up @@ -142,7 +148,7 @@
"Help": {
"embed": {
"title": "Information",
"description": "**Would You** est un bot discord conçu pour augmenter l'activité du serveur discord. Il te permet de jouer à **Truth or Dare**, **Would You Rather**, **Higher or Lower**, **Never Have I Ever** et **What Would You Do**.",
"description": "**Would You** est un bot discord conçu pour augmenter l'activité du serveur discord. Il vous permet de jouer à **Action ou Vérité**, **Préférez-vous**, **Plus ou moins**, **Je n'ai jamais** et **Que feriez-vous**.",
"footer": "Would You",
"Fields": {
"name": "**Mes commandes**",
Expand All @@ -157,7 +163,7 @@
},
"Vote": {
"embed": {
"title": "Voter aide **Would You** à gagner plus d'utilisateurs ! Assurez-vous de voter tous les jours !",
"title": "Le vote permet à **Would You** de gagner en popularité auprès des utilisateurs sur discord ! Vous pouvez voter toutes les 12 heures et soutenir le bot !",
"value": "Clique pour voter",
"footer": "Would You"
}
Expand Down
82 changes: 70 additions & 12 deletions src/util/generateText.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,120 @@
import WouldYou from "./wouldYou";

interface GuildDB {
language: string;
}

export function generateWYR(
client: WouldYou,
text: string,
id: string,
guilddb: GuildDB,
): object {
const wyr = /^(?!.*(?:would you rather)).*$/i;
const wyrRegexes: Record<string, RegExp> = {
"en_EN": /^(?!.*(?:would you rather)).*$/i,
"de_DE": /^(?!.*(?:würdest du eher)).*$/i,
"es_ES": /^(?!.*(?:preferirías)).*$/i,
"fr_FR": /^(?!.*(?:préfères-tu)).*$/i,
};

if (wyr.test(text)) {
const wyrMap: Record<string, string> = {
"en_EN": "Would you rather",
"de_DE": "Würdest du eher",
"es_ES": "Preferirías",
"fr_FR": "Préfères-tu",
};

const guildLanguage = guilddb.language as string;
const wyrRegexPattern = wyrRegexes[guildLanguage];
const responsePhrase = wyrMap[guildLanguage];

if (wyrRegexPattern.test(text.toLowerCase())) {
client.customAdd.set(id, {
type: "wouldyourather",
text: `Would you rather ${text}`,
text: `${responsePhrase} ${text}`,
});
return {
value: false,
type: "wouldyourather",
text: `Would you rather ${text}`,
text: `${responsePhrase} ${text}`,
};
} else {
return { value: true, type: "wouldyourather", text: text };
}
}


export function generateWWYD(
client: WouldYou,
text: string,
id: string,
guilddb: GuildDB,
): object {
const wwyd = /^(?!.*(?:what would you do)).*$/i;
const languageRegex: Record<string, RegExp> = {
"en_EN": /^(?!.*(?:what would you do)).*$/i,
"de_DE": /^(?!.*(?:was würdest du tun)).*$/i,
"es_ES": /^(?!.*(?:qué harías)).*$/i,
"fr_FR": /^(?!.*(?:que ferais-tu)).*$/i,
};

if (wwyd.test(text)) {
const languageMap: Record<string, string> = {
"en_EN": "What would you do",
"de_DE": "Was würdest du tun",
"es_ES": "Qué harías",
"fr_FR": "Que ferais-tu",
};

const guildLanguage = guilddb.language as string;
const languageRegexPattern = languageRegex[guildLanguage];
const responsePhrase = languageMap[guildLanguage];
if (languageRegexPattern.test(text.toLowerCase())) {
client.customAdd.set(id, {
type: "wwyd",
text: `What would you do ${text}`,
text: `${responsePhrase} ${text}`,
});
return { value: false, type: "wwyd", text: `What would you do ${text}` };
return { value: false, type: "wwyd", text: `${responsePhrase} ${text}` };
} else {
return { value: true, type: "wwyd", text: text };
}
}


export function generateNHIE(
client: WouldYou,
text: string,
id: string,
guilddb: GuildDB,
): object {
const nhie = /^(?!.*(?:never have i ever)).*$/i;
const nhieRegexes: Record<string, RegExp> = {
"en_EN": /^(?!.*(?:never have i ever)).*$/i,
"de_DE": /^(?!.*(?:niemals habe ich)).*$/i,
"es_ES": /^(?!.*(?:nunca he)).*$/i,
"fr_FR": /^(?!.*(?:jamais je)).*$/i,
};

const nhieMap: Record<string, string> = {
"en_EN": "Never have I ever",
"de_DE": "Niemals habe ich",
"es_ES": "Nunca he",
"fr_FR": "Jamais je",
};

if (nhie.test(text)) {
const guildLanguage = guilddb.language as string;
const nhieRegexPattern = nhieRegexes[guildLanguage];
const responsePhrase = nhieMap[guildLanguage];

if (nhieRegexPattern.test(text.toLowerCase())) {
client.customAdd.set(id, {
type: "neverhaveiever",
text: `Never have I ever ${text}`,
text: `${responsePhrase} ${text}`,
});
return {
value: false,
type: "neverhaveiever",
text: `Never have I ever ${text}`,
text: `${responsePhrase} ${text}`,
};
} else {
return { value: true, type: "neverhaveiever", text: text };
}
}

49 changes: 49 additions & 0 deletions src/util/promHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import express from "express";
import { Registry, Gauge } from "prom-client"
import WouldYou from "./wouldYou";

export default class prometheusClient {
private registry: Registry;
private serverGauge: Gauge;
private userGauge: Gauge;
private client: WouldYou;

constructor(client: WouldYou) {
this.client = client;
}

initialize() {
this.registry = new Registry();
this.serverGauge = new Gauge({
name: "server_count",
help: "The amount of servers the bot is in.",
registers: [this.registry],
});
this.userGauge = new Gauge({
name: "user_count",
help: "The amount of users the bot has.",
registers: [this.registry],
});

const app = express();

app.use(express.json());

// Expose Prometheus metrics endpoint
app.get("/metrics", async (req, res) => {
this.serverGauge.set(this.client.guilds.cache.size);
this.userGauge.set(this.client.guilds.cache
.reduce((a, b) => a + b.memberCount, 0));
res.end(await this.registry.metrics());
});

app.listen(3029, () => {
console.log("Prometheus metrics listening on port 3029");
});
}


getMetrics() {
return this.registry.metrics();
}
}
Loading

0 comments on commit 6dd05c1

Please sign in to comment.