feat: Add Telegram bot integration and .env configuration

This commit is contained in:
uxname committed 2025-05-24 16:55:42 +03:00
1 parent e9320e438f
commit 4b672efa41
6 files changed
+222 -58

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
import { Telegraf } from 'telegraf';
import { Pipeline } from '../models/pipeline';
import { PipelineExecutor } from '../pipelines/pipeline-executor';
export class TelegramBot {
private bot: Telegraf;
private pipelineExecutor: PipelineExecutor;
private activePipelines: Map<number, Pipeline> = new Map();
constructor(token: string, mcpServerUrl: string) {
this.bot = new Telegraf(token);
this.pipelineExecutor = new PipelineExecutor(mcpServerUrl);
this.setupHandlers();
}
private setupHandlers(): void {
// Start command
this.bot.start((ctx) => {
ctx.reply(
'Привет! Я бот для работы с AI пайплайнами. Просто отправь мне сообщение, и я обработаю его через пайплайн.',
);
});
// Handle text messages
this.bot.on('text', async (ctx) => {
const chatId = ctx.chat.id;
const userMessage = ctx.message.text;
try {
// Create a simple pipeline with the user's message as the first step
const userPipeline: Pipeline = {
description: 'User message processing pipeline',
systemPrompt:
'Ты полезный ассистент, который всегда отвечает на русском языке. Анализируй сообщения пользователя и давай развернутые ответы.',
steps: [
{
name: 'Start',
prompt: 'Всегда начинай своё сообщение со слов: Мой господин,',
},
{
name: 'Обработка сообщения',
prompt: userMessage,
},
],
};
// Store the pipeline for this chat
this.activePipelines.set(chatId, userPipeline);
// Show typing action
await ctx.sendChatAction('typing');
// Execute the pipeline
const results = await this.pipelineExecutor.executeChain({
pipeline: userPipeline,
variables: {},
systemPrompts: [],
openAIApiKey: process.env.OPENAI_API_KEY || '',
});
// Send the result back to the user
const lastResult = results[results.length - 1];
if (lastResult) {
await ctx.reply(lastResult);
} else {
await ctx.reply(
'Не удалось обработать запрос. Пожалуйста, попробуйте еще раз.',
);
}
} catch (error) {
console.error('Error processing message:', error);
await ctx.reply('Произошла ошибка при обработке вашего запроса.');
}
});
// Error handling
this.bot.catch((error: unknown) => {
const errorMessage =
error instanceof Error ? error.message : 'Unknown error';
console.error('Telegram bot error:', errorMessage);
});
}
public launch(): void {
this.bot.launch();
console.log('Telegram bot started');
// Enable graceful stop
process.once('SIGINT', () => {
this.bot.stop('SIGINT');
this.cleanup();
});
process.once('SIGTERM', () => {
this.bot.stop('SIGTERM');
this.cleanup();
});
}
private async cleanup(): Promise<void> {
// Cleanup resources
await this.pipelineExecutor.mcpToolsService.disconnect();
}
}