Javascript/Alina_translator_Telegram_bot/bot.js
Fernando Mรฉndez 00ff7e2b89
Add files via upload
2021-03-12 18:39:53 +01:00

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 [];
}
}