import TelegramBot from "node-telegram-bot-api"; import dotenv from "dotenv"; import axios from "axios"; import FormData from 'form-data'; import fs from 'fs'; import { UserRepository } from "./user.repository.js"; dotenv.config(); const tokenTg = process.env.TOKEN_TG; const tokenAi = process.env.TOKEN_AI; const accessId = process.env.SECRET_ID; const bot = new TelegramBot(tokenTg, { polling: true }); console.log("Бот запущен..."); bot.onText(/\/info/, (msg)=>{ const message = `Информация о боте: \n '/start' - перезапускает чат, забывает контекст прошлого диалого \n '/toggleModel' - Выбор модели (еще не доступен)` const chatId = msg.chat.id bot.sendMessage(chatId, message) }) bot.onText(/\/armyan (.+)/, async(msg, match)=>{ const chatId = msg.chat.id; const textAfterCommand = match[1]; }) bot.onText(/\/start/, async(msg) => { const chatId = msg.chat.id; const chatType = msg.chat.type const user = msg.from try{ const createOrUpdateUser = await UserRepository.createOrUpdateUser({ telegramId: user.id, username: user.username, chatId: chatId }); }catch(err){ console.error('Ошибка при создании или обновлении пользователя:', err); } bot.sendMessage(chatId, `Чат перезапущен, тип чата ${chatType}`); }); bot.on('message', async(msg) => { const chatId = msg.chat.id; const user = msg.from console.log(user) console.log(msg) if (msg.text && msg.text.startsWith('/')) { return; } if (msg.photo) { bot.sendMessage(chatId, 'Красиво, но такое мне не надо', {reply_to_message_id: msg.message_id}); return; } if (msg.document) { bot.sendMessage(chatId, 'Такое мне не надо', {reply_to_message_id: msg.message_id}); return; } if (msg.from.is_bot){ bot.sendMessage(chatId, 'Пошел нахуй бот ебанный, не мешай слушать брата', {reply_to_message_id: msg.message_id}); return; } if (msg.voice ){ const fileId = msg.voice.file_id; const filePath = await bot.downloadFile(fileId, './voices'); const form = new FormData(); form.append('file', fs.createReadStream(filePath)); const response = await axios.post( 'http://10.8.1.2:3000/upload', form, { headers: form.getHeaders() } ); if(response.status === 200){ const recognizedText = response.data.text; bot.sendMessage(chatId, recognizedText, {reply_to_message_id: msg.message_id}); }else{ bot.sendMessage(chatId, 'Что-то пошло не так', {reply_to_message_id: msg.message_id}); } return; } if (msg.text && user.id === 5536333712){ console.log('Армянин, переключаем модель') const response = await switchToRussian(msg.text); bot.sendMessage(chatId, response.message, {reply_to_message_id: msg.message_id}); return; } if (msg.text && msg.chat.type === 'private') { //bot.sendMessage(chatId, `Ты написал: ${msg.text}`); try{ const last_msg_context = await UserRepository.getContext(user.id) || '' console.log('last_msg_context:', last_msg_context); if(last_msg_context === ''){ console.log('Новый пользователь, начинаем диалог с чистого листа'); const response = await getAIResponse(msg.text, null); bot.sendMessage(chatId, response.message); await UserRepository.updateContext(user.id, response.id); }else{ console.log('Продолжаем диалог, контекст найден'); const response = await getAIResponse(msg.text, last_msg_context); bot.sendMessage(chatId, response.message); await UserRepository.updateContext(user.id, response.id); } }catch(err){ console.error('Ошибка при обработке сообщения:', err); } return; } }); async function switchToRussian(message){ try{ const options = { method:'POST', url:`https://agent.timeweb.cloud/api/v1/cloud-ai/agents/${accessId}/call`, headers: { Authorization: `Bearer ${tokenAi}`, 'x-proxy-source': '', 'Content-Type': 'application/json' }, data:{ message: `Убери ошибки в тексте и поставь знаки препинания: "${message}". Если текст короткий или без явных ошибок ничего не делай и отвечай просто "Армянин молодец", особо не размышляй над содержимым текста, просто выполняй свою задачу. Так же делай рядом версию с переводом на армянский язык`, parent_message_id: '' } } const response = await axios.request(options); return response.data; }catch(err){ console.error('Ошибка при получении ответа от AI:', err); } } async function getAIResponse(message, context) { try{ const options = { method:'POST', url:`https://agent.timeweb.cloud/api/v1/cloud-ai/agents/${accessId}/call`, headers: { Authorization: `Bearer ${tokenAi}`, 'x-proxy-source': '', 'Content-Type': 'application/json' }, data:{ message: message, parent_message_id: context } } const response = await axios.request(options); return response.data; }catch(err){ console.error('Ошибка при получении ответа от AI:', err); } }