57 lines
1.6 KiB
JavaScript
57 lines
1.6 KiB
JavaScript
import { Bot } from "grammy";
|
|
import express from "express";
|
|
|
|
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
|
|
const DEEPAGENTS_URL = process.env.DEEPAGENTS_URL || "http://deepagents:8000";
|
|
|
|
const bot = new Bot(TELEGRAM_BOT_TOKEN);
|
|
|
|
// Forward all text messages to the unified gateway /message endpoint
|
|
bot.on("message:text", (ctx) => {
|
|
const text = ctx.message.text;
|
|
const chat_id = String(ctx.chat.id);
|
|
|
|
console.log(`[grammy] message from ${chat_id}: ${text.slice(0, 80)}`);
|
|
|
|
fetch(`${DEEPAGENTS_URL}/message`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
text,
|
|
session_id: `tg-${chat_id}`,
|
|
channel: "telegram",
|
|
user_id: chat_id,
|
|
}),
|
|
}).catch((err) => console.error("[grammy] error forwarding to deepagents:", err));
|
|
});
|
|
|
|
// HTTP server — delivers replies from the gateway back to Telegram
|
|
const app = express();
|
|
app.use(express.json());
|
|
|
|
app.post("/send", async (req, res) => {
|
|
const { chat_id, text } = req.body;
|
|
if (!chat_id || !text) {
|
|
res.status(400).json({ error: "chat_id and text required" });
|
|
return;
|
|
}
|
|
try {
|
|
await bot.api.sendMessage(chat_id, text);
|
|
console.log(`[grammy] sent to ${chat_id}: ${text.slice(0, 60)}`);
|
|
res.json({ ok: true });
|
|
} catch (err) {
|
|
console.error(`[grammy] send error to ${chat_id}:`, err.message);
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
|
|
app.get("/health", (_req, res) => res.json({ ok: true }));
|
|
|
|
app.listen(3001, () => {
|
|
console.log("[grammy] HTTP server listening on port 3001");
|
|
});
|
|
|
|
bot.start({
|
|
onStart: (info) => console.log(`[grammy] bot @${info.username} started`),
|
|
});
|