Im having a bit of troubles trying to integrate openai api into my discord bot. I really simplified my prompt now but it still isnt working i dont know what im doing wrong.
Im getting the Error: TypeError: Cannot read properties of undefined (reading ‘0’) in line 51, which is the line containing completion.choices[0].text;
Here is the code:
const { Client, IntentsBitField } = require('discord.js');
require('dotenv').config();
const { Configuration, OpenAIApi } = require("openai");
const fetch = require('node-fetch');
const axios = require('axios');
// Set up the Discord client
const client = new Client({
intents: [
IntentsBitField.Flags.Guilds,
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent,
IntentsBitField.Flags.GuildMembers,
]
});
// Set up the OpenAI API key and model ID
const configuration = new Configuration({
apiKey: process.env.Openai_API_Key,
});
const openai = new OpenAIApi(configuration);
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
};
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (!message.content.startsWith('!ask')) return;
const question = message.content.slice(5);
const websiteLink = process.env.WEBSITE_LINK;
try {
const websiteHtml = await fetch(websiteLink, { headers }).then((res) => res.text());
const completion = await openai.createCompletion({
model: "text-curie-001",
prompt: "Say this is a test ",
max_tokens: 20,
n: 1,
stop: "\n"
});
const answer = completion.choices[0].text;
message.reply(answer);
} catch (error) {
console.error('Error:', error);
message.reply('Sorry, I could not get an answer at this time.');
}
});
client.login(process.env.DISCORD_BOT_TOKEN);