GPTcord/src/toOpenAIMessages.ts

87 lines
2.7 KiB
TypeScript
Raw Normal View History

2023-03-14 21:16:54 +01:00
import { ChatCompletionRequestMessage as OpenAIMessage } from "openai";
import { Collection, Message as DiscordMessage } from "discord.js";
import FoldToAscii from "fold-to-ascii";
2023-03-14 21:16:54 +01:00
import config from "./config.json";
/**
* Formats the message to use as a message content in OpenAI api
* @param message the message to format
* @returns the formatted message
*/
export function formatMessage(message: DiscordMessage): string {
2023-03-14 21:16:54 +01:00
let rvalue: string = message.cleanContent;
for (const attachment of message.attachments) {
rvalue += ` [Attachment: ${attachment[1].name}`;
rvalue += attachment[1].description ? ` - ${attachment[1].description}` : "";
rvalue += "]";
}
for (const embed of message.embeds) {
rvalue += ` [Embed:`;
rvalue += embed.title ? ` ${embed.title}` : "";
rvalue += embed.author ? ` by ${embed.author.name}` : "";
rvalue += (embed.title || embed.author) && embed.description ? " -": "";
2023-03-14 21:16:54 +01:00
rvalue += embed.description ? ` ${embed.description}` : "";
rvalue += "]";
}
return rvalue;
}
/**
* Formats name to be accepted in OpenAI api
* @param name the name to format
* @returns formatted name
*/
function formatName(name: string): string {
// replace all characters to ascii equivelant
return FoldToAscii.foldReplacing(name)
// White spaces are not allowed
.replace(" ", "_")
// remove trailing '-_' characters
.replace(/^[-_]+|[-_]+$/g, "")
// remove duplicated '-_' characters
.replace(/([-_])*/g, "")
// replace characters that are not accepted by api with '?'
.replace(/[^a-zA-Z0-9_-]/g, "?");
}
/**
* Gets the name of the author of the message, formatted to be used in OpenAI api
* @param message the message to get the author name
* @returns the proper author name of the message
*/
function getAuthorUsername(message: DiscordMessage): string {
if (message.member) {
const name = formatName(message.member.displayName);
if (name.length >= 3) return name;
}
const name = formatName(message.author.username);
return name;
}
/**
* Converts the Collection of Discord Messages to array of OpenAI Messages
* @param messages the collection to convert
* @returns the converted messages
*/
2023-03-14 21:16:54 +01:00
export default function toOpenAIMessages(messages: Collection<string, DiscordMessage>): OpenAIMessage[] {
const rvalue: OpenAIMessage[] = [];
rvalue.push({ role: "system", content: config.systemPrompt});
messages
.sort((a, b) => a.createdTimestamp - b.createdTimestamp)
.each(message => {
rvalue.push({
role: message.author.id == message.client.user.id ? "assistant" : "user",
content: formatMessage(message),
name: getAuthorUsername(message),
2023-03-14 21:16:54 +01:00
});
});
return rvalue;
}