telegram-ai-bot / server.js
Snapspark's picture
Update server.js
bb0fb92 verified
Raw
History Blame Contribute Delete
2.62 kB
const TelegramBot = require("node-telegram-bot-api");
const axios = require("axios");
const TOKEN = process.env.BOT_TOKEN;
const GROQ_API = process.env.GROQ_API;
const SUPABASE_URL = process.env.SUPABASE_URL;
const SUPABASE_KEY = process.env.SUPABASE_KEY;
const bot = new TelegramBot(TOKEN, {
polling: {
interval: 300,
autoStart: true,
params: {
timeout: 10
}
}
});
console.log("CEO AI Started");
async function saveMemory(role, content) {
try {
await axios.post(
`${SUPABASE_URL}/rest/v1/Memory`,
{
role,
content
},
{
headers: {
apikey: SUPABASE_KEY,
Authorization: `Bearer ${SUPABASE_KEY}`,
"Content-Type": "application/json",
Prefer: "return=minimal"
}
}
);
} catch (err) {
console.log("Memory Save Error:", err.message);
}
}
async function getMemory() {
try {
const res = await axios.get(
`${SUPABASE_URL}/rest/v1/memory?select=role,content&order=id.desc&limit=10`,
{
headers: {
apikey: SUPABASE_KEY,
Authorization: `Bearer ${SUPABASE_KEY}`
}
}
);
return res.data.reverse();
} catch (err) {
console.log("Memory Load Error:", err.message);
return [];
}
}
bot.on("message", async (msg) => {
const chatId = msg.chat.id;
const text = msg.text;
if (!text) return;
bot.sendChatAction(chatId, "typing");
await saveMemory("user", text);
const memory = await getMemory();
const history = memory.map(m =>
`${m.role}: ${m.content}`
).join("\n");
try {
const response = await axios.post(
"https://api.groq.com/openai/v1/chat/completions",
{
model: "llama-3.1-8b-instant",
messages: [
{
role: "system",
content:
"You are a powerful CEO AI assistant managing business growth, automation, AI agents, content systems, apps, websites, YouTube automation, blogging, and online business infrastructure."
},
{
role: "user",
content: history + `\nUser: ${text}`
}
]
},
{
headers: {
Authorization: `Bearer ${GROQ_API}`,
"Content-Type": "application/json"
}
}
);
const reply =
response.data.choices[0].message.content;
await saveMemory("assistant", reply);
bot.sendMessage(chatId, reply);
} catch (err) {
console.log(err.response?.data || err.message);
bot.sendMessage(
chatId,
"AI system error. Check logs."
);
}
});