import { Message, TextChannel } from 'discord.js'; import { DyFM_Error } from '@futdevpro/fsm-dynamo'; import { DyFM_AI_Message, DyFM_AI_MessageRole } from '@futdevpro/fsm-dynamo/ai'; import { DyNTS_DiAs_global_settings } from './dias-global-settings.const'; export class DyNTS_DiAs_Util { static convertDiscordMessagesToOAIConversation( set: { messages: Message[], botClientId: string, botDisplayName: string, issuer: string, } ): DyFM_AI_Message[] { return set.messages.map(message => { if ( (message?.author && (message.author.bot || message.author.id === set.botClientId || message.author.displayName === set.botDisplayName)) ) { if (DyNTS_DiAs_global_settings.userTranslationFlags.some( flag => message.content.includes(flag) )) { return { role: DyFM_AI_MessageRole.user, content: message.content, }; } else { return { role: DyFM_AI_MessageRole.assistant, content: message.content, }; } } else { return { role: DyFM_AI_MessageRole.user, content: message.content, }; } }) } static async gatherMessagesAsOAIConversation( set: { message: Message, botClientId: string, botDisplayName: string, issuer: string, skipFlags?: string[], } ): Promise { const messages: Message[] = await this.gatherMessagesForMessage(set/* message, botClientId, issuer, skipFlags */); return DyNTS_DiAs_Util.convertDiscordMessagesToOAIConversation({ messages: messages, botClientId: set.botClientId, botDisplayName: set.botDisplayName, issuer: set.issuer, }); } static async gatherMessagesForMessage( set: { message: Message, botClientId: string, issuer: string, skipFlags?: string[], } ): Promise { if (!set.message.channel.isTextBased()) { throw new Error('Message channel is not a text channel!'); } return this.gatherMessages({ channel: set.message.channel as TextChannel, userId: set.message.author.id, botClientId: set.botClientId, skipFlags: set.skipFlags, issuer: set.issuer, }); } static async gatherMessages( set: { /* message: Message, */ channel: TextChannel, userId: string, botClientId: string, skipFlags?: string[], limit?: number, issuer: string, } ): Promise { try { if (!set.channel.isTextBased()) { throw new Error('Message channel is not a text channel!'); } const messages: Message[] = await set.channel.messages.fetch({ limit: set.limit ?? 100, }).then( messages => { if (set.skipFlags) { messages = messages.filter( msg => !set.skipFlags.some(flag => msg.content.includes(flag)) ) } return messages.map(msg => msg) } ); if (messages.some(msg => ![ set.botClientId, set.userId ].includes(msg.author.id))) { messages.forEach(msg => { msg.content = `**${msg.author.displayName}** ${msg.content}`; }); } return messages; } catch (error) { throw new DyFM_Error({ errorCode: 'DIA-DU-GM0', error: error, //...this.getDefaultErrorSettings('gatherMessages', error, set.issuer), }); } } }