feat: Add Telegram bot integration and .env configuration
This commit is contained in:
1 parent
e9320e438f
commit
4b672efa41
6 files changed
+222
-58
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
+25
-51
@@ -1,13 +1,19 @@
|
||||
import dotenv from 'dotenv';
|
||||
import { Pipeline } from './models/pipeline';
|
||||
import { PipelineExecutor } from './pipelines/pipeline-executor';
|
||||
import { TelegramBot } from './bot/telegram-bot';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
async function main() {
|
||||
const telegramToken = process.env.TELEGRAM_BOT_TOKEN;
|
||||
const openAIApiKey = process.env.OPENAI_API_KEY;
|
||||
const mcpServerUrl =
|
||||
process.env.MCP_SERVER_URL || 'https://santiment-mcp.dev.mind-dev.com/sse';
|
||||
const mcpServerUrl = process.env.MCP_SERVER_URL;
|
||||
|
||||
if (!telegramToken) {
|
||||
console.error(
|
||||
'Ошибка: Переменная окружения TELEGRAM_BOT_TOKEN не установлена.',
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!openAIApiKey) {
|
||||
console.error(
|
||||
@@ -16,53 +22,21 @@ async function main() {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const pipelineExecutor = new PipelineExecutor(mcpServerUrl);
|
||||
|
||||
const testPipeline: Pipeline = {
|
||||
description: 'Тестовый пайплайн',
|
||||
systemPrompt:
|
||||
'Ты полезный ассистент, который всегда отвечает на русском языке.',
|
||||
steps: [
|
||||
{
|
||||
name: 'Приветствие',
|
||||
prompt: 'Скажи привет пользователю, его имя - {{username}}.',
|
||||
},
|
||||
{
|
||||
name: 'Использование инструмента',
|
||||
prompt:
|
||||
'Напиши какие инструменты тебе доступны? (Очень кратко напиши суть и входящие параметры).',
|
||||
},
|
||||
{
|
||||
name: 'Использование инструмента',
|
||||
prompt: 'Вызови **top_gainers** с pageSize=2 и покажи что получилось.',
|
||||
},
|
||||
{
|
||||
name: 'Итог',
|
||||
prompt:
|
||||
'Отлично, теперь давай подытожим всё что мы сделали, соберём информацию вместе и оформим её как telegram пост.',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const variables = {
|
||||
username: 'Вася',
|
||||
};
|
||||
|
||||
const systemPrompts = ['Отвечай кратко и по существу.'];
|
||||
|
||||
try {
|
||||
const results = await pipelineExecutor.executeChain({
|
||||
pipeline: testPipeline,
|
||||
variables: variables,
|
||||
systemPrompts: systemPrompts,
|
||||
openAIApiKey: openAIApiKey,
|
||||
});
|
||||
console.log('Результаты выполнения пайплайна:', results);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при выполнении пайплайна:', error);
|
||||
} finally {
|
||||
await pipelineExecutor.mcpToolsService.disconnect();
|
||||
if (!mcpServerUrl) {
|
||||
console.error(
|
||||
'Ошибка: Переменная окружения MCP_SERVER_URL не установлена.',
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Initialize and start the Telegram bot
|
||||
const bot = new TelegramBot(telegramToken, mcpServerUrl);
|
||||
bot.launch();
|
||||
|
||||
console.log('Бот запущен и готов к работе!');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
main().catch((error) => {
|
||||
console.error('Произошла ошибка:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in new issue
Block a user