armyan tts add

This commit is contained in:
2026-03-03 01:10:41 +04:00
parent a0d98b95e5
commit 424823794b
6 changed files with 183 additions and 91 deletions

155
bot.js
View File

@@ -4,6 +4,18 @@ import axios from "axios";
import FormData from 'form-data';
import fs from 'fs';
import ffmpeg from 'fluent-ffmpeg';
function convertToOgg(inputPath, outputPath) {
return new Promise((resolve, reject) => {
ffmpeg(inputPath)
.audioCodec('libopus')
.format('ogg')
.on('end', () => resolve())
.on('error', (err) => reject(err))
.save(outputPath);
});
}
import { UserRepository } from "./user.repository.js";
@@ -18,39 +30,42 @@ const bot = new TelegramBot(tokenTg, { polling: true });
console.log("Бот запущен...");
bot.onText(/\/info/, (msg)=>{
const message = `Информация о боте: \n
bot.onText(/\/info/, (msg) => {
const message = `Информация о боте: \n
'/start' - перезапускает чат, забывает контекст прошлого диалого \n
'/toggleModel' - Выбор модели (еще не доступен)`
const chatId = msg.chat.id
const chatId = msg.chat.id
bot.sendMessage(chatId, message)
bot.sendMessage(chatId, message)
})
bot.onText(/\/armyan (.+)/, async(msg, match)=>{
bot.onText(/\/armyan (.+)/, async (msg, match) => {
const chatId = msg.chat.id;
const textAfterCommand = match[1];
const response = await textToArmyan(textAfterCommand);
await convertToOgg(`voices/${response.file}.wav`, `voices/${response.file}.ogg`);
bot.sendVoice(chatId, `voices/${response.file}.ogg`);
})
bot.onText(/\/start/, async(msg) => {
bot.onText(/\/start/, async (msg) => {
const chatId = msg.chat.id;
const chatType = msg.chat.type
const user = msg.from
try{
try {
const createOrUpdateUser = await UserRepository.createOrUpdateUser({
telegramId: user.id,
username: user.username,
chatId: chatId
});
}catch(err){
} catch (err) {
console.error('Ошибка при создании или обновлении пользователя:', err);
}
bot.sendMessage(chatId, `Чат перезапущен, тип чата ${chatType}`);
});
bot.on('message', async(msg) => {
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
const user = msg.from
@@ -62,115 +77,155 @@ bot.on('message', async(msg) => {
}
if (msg.photo) {
bot.sendMessage(chatId, 'Красиво, но такое мне не надо', {reply_to_message_id: msg.message_id});
bot.sendMessage(chatId, 'Красиво, но такое мне не надо', { reply_to_message_id: msg.message_id });
return;
}
if (msg.document) {
bot.sendMessage(chatId, 'Такое мне не надо', {reply_to_message_id: msg.message_id});
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});
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;
if (msg.voice) {
const fileId = msg.voice.file_id;
const filePath = await bot.downloadFile(fileId, './voices');
const filePath = await bot.downloadFile(fileId, './voices');
const form = new FormData();
form.append('file', fs.createReadStream(filePath));
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()
}
);
const response = await axios.post(
`http://${process.env.API_URL}:${process.env.API_PORT}/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});
}
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){
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});
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{
try {
const last_msg_context = await UserRepository.getContext(user.id) || ''
console.log('last_msg_context:', last_msg_context);
if(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{
} 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){
} catch (err) {
console.error('Ошибка при обработке сообщения:', err);
}
return;
}
});
async function switchToRussian(message){
try{
async function switchToRussian(message) {
try {
const options = {
method:'POST',
url:`https://agent.timeweb.cloud/api/v1/cloud-ai/agents/${accessId}/call`,
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:{
data: {
message: `Убери ошибки в тексте и поставь знаки препинания: "${message}". Если текст короткий или без явных ошибок ничего не делай и отвечай просто "Армянин молодец", особо не размышляй над содержимым текста, просто выполняй свою задачу. Так же делай рядом версию с переводом на армянский язык`,
parent_message_id: ''
parent_message_id: ''
}
}
const response = await axios.request(options);
return response.data;
}catch(err){
} catch (err) {
console.error('Ошибка при получении ответа от AI:', err);
}
}
async function getAIResponse(message, context) {
try{
try {
const options = {
method:'POST',
url:`https://agent.timeweb.cloud/api/v1/cloud-ai/agents/${accessId}/call`,
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,
data: {
message: message,
parent_message_id: context
}
}
const response = await axios.request(options);
return response.data;
}catch(err){
} catch (err) {
console.error('Ошибка при получении ответа от AI:', err);
}
}
async function textToArmyan(message) {
try {
const optionsArmyan = {
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 responseArmyan = await axios.request(optionsArmyan);
const options = {
method: 'POST',
url: `http://${process.env.API_URL}:${process.env.API_PORT}/voice/start`,
headers: {
'Content-Type': 'application/json'
},
data: {
text: responseArmyan.data.message
}
}
const response = await axios.request(options);
if (response.status === 200) {
return response.data;
} else {
console.error('Ошибка при получении ответа от AI:', response.data);
}
} catch (err) {
console.error('Ошибка при получении ответа от AI:', err);
}
}