Refactor out the common error handling in moderation
This commit is contained in:
parent
5a116b0531
commit
853bf183ee
2 changed files with 30 additions and 20 deletions
|
@ -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) {
|
||||
|
|
|
@ -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,13 +28,13 @@ export default class Moderation {
|
|||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const answer = await openai.createModeration({
|
||||
input: await formatRequestOrResponse(message),
|
||||
});
|
||||
|
||||
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 */ });
|
||||
}
|
||||
|
@ -40,11 +45,16 @@ export default class Moderation {
|
|||
|
||||
return flagged;
|
||||
}
|
||||
catch (e) {
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
|
|
Loading…
Reference in a new issue