Wroclaw
4f4b708ba5
Now we can write code inside config, which allows us to send current time to the OpenAI api inside system message! Example config updated accordingly
78 lines
2.4 KiB
TypeScript
78 lines
2.4 KiB
TypeScript
import DiscordApi from "discord.js";
|
|
import { Configuration as OpenAIApiConfiguration, OpenAIApi } from "openai";
|
|
|
|
import config from "./config";
|
|
import toOpenAIMessages from "./toOpenAIMessages";
|
|
import Moderation from "./moderation";
|
|
|
|
const discord = new DiscordApi.Client({
|
|
intents: [
|
|
DiscordApi.GatewayIntentBits.Guilds,
|
|
DiscordApi.GatewayIntentBits.GuildMessages,
|
|
DiscordApi.GatewayIntentBits.MessageContent,
|
|
]
|
|
});
|
|
|
|
export const openai = new OpenAIApi(new OpenAIApiConfiguration({
|
|
apiKey: config.tokens.OpenAI
|
|
}));
|
|
|
|
discord.on("ready", async event => {
|
|
console.log(`Connected to Discord as ${event.user.tag} (${event.user.id})`);
|
|
});
|
|
|
|
discord.on("messageCreate", async message => {
|
|
if (message.author.bot) return;
|
|
if (!message.mentions.has(message.client.user)) return;
|
|
|
|
try {
|
|
let messages: DiscordApi.Collection<string, DiscordApi.Message> = await message.channel.messages.fetch({ limit: 50, cache: false });
|
|
|
|
messages = messages.filter(m => message.createdTimestamp - m.createdTimestamp < 1000*60*60 );
|
|
|
|
messages.forEach(m => Moderation.checkMessage(m));
|
|
|
|
message.channel.sendTyping();
|
|
const answer = await openai.createChatCompletion({
|
|
...config.chatCompletionConfig,
|
|
messages: toOpenAIMessages(messages),
|
|
});
|
|
|
|
const usage = answer.data.usage;
|
|
if (usage != undefined) {
|
|
const channelName: string = message.inGuild() ? `${message.channel.name} (${message.guild.name})` : `@${message.author.tag}`;
|
|
console.log(`Used ${usage.total_tokens} (${usage.prompt_tokens} + ${usage.completion_tokens}) tokens for ${message.author.tag} (${message.author.id}) in #${channelName}`);
|
|
}
|
|
|
|
const answerContent = answer.data.choices[0].message?.content;
|
|
|
|
if (answerContent != undefined && answerContent != "") {
|
|
const response = message.reply({
|
|
content: answerContent,
|
|
allowedMentions: {
|
|
repliedUser: false,
|
|
}
|
|
});
|
|
|
|
Moderation.checkMessage(await response);
|
|
}
|
|
else {
|
|
message.react("😶");
|
|
}
|
|
} catch (e) {
|
|
console.error(`Error ocurred while handling chat completion request (${(e as object).constructor.name}):`);
|
|
console.error(e);
|
|
|
|
message.reply({
|
|
embeds: [{
|
|
color: 0xff0000,
|
|
description: "Something bad happened! :frowning:"
|
|
}],
|
|
allowedMentions: {
|
|
repliedUser: false,
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
discord.login(config.tokens.Discord);
|