Parse usernames for use in OpenAI api

also document the toOpenAIMssages.ts file
This commit is contained in:
Wroclaw 2023-03-18 02:06:49 +01:00
parent d877097517
commit 276d70efee
3 changed files with 62 additions and 1 deletions

View file

@ -1,8 +1,14 @@
import { ChatCompletionRequestMessage as OpenAIMessage } from "openai";
import { Collection, Message as DiscordMessage } from "discord.js";
import FoldToAscii from "fold-to-ascii";
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 {
let rvalue: string = message.cleanContent;
@ -24,6 +30,43 @@ export function formatMessage(message: DiscordMessage): string {
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
*/
export default function toOpenAIMessages(messages: Collection<string, DiscordMessage>): OpenAIMessage[] {
const rvalue: OpenAIMessage[] = [];
@ -35,7 +78,7 @@ export default function toOpenAIMessages(messages: Collection<string, DiscordMes
rvalue.push({
role: message.author.id == message.client.user.id ? "assistant" : "user",
content: formatMessage(message),
name: message.member?.displayName,
name: getAuthorUsername(message),
});
});