podklyuchis-k-moemu-alem-bot/bot.js

76 lines
2.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { Bot } = require("grammy");
const fetch = require("node-fetch"); // в node >=18 fetch есть, но оставляем на случай старой версии
const bot = new Bot(process.env.BOT_TOKEN);
// ----- функции для работы с Alem -----
async function createAlemSession() {
const url = `${process.env.ALEM_BASE_URL}/api/v1/open-api/conversation`;
const resp = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + process.env.ALEM_API_KEY,
},
body: JSON.stringify({
template_id: process.env.ALEM_TEMPLATE_ID,
title: "TelegramBot",
user_id: "vibe42_user",
}),
});
if (!resp.ok) throw new Error("Alem create: " + resp.status);
const data = await resp.json();
return data?.data?.session_id;
}
async function askAlem(sessionId, prompt) {
const url = `${process.env.ALEM_BASE_URL}/api/v1/open-api/conversation/${sessionId}/send`;
const resp = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + process.env.ALEM_API_KEY,
},
body: JSON.stringify({
content: prompt,
user_id: "vibe42_user",
model_api_key: process.env.ALEM_API_KEY,
}),
});
if (!resp.ok) throw new Error("Alem ask: " + resp.status);
const raw = await resp.text(); // SSE поток
let answer = null;
for (const line of raw.split("\n")) {
const s = line.trim();
if (!s.startsWith("data:")) continue;
const payload = s.slice(5).trim();
if (!payload || payload === "[DONE]") continue;
try {
const ev = JSON.parse(payload);
if (ev?.detail?.full_content) answer = ev.detail.full_content;
} catch (e) {}
}
return answer || "Нет ответа от Alem";
}
async function alembotReply(text) {
const sid = await createAlemSession();
return await askAlem(sid, text);
}
// -------------------------------------
bot.command("start", (ctx) => ctx.reply("Привет! Я бот, отвечаю через Alem. Пиши любое сообщение."));
bot.on("message:text", async (ctx) => {
try {
const reply = await alembotReply(ctx.message.text);
await ctx.reply(reply);
} catch (e) {
console.error(e);
await ctx.reply("Ошибка при обращении к Alem.");
}
});
bot.start();
console.log("Бот запущен (longpolling)");