import DiscordApi from "discord.js"; import { Configuration as OpenAIApiConfiguration, OpenAIApi } from "openai"; import config from "./config.json"; import toOpenAIMessages from "./toOpenAIMessages"; const discord = new DiscordApi.Client({ intents: [ DiscordApi.GatewayIntentBits.Guilds, DiscordApi.GatewayIntentBits.GuildMessages, DiscordApi.GatewayIntentBits.MessageContent, ] }); 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 = await message.channel.messages.fetch({ limit: 50, cache: false }); messages = messages.filter(m => message.createdTimestamp - m.createdTimestamp < 1000*60*60 ); message.channel.sendTyping(); const answer = await openai.createChatCompletion({ model: "gpt-3.5-turbo", messages: toOpenAIMessages(messages), max_tokens: 168 }); message.reply({ 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}`); } } catch (e) { console.error(e); message.reply({ embeds: [{ color: 0xff0000, description: "Something bad happened! :frown:" }], allowedMentions: { repliedUser: false, } }); } }); discord.login(config.tokens.Discord);