Refactor out the common error handling in moderation

This commit is contained in:
Wroclaw 2023-07-31 20:36:49 +02:00
parent 5a116b0531
commit 853bf183ee
2 changed files with 30 additions and 20 deletions

View file

@ -231,7 +231,7 @@ async function executeFromQueue(channel: string) {
messages = messages.filter(m => message.createdTimestamp - m.createdTimestamp < config.limits.time );
messages.forEach(m => { Moderation.checkMessage(m); });
messages.forEach(m => { Moderation.checkMessageNoReturn(m); });
if (message instanceof DiscordApi.Message) {
await message.channel.sendTyping();
@ -286,7 +286,7 @@ async function executeFromQueue(channel: string) {
for (const i of answerMessagesContent) {
const response = requestReply(message, {content: i}, {allowedMentions: { repliedUser: false }});
await response.then(rval => Moderation.checkMessage(rval));
await response.then(rval => Moderation.checkMessageNoReturn(rval));
}
}
} catch (e) {

View file

@ -9,6 +9,11 @@ export default class Moderation {
private static cache = new Collection<string, boolean>();
private static worker: NodeJS.Timeout | null = null;
/**
* Checks the message in the OpenAI Moderation API
* @param message The message to check
* @returns if the message fails the moderation (true) or not (false)
*/
public static async checkMessage(message: Message | InteractionResponse): Promise<boolean> {
if (this.cache.has(message.id)) {
return this.cache.get(message.id) as boolean;
@ -23,28 +28,33 @@ export default class Moderation {
}
}
try {
const answer = await openai.createModeration({
input: await formatRequestOrResponse(message),
});
const answer = await openai.createModeration({
input: await formatRequestOrResponse(message),
});
const flagged = answer.data.results[0].flagged;
this.cache.set(message.id, flagged);
if (flagged) if (message instanceof Message) {
message.react("⚠").catch(() => { /* GRACEFAIL: We don't inform the enduser then */ });
}
else {
const channelMessage = await message.fetch();
channelMessage.react("⚠").catch(() => { /* GRACEFAIL: We don't inform the enduser then */ });
}
return flagged;
const flagged = answer.data.results[0].flagged;
this.cache.set(message.id, flagged);
// FIXME: These next 7 lines does not belong there and should be refactored out.
if (flagged) if (message instanceof Message) {
message.react("⚠").catch(() => { /* GRACEFAIL: We don't inform the enduser then */ });
}
catch (e) {
else {
const channelMessage = await message.fetch();
channelMessage.react("⚠").catch(() => { /* GRACEFAIL: We don't inform the enduser then */ });
}
return flagged;
}
/**
* Checks the message in the OpenAI ModerationAPI
* @param message The message to check
*/
public static checkMessageNoReturn(message: Message | InteractionResponse) {
this.checkMessage(message).catch(e => {
console.error(`Error occured while handling moderation request (${(e as object).constructor.name}):`);
console.error(e);
return false;
}
});
}
public static removeExpiredCacheEntries() {