GPTcord/src/index.ts

72 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-03-14 21:16:54 +01:00
import DiscordApi from "discord.js";
import { Configuration as OpenAIApiConfiguration, OpenAIApi } from "openai";
import config from "./config.json";
import toOpenAIMessages from "./toOpenAIMessages";
import Moderation from "./moderation";
2023-03-14 21:16:54 +01:00
const discord = new DiscordApi.Client({
intents: [
DiscordApi.GatewayIntentBits.Guilds,
DiscordApi.GatewayIntentBits.GuildMessages,
DiscordApi.GatewayIntentBits.MessageContent,
]
});
export const openai = new OpenAIApi(new OpenAIApiConfiguration({
2023-03-14 21:16:54 +01:00
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));
2023-03-14 21:16:54 +01:00
message.channel.sendTyping();
const answer = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: toOpenAIMessages(messages),
max_tokens: 168
});
const response = message.reply({
2023-03-14 21:16:54 +01:00
content: answer.data.choices[0].message?.content,
allowedMentions: {
repliedUser: false,
}
});
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}`);
}
Moderation.checkMessage(await response);
2023-03-14 21:16:54 +01:00
} catch (e) {
console.error(e);
message.reply({
embeds: [{
color: 0xff0000,
description: "Something bad happened! :frown:"
}],
allowedMentions: {
repliedUser: false,
}
});
}
});
discord.login(config.tokens.Discord);