267 lines
9.5 KiB
JavaScript
267 lines
9.5 KiB
JavaScript
/*
|
|
"name": "alina_bot",
|
|
"version": "2.0.0",
|
|
"description": "Text translation bot",
|
|
"main": "index.js",
|
|
"scripts": {
|
|
"test": "echo \"Error: no test specified\" && exit 1"
|
|
},
|
|
"keywords": [],
|
|
"author": "Fernando Mรฉndez (https://fermdez.ddns.net | @HumperCobra)",
|
|
"license": "Educational Community License v2.0 (ECL-2.0)",
|
|
}
|
|
|
|
*/
|
|
|
|
/* Bot token and API */
|
|
const TelegramBot = require('node-telegram-bot-api');
|
|
const _private = require('./private.js');
|
|
const token = _private.token();
|
|
const bot = new TelegramBot(token, {polling:true});
|
|
|
|
|
|
/* Translator */
|
|
//const translate = require('translate-api');
|
|
const translate = require('@vitalets/google-translate-api'); //https://www.npmjs.com/package/@vitalets/google-translate-api
|
|
//const translate = require('google-translate-api');
|
|
|
|
// To overwrite the users.json file:
|
|
const fs = require('fs');
|
|
// File with user information:
|
|
//const usersFile = require("./users.json");
|
|
// Stores user IDs read from "usuers.json":
|
|
//const _users = JSON.parse(JSON.stringify(usersFile.users));
|
|
const _users = createUsersFile();
|
|
|
|
|
|
bot.on('polling_error', function(error){
|
|
console.log(error);
|
|
});
|
|
|
|
bot.onText(/^\/start/, function(msg){
|
|
var chatId = msg.chat.id;
|
|
var nameUser = msg.from.first_name;
|
|
var userId = msg.from.id;
|
|
var userIndex = indexOfArray(msg.from);
|
|
if(userIndex === -1){
|
|
addUser(msg.from);
|
|
//updateUsers();
|
|
}
|
|
|
|
bot.sendMessage(chatId, "Welcome " + nameUser + "!\n\nI am a text translation bot created by *Fernando* (https://fermdez.ddns.net/en-UK/)."
|
|
+ "\n\nUse the command */translator* to change languages.", {parse_mode: 'Markdown'});
|
|
console.log("User /start: " + nameUser + ", Id: " + userId);
|
|
|
|
});
|
|
|
|
// Author:
|
|
bot.onText(/^\/author/, function(msg){
|
|
var chatId = msg.chat.id;
|
|
var nameUser = msg.from.first_name;
|
|
var userId = msg.from.id;
|
|
var date = msg.date;
|
|
|
|
bot.sendMessage(chatId, "Author๐ค: *Fernando Mรฉndez 'Humpercobra'* \n" +
|
|
"Website๐: https://fermdez.ddns.net/en-UK/", {parse_mode : "Markdown"});
|
|
|
|
console.log("[" + Date(date) + "] " + nameUser + " (" + userId + "): Ha solicitado el autor.");
|
|
});
|
|
|
|
// Traductor command:
|
|
bot.onText(/^\/translator/, function(msg){
|
|
translator(msg);
|
|
});
|
|
|
|
/* Translator */
|
|
bot.on('message', (msg) => {
|
|
var chatId = msg.chat.id;
|
|
var nameUser = msg.from.first_name;
|
|
//updateUsers();
|
|
var userIndex = indexOfArray(msg.from);
|
|
|
|
|
|
if(userIndex === -1){
|
|
addUser(msg.from);
|
|
bot.sendMessage(chatId, "Welcome *"+nameUser+"*!" + "\nWe have just added you to the list of users. \n\nChoose the language you want to translate with the command: */translator*.", {parse_mode: 'Markdown'});
|
|
}
|
|
else{
|
|
if(msg.text.includes('Spanish[๐ช๐ธ]') || msg.text.includes('English[๐ฌ๐ง]') || msg.text.includes('Russian[๐ท๐บ]')){
|
|
switch(msg.text){
|
|
case 'Spanish[๐ช๐ธ] --> English[๐ฌ๐ง]': //_from='es'; _to='en';
|
|
_users[userIndex].from='es'; _users[userIndex].to='en';
|
|
updateUsers();
|
|
bot.sendMessage(chatId, "*"+nameUser+"*" + ", now I will translate the texts from *Spanish*๐ช๐ธ to *English*๐ฌ๐ง.", {parse_mode: 'Markdown'});
|
|
break ;
|
|
case 'English[๐ฌ๐ง] --> Spanish[๐ช๐ธ]': //_from='en'; _to='es';
|
|
_users[userIndex].from='en'; _users[userIndex].to='es';
|
|
updateUsers();
|
|
bot.sendMessage(chatId, "*"+nameUser+"*" + ", now I will translate the texts from *English*๐ฌ๐ง to *Spanish*๐ช๐ธ.", {parse_mode: 'Markdown'});
|
|
break ;
|
|
case 'Spanish[๐ช๐ธ] --> Russian[๐ท๐บ]': //_from='es'; _to='ru';
|
|
_users[userIndex].from='es'; _users[userIndex].to='ru';
|
|
updateUsers();
|
|
bot.sendMessage(chatId, "*"+nameUser+"*" + ", now I will translate the texts from *Spanish*๐ช๐ธ to *Russian*๐ท๐บ.", {parse_mode: 'Markdown'});
|
|
break ;
|
|
case 'Russian[๐ท๐บ] --> Spanish[๐ช๐ธ]': //_from='ru'; _to='es';
|
|
_users[userIndex].from='ru'; _users[userIndex].to='es';
|
|
updateUsers();
|
|
bot.sendMessage(chatId, "*"+nameUser+"*" + ", now I will translate the texts from *Russian*๐ท๐บ to *Spanish*๐ช๐ธ.", {parse_mode: 'Markdown'});
|
|
break ;
|
|
case 'English[๐ฌ๐ง] --> Russian[๐ท๐บ]': //_from='en'; _to='ru';
|
|
_users[userIndex].from='en'; _users[userIndex].to='ru';
|
|
updateUsers();
|
|
bot.sendMessage(chatId, "*"+nameUser+"*" + ", now I will translate the texts from *English*๐ฌ๐ง to *Russian*๐ท๐บ.", {parse_mode: 'Markdown'});
|
|
break ;
|
|
case 'Russian[๐ท๐บ] --> English[๐ฌ๐ง]': //_from='ru'; _to='en';
|
|
_users[userIndex].from='ru'; _users[userIndex].to='en';
|
|
updateUsers();
|
|
bot.sendMessage(chatId, "*"+nameUser+"*" + ", now I will translate the texts from *Russian*๐ท๐บ to *English*๐ฌ๐ง.", {parse_mode: 'Markdown'});
|
|
break ;
|
|
}
|
|
} else if(!msg.text.includes('/') && userIndex != -1){
|
|
traduce(msg);
|
|
}
|
|
}
|
|
});
|
|
|
|
function translator(msg){
|
|
var chatId = msg.chat.id;
|
|
|
|
bot.sendMessage(chatId, "<b>Choose an option: </b> ๐ช๐ธ ๐ฌ๐ง ๐ท๐บ",
|
|
{
|
|
reply_markup: {
|
|
keyboard: [
|
|
[
|
|
{
|
|
text:"Spanish[๐ช๐ธ] --> English[๐ฌ๐ง]", callback_data: 'es_en',
|
|
},
|
|
{
|
|
text:"English[๐ฌ๐ง] --> Spanish[๐ช๐ธ]", callback_data: 'en_es',
|
|
}
|
|
],
|
|
[
|
|
{
|
|
text:"Spanish[๐ช๐ธ] --> Russian[๐ท๐บ]", callback_data: 'es_ru',
|
|
},
|
|
{
|
|
text:"Russian[๐ท๐บ] --> Spanish[๐ช๐ธ]", callback_data: 'ru_es',
|
|
}
|
|
],
|
|
[
|
|
{
|
|
text:"English[๐ฌ๐ง] --> Russian[๐ท๐บ]", callback_data: 'es_ru',
|
|
},
|
|
{
|
|
text:"Russian[๐ท๐บ] --> English[๐ฌ๐ง]", callback_data: 'ru_es',
|
|
}
|
|
]
|
|
]
|
|
},
|
|
parse_mode:"HTML",
|
|
});
|
|
}
|
|
|
|
function traduce(msg){
|
|
var chatId = msg.chat.id;
|
|
var message = msg.text;
|
|
//var tipoChat = msg.chat.type;
|
|
|
|
var userIndex = indexOfArray(msg.from);
|
|
/* if(userIndex === -1){
|
|
addUser(msg.from);
|
|
userIndex = indexOfArray(msg.from);
|
|
} */
|
|
var _from = _users[userIndex].from;
|
|
var _to = _users[userIndex].to;
|
|
|
|
|
|
/* Without Google-API */
|
|
translate(message, {from: _from, to: _to}).then(res => {
|
|
if(res.from.text.didYouMean){
|
|
translate(res.from.text.value, {from: _from, to: _to}).then(resFixed => {
|
|
bot.sendMessage(chatId, "I have corrected a possible typing error: \n\n" + res.from.text.value + "\n\n-----\n\nTraduction: \n\n" + resFixed.text);
|
|
console.log("Bot auto-corrected --> " + message + " : " + resFixed.text);
|
|
});
|
|
}
|
|
else{
|
|
bot.sendMessage(chatId, res.text);
|
|
console.log("Bot traduce --> " + message + " : " + res.text);
|
|
}
|
|
}).catch(err => {
|
|
console.error(err);
|
|
});
|
|
|
|
}
|
|
|
|
function addUser(newUser){
|
|
let userToSave;
|
|
var index = indexOfArray(newUser);
|
|
var _from = newUser.language_code;
|
|
var _to = 'en';
|
|
|
|
newUser.from = _from;
|
|
newUser.to = _to;
|
|
|
|
if (index === -1){
|
|
_users.push(newUser);
|
|
userToSave = {users:_users};
|
|
fs.writeFile('./users.json', JSON.stringify(userToSave), 'utf8', (err) => {
|
|
if (err) /*throw err*/ console.log('ERROR: no se ha actualizado la lista de Usuarios.');
|
|
});
|
|
console.log(newUser + ' Usuario nuevo aรฑadido la base de datos.');
|
|
} else if (index > -1){
|
|
console.log(newUser + ' Ya existe el usuario en la base de datos.');
|
|
}
|
|
}
|
|
|
|
function updateUsers(){
|
|
let userToSave = {users:_users};
|
|
fs.writeFile('./users.json', JSON.stringify(userToSave), 'utf8', (err) => {
|
|
if (err) /*throw err*/ console.log('ERROR: no se ha actualizado la lista de Usuarios.');
|
|
});
|
|
|
|
}
|
|
|
|
function indexOfArray(_user){
|
|
var encontrado = false;
|
|
var index = -1;
|
|
var i = 0;
|
|
|
|
if(_users.length === 0){
|
|
index = -1;
|
|
} else {
|
|
do{
|
|
if(_users[i].id === _user.id){
|
|
index = i;
|
|
}
|
|
if(index != -1){
|
|
encontrado = true;
|
|
} else {
|
|
i++;
|
|
}
|
|
} while(!encontrado && i < _users.length);
|
|
}
|
|
|
|
return index;
|
|
}
|
|
|
|
function createUsersFile(){
|
|
try {
|
|
if (!(fs.existsSync("./users.json"))) {
|
|
//fs.createWriteStream('./users.json');
|
|
fs.writeFile('./users.json', JSON.stringify({users:[]}), 'utf8', function(err) {
|
|
if(err) console.log(err);
|
|
else console.log("Users file not found. A new one has been created.");
|
|
});
|
|
return [];
|
|
} else {
|
|
// File with user information:
|
|
const usersFile = require("./users.json");
|
|
console.log("Users file load successfully.");
|
|
return JSON.parse(JSON.stringify(usersFile.users));
|
|
}
|
|
} catch(err) {
|
|
console.log("Error creating user file: \n\n" + err);
|
|
return [];
|
|
}
|
|
} |