From 8e34ec72c68062af7883ca6037b207bc4a7c51a9 Mon Sep 17 00:00:00 2001 From: devmhand Date: Mon, 26 Jan 2026 17:53:36 +0400 Subject: [PATCH] update proj --- bot.js | 67 ++++++++++++++++++++++++++++++++++++++++------ db.js | 16 +++++++++++ example.env | 7 ++++- package.json | 6 +++-- user.repository.js | 53 ++++++++++++++++++++++++++++++++++++ 5 files changed, 138 insertions(+), 11 deletions(-) create mode 100644 db.js create mode 100644 user.repository.js diff --git a/bot.js b/bot.js index 0b927f7..66ac1c2 100644 --- a/bot.js +++ b/bot.js @@ -1,16 +1,18 @@ -const TelegramBot = require('node-telegram-bot-api'); -require('dotenv').config() +import TelegramBot from "node-telegram-bot-api"; +import dotenv from "dotenv"; +import axios from "axios"; -const axios = require('axios') +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('Бот запущен...'); +console.log("Бот запущен..."); bot.onText(/\/info/, (msg)=>{ @@ -23,14 +25,24 @@ bot.onText(/\/info/, (msg)=>{ }) -bot.onText(/\/start/, (msg) => { +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', (msg) => { +bot.on('message', async(msg) => { const chatId = msg.chat.id; const user = msg.from @@ -50,7 +62,46 @@ bot.on('message', (msg) => { } if (msg.text) { - bot.sendMessage(chatId, `Ты написал: ${msg.text}`); + //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 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); + } +} diff --git a/db.js b/db.js new file mode 100644 index 0000000..93bbff5 --- /dev/null +++ b/db.js @@ -0,0 +1,16 @@ +import pg from "pg"; +const { Pool } = pg; +import dotenv from "dotenv"; + +dotenv.config(); + +export const pool = new Pool({ + user: process.env.DATABASE_USER, + host: process.env.DATABASE_URL, + database: process.env.DATABASE_NAME, + password: process.env.DATABASE_PASSWORD, + port: 5432, + max: 10, + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 5000 +}); diff --git a/example.env b/example.env index f111874..81dea95 100644 --- a/example.env +++ b/example.env @@ -1,3 +1,8 @@ TOKEN_TG = TOKEN_AI = -SECRET_ID = \ No newline at end of file +SECRET_ID = +DATABASE_TABLE = +DATABASE_NAME = +DATABASE_URL = +DATABASE_USER = +DATABASE_PASSWORD = \ No newline at end of file diff --git a/package.json b/package.json index 8b4b92d..1509afa 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,8 @@ "dependencies": { "axios": "^1.13.2", "dotenv": "^17.2.3", - "node-telegram-bot-api": "^0.67.0" - } + "node-telegram-bot-api": "^0.67.0", + "pg": "^8.17.2" + }, + "type": "module" } diff --git a/user.repository.js b/user.repository.js new file mode 100644 index 0000000..a085a62 --- /dev/null +++ b/user.repository.js @@ -0,0 +1,53 @@ +import { pool } from "./db.js"; + +export const UserRepository = { + + async createOrUpdateUser({ telegramId, username, chatId }) { + const query = ` + INSERT INTO users (telegram_id, telegram_username, chat_id, last_msg_context) + VALUES ($1, $2, $3, '') + ON CONFLICT (telegram_id) + DO UPDATE SET + telegram_username = EXCLUDED.telegram_username, + chat_id = EXCLUDED.chat_id, + last_msg_context = '', + updated_at = now() + RETURNING *; + `; + + const values = [telegramId, username, chatId]; + + const { rows } = await pool.query(query, values); + return rows[0]; + }, + + async getByTelegramId(telegramId) { + const { rows } = await pool.query( + `SELECT * FROM users WHERE telegram_id = $1`, + [telegramId] + ); + return rows[0]; + }, + + async updateContext(telegramId, context) { + await pool.query( + `UPDATE users SET last_msg_context = $1 WHERE telegram_id = $2`, + [context, telegramId] + ); + }, + + async getContext(telegramId) { + const { rows } = await pool.query( + `SELECT last_msg_context FROM users WHERE telegram_id = $1`, + [telegramId] + ); + return rows[0]?.last_msg_context; + }, + + async deleteUser(telegramId) { + await pool.query( + `DELETE FROM users WHERE telegram_id = $1`, + [telegramId] + ); + } +};