I’ve made bot for my discord server and tried to make it use ChatGPT. After sending message on chat it only types error and in terminal it says error no.429
const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
const OPENAI_API_KEY = 'My code';
const DISCORD_BOT_TOKEN = 'My code';
const MIN_DELAY_BETWEEN_REQUESTS = 10000; // adjust this based on your rate limits
let lastRequestTime = 0;
const waitForRateLimit = () => {
const now = Date.now();
const delay = Math.max(0, MIN_DELAY_BETWEEN_REQUESTS - (now - lastRequestTime));
return new Promise(resolve => setTimeout(resolve, delay));
};
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
await waitForRateLimit(); // wait for appropriate delay
lastRequestTime = Date.now();
try {
const response = await axios.post('https://api.openai.com/v1/chat/completions', {
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: message.content }]
}, {
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json'
}
});
const botReply = response.data.choices[0].message.content;
message.reply(botReply);
} catch (error) {
if (error.response?.status === 429) {
message.reply('I am receiving too many requests, please try again later.');
} else {
message.reply('An error occurred. Please try again.');
}
console.error('Error with OpenAI API:', error);
}
});
client.login(DISCORD_BOT_TOKEN);
I tried to add delay for 3, 5 and even 10 seconds