Skip to content

Commit

Permalink
Fix formatting, other lint complaints. Also resolved warnings in d.ad…
Browse files Browse the repository at this point in the history
…min from console logs.
  • Loading branch information
theimperious1 committed Nov 10, 2024
1 parent 8763f7f commit 1a588cc
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 85 deletions.
2 changes: 1 addition & 1 deletion src/discord/commands/global/d.ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import {
import { SlashCommand } from '../../@types/commandDef';
import { embedTemplate } from '../../utils/embedTemplate';
import commandContext from '../../utils/context';
import aiChat, { aiModerate, handleAiMessageQueue } from '../../../global/commands/g.ai';
import { aiModerate, handleAiMessageQueue } from '../../../global/commands/g.ai';

/* TODO
* only direct @ message should trigger a response
Expand Down
12 changes: 6 additions & 6 deletions src/discord/commands/guild/d.admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ async function setAvatar(interaction: ChatInputCommandInteraction, avatarUrl: st
'Content-Type': 'application/json',
},
}).then(() => {
console.log('Avatar set successfully');
log.info(F, 'Avatar set successfully');
interaction.editReply('Avatar set successfully');
return true;
}).catch((error: Error) => {
console.error(`Error setting avatar: ${error.message}`);
log.error(F, `Error setting avatar: ${error.message}`);
interaction.editReply('Error setting avatar');
return false;
});
Expand All @@ -107,11 +107,11 @@ async function setBanner(interaction: ChatInputCommandInteraction, bannerUrl: st
'Content-Type': 'application/json',
},
}).then(() => {
console.log('Banner set successfully');
log.info(F, 'Banner set successfully');
interaction.editReply('Banner set successfully');
return true;
}).catch((error: Error) => {
console.error(`Error setting banner: ${error.message}`);
log.error(F, `Error setting banner: ${error.message}`);
interaction.editReply('Error setting banner');
return false;
});
Expand Down Expand Up @@ -206,9 +206,9 @@ async function overwriteUserData(
total_points: levelPoints,
},
});
console.log(`Update result: ${JSON.stringify(result)}`);
log.info(F, `Update result: ${JSON.stringify(result)}`);
} catch (error) {
console.error(`Error updating database: ${(error as Error).message}`);
log.error(F, `Error updating database: ${(error as Error).message}`);
}

await interaction.editReply(`User level and points updated for category ${category} to level ${level} with ${levelPoints} points.`);

Check warning on line 214 in src/discord/commands/guild/d.admin.ts

View workflow job for this annotation

GitHub Actions / Lint

This line has a length of 134. Maximum allowed is 120
Expand Down
174 changes: 96 additions & 78 deletions src/global/commands/g.ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,18 @@ const googleAi = new GoogleGenerativeAI(env.GEMINI_KEY);

type UserQueue = {
queue: {
aiPersona: ai_personas;
messages: { role: 'user'; content: string }[];
messageData: Message<boolean>;
attachmentInfo: {
url: string | null;
mimeType: string | null;
};
resolve: (value: {
response: string;
promptTokens: number;
completionTokens: number;
}) => void;
aiPersona: ai_personas;
messages: { role: 'user'; content: string }[];
messageData: Message<boolean>;
attachmentInfo: {
url: string | null;
mimeType: string | null;
};
resolve: (value: {
response: string;
promptTokens: number;
completionTokens: number;
}) => void;
}[];
isProcessing: boolean;
};
Expand Down Expand Up @@ -122,72 +122,6 @@ const aiFunctions = [
},
];

// Main function for aiChat to handle incoming messages and return a Promise with response data
export function handleAiMessageQueue(
aiPersona: ai_personas,
messages: { role: 'user'; content: string }[],
messageData: Message<boolean>,
attachmentInfo: { url: string | null; mimeType: string | null }
): Promise<{
response: string;
promptTokens: number;
completionTokens: number;
}> {
if (!userQueues.has(messageData.author.id)) {
userQueues.set(messageData.author.id, { queue: [], isProcessing: false });
}

const userQueue = userQueues.get(messageData.author.id)!;

// Push the new message data into the user's queue
return new Promise((resolve) => {
userQueue.queue.push({
aiPersona,
messages,
messageData,
attachmentInfo,
resolve
});

// If the user is not currently processing, start processing
if (!userQueue.isProcessing) {
processNextMessage(messageData.author.id);
}
});
}

// Function to process the next message in the user's queue
async function processNextMessage(userId: string) {
const userQueue = userQueues.get(userId);
if (!userQueue || userQueue.queue.length === 0) {
userQueue!.isProcessing = false;
return;
}

userQueue.isProcessing = true; // Mark as processing

// Get the next message in the queue
const { aiPersona, messages, messageData, attachmentInfo, resolve } = userQueue.queue.shift()!;

try {
// Call the aiChat function and destructure the needed response data
const { response, promptTokens, completionTokens } = await aiChat(
aiPersona,
messages,
messageData,
attachmentInfo
);

resolve({ response, promptTokens, completionTokens });
} catch (error) {
log.error(F, `Error processing message for user: ${userId} - error: ${error}`);
resolve({ response: "Error", promptTokens: 0, completionTokens: 0 });
} finally {
// Process the next message after this one is done
processNextMessage(userId);
}
}

export async function aiModerateReport(
message: string,
):Promise<ModerationCreateResponse> {
Expand Down Expand Up @@ -974,6 +908,90 @@ export default async function aiChat(
return openAiConversation(aiPersona, messages, messageData);
}

// Function to process the next message in the user's queue
async function processNextMessage(userId: string) {
const userQueue = userQueues.get(userId);

// If userQueue is null or undefined, exit the function immediately
if (!userQueue) return;

// If the queue is empty, reset isProcessing to false and exit
if (userQueue.queue.length === 0) {
userQueue.isProcessing = false;
return;
}

userQueue.isProcessing = true; // Mark as processing

// Ensure the queue has an item before destructuring
const nextMessage = userQueue.queue.shift();
if (!nextMessage) {
// Handle case where there’s no next message in the queue, if needed
return;
}

const {
aiPersona, messages, messageData, attachmentInfo, resolve,
} = nextMessage;

try {
// Call the aiChat function and destructure the needed response data
const { response, promptTokens, completionTokens } = await aiChat(
aiPersona,
messages,
messageData,
attachmentInfo,
);

resolve({ response, promptTokens, completionTokens });
} catch (error) {
log.error(F, `Error processing message for user: ${userId} - error: ${error}`);
resolve({ response: 'Error', promptTokens: 0, completionTokens: 0 });
} finally {
// Process the next message after this one is done
processNextMessage(userId);
}
}

// Main function for aiChat to handle incoming messages and return a Promise with response data
export function handleAiMessageQueue(
aiPersona: ai_personas,
messages: { role: 'user'; content: string }[],
messageData: Message<boolean>,
attachmentInfo: { url: string | null; mimeType: string | null },
): Promise<{
response: string;
promptTokens: number;
completionTokens: number;
}> {
if (!userQueues.has(messageData.author.id)) {
userQueues.set(messageData.author.id, { queue: [], isProcessing: false });
}

const userQueue = userQueues.get(messageData.author.id);

if (!userQueue) {
// Return a rejected promise if userQueue is undefined
return Promise.reject(new Error(`User queue could not be initialized for user ${messageData.author.id}`));
}

// Push the new message data into the user's queue
return new Promise(resolve => {
userQueue.queue.push({
aiPersona,
messages,
messageData,
attachmentInfo,
resolve,
});

// If the user is not currently processing, start processing
if (!userQueue.isProcessing) {
processNextMessage(messageData.author.id);
}
});
}

export async function aiFlairMod(
aiPersona:ai_personas,
messages: OpenAI.Chat.ChatCompletionMessageParam [],
Expand Down

0 comments on commit 1a588cc

Please sign in to comment.