Below is the JavaScript Code used to build the Discord Open Ai Chat Bot!
require('dotenv/config'); const { Client, IntentsBitField } = require('discord.js'); const OpenAI = require('openai'); // Import the OpenAI class directly // All Intents const client = new Client({ intents: [ IntentsBitField.Flags.Guilds, IntentsBitField.Flags.GuildMembers, IntentsBitField.Flags.GuildMessages, IntentsBitField.Flags.MessageContent, ], }); // Client on and OpenAI connection client.on('ready', (c) => { console.log('The Bot is Online'); }); // Initialize OpenAI API const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, // Pass the API key directly }); client.on('messageCreate', async (message) => { // Ignore messages from the bot itself if (message.author.bot) return; // Log message contents console.log(`Message from ${message.author.tag}: ${message.content}`); // Create conversation log let conversationLog = [{ role: 'system', content: "You are a friendly Chat bot!" }]; // Add user message to conversation log conversationLog.push({ role: 'user', content: message.content, }); // Send typing indicator await message.channel.sendTyping(); try { // Get response from OpenAI const response = await openai.chat.completions.create({ model: "gpt-3.5-turbo", messages: conversationLog, }); // Reply with the generated message const reply = response.choices[0].message.content; await message.reply(reply); // Log the reply console.log(`Bot replied: ${reply}`); } catch (error) { console.error('Error generating response:', error); await message.reply("Sorry, I encountered an error while processing your request."); } }); // Log in to Discord client.login(process.env.TOKEN);