I have a paid account and use GPT-4o and want to create API with NodeJS
const TelegramBot = require('node-telegram-bot-api');
const OpenAI = require('openai');
require('dotenv').config();
const telegramToken = process.env.TELEGRAM_TOKEN;
const openaiApiKey = process.env.OPENAI_API_KEY;
// Initialize the Telegram bot
const bot = new TelegramBot(telegramToken, { polling: true });
// Initialize OpenAI API
const openai = new OpenAI({
apiKey: openaiApiKey,
});
// Handle the /start command
bot.onText(/\/start/, (msg) => {
bot.sendMessage(msg.chat.id, "Hi! I am your ChatGPT bot. How can I assist you today?");
});
// Code Snippet Assistance
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
const userMessage = msg.text;
try {
let response;
// Check if the message contains code (indicated by backticks for code blocks)
if (userMessage.startsWith('```') && userMessage.endsWith('```')) {
response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a helpful assistant specializing in code." },
{ role: "user", content: `Please review or provide suggestions for this code:\n${userMessage}` }
],
});
} else {
// Regular message handling
response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: userMessage }],
});
}
const botReply = response.choices[0].message.content;
bot.sendMessage(chatId, botReply);
} catch (error) {
console.error('Error with OpenAI API:', error);
bot.sendMessage(chatId, 'Sorry, I am having trouble connecting to the service right now. Please try again later.');
}
});
// Code Review Assistance
bot.onText(/\/reviewcode (.+)/, async (msg, match) => {
const chatId = msg.chat.id;
const codeToReview = match[1];
try {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are an expert at reviewing code for best practices and security vulnerabilities." },
{ role: "user", content: `Please review the following code:\n${codeToReview}` }
],
});
const botReply = response.choices[0].message.content;
bot.sendMessage(chatId, botReply);
} catch (error) {
console.error('Error with OpenAI API:', error);
bot.sendMessage(chatId, 'Sorry, I am having trouble reviewing the code right now. Please try again later.');
}
});
console.log("Bot is running...");
I created an API default Project but I always see 429 errors even I have 5$ and try all models the same error