From 79364f3df8898a168dbe74c0d53b5d0e0a4f8fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20M=C3=A9ndez?= <45081533+FerMdez@users.noreply.github.com> Date: Tue, 9 Mar 2021 21:42:25 +0100 Subject: [PATCH] Add files via upload --- Alina_translator_Telegram_bot/README.ms | 109 +++++++++++ Alina_translator_Telegram_bot/bot.js | 238 +++++++++++++++++++++++ Alina_translator_Telegram_bot/users.json | 1 + 3 files changed, 348 insertions(+) create mode 100644 Alina_translator_Telegram_bot/README.ms create mode 100644 Alina_translator_Telegram_bot/bot.js create mode 100644 Alina_translator_Telegram_bot/users.json diff --git a/Alina_translator_Telegram_bot/README.ms b/Alina_translator_Telegram_bot/README.ms new file mode 100644 index 0000000..8ca4ed7 --- /dev/null +++ b/Alina_translator_Telegram_bot/README.ms @@ -0,0 +1,109 @@ +# Alina_translator_Telegram_bot 🤖 + +## Índice +1. [Descripción](#1-descripción-) +2. [Autor](#2-autor-%EF%B8%8F) +3. [Advertencia](#3-advertencia-%EF%B8%8F) +4. [Generar un token con @BotFather](#4-generar-un-token-con-botfather) +5. [Ejecución](#5-ejecución-%EF%B8%8F) +* 5.1. [Instalación _node_modules_](#instalación-node_modules-) +* 5.2. [Poner el Bot en producción](#poner-el-bot-en-producción-%EF%B8%8F) + * 5.2.1. [En Windows](#en-windows-) + * 5.2.2. [En Linux](#en-linux-debianubuntu-) +* 5.3 [Añadir nuevas librerías](#53-añadir-nuevas-librerías-) +6. [Licencia](#6-licencia-) +7. [Enlace al Bot](#7-enlace-al-bot-) +*** +## 1. Descripción 📖 +Bot de Telegram para la Asociación Diskobolo de la Facultad de Informática de la Universidad Complutense de Madrid. +*** +## 2. Autor ✒️ +Fernando Méndez (https:/fermdez.ddns.net | @HumperCobra) +*** +## 3. Advertencia ⚠️ +Desbes generar tu propio token para el bot y añadirlo a _const token = 'AQUÍ_A_TU_TOKEN';_ en el archivo *bot.js*. +*** +## 4. Generar un token con @BotFather +1. Inicia un chat con https://t.me/botfather +2. Escribe en el chat el comando */newbot* +3. Te pedirá el alias y luego el nombre del bot (debe contener la palabra _bot_). +4. Nos devolverá el token de nuestro bot, por ejemplo: + + > Use this token to access the HTTP API: 668219748:ABCRTZu7zNT5QO2bRfZfbPIXBLXb2U-ojVX +*** +## 5. Ejecución 🛠️ +### 5.1 Instalación _node_modules_ 🔧 +1. Creamos un directorio para el bot y guardamos ahí el archivo *bot.js*. +2. Instalar *node.js* + * En Windows/Mac: https://nodejs.org/es/download/. + * Si tienes Linux (Debian/Ubuntu), usa los siguientes comandos: + ``` + $ sudo apt-get update + $ sudo apt-get upgrade + $ sudo apt-get install curl + + $ cd ~ + $ curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - + + $ sudo apt-get install -y nodejs + + $ cd ./ruta_del_directorio_del_bot/ + $ npm install + ``` +3. Comprobar que se ha instalado con el comando: + ``` + >/$ node --version + ``` +4. Dentro del directorio del bot, ejecutar los siguientes comandos: + ``` + >/$ npm init --yes + >/$ npm install --save node-telegram-bot-api + ``` +5. Comprobar que se ha generado el directorio _node_modules_. +### 5.2 Poner el Bot en producción ⚙️ +#### 5.2.1 En Windows 💻 +* Instala *nodejs*, si no lo hiciste en el punto anterior: https://nodejs.org/es/download/ +* Ejecutar en CMD o PS los comandos: + ``` + > cd ./ruta_del_directorio_del_bot/ + > node bot.js + ``` +* El proceso se puede automatizar creando un archivo .bat y añadiéndolo al programador de tareas. + +#### 5.2.2 En Linux (Debian/Ubuntu) 🐧 +* Instalamos *nodejs*, si no lo hicimos en el punto anterior: + ``` + $ sudo apt-get update + $ sudo apt-get upgrade + $ sudo apt-get install curl + + $ cd ~ + $ curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - + + $ sudo apt-get install -y nodejs + + $ cd ./ruta_del_directorio_del_bot/ + $ npm install +``` + +* Ejecutamos el bot con el comando: + ``` + $ node bot.js + ``` + +* El proceso se puede automatizar creando un script. + +### 5.3 Añadir nuevas librerías 📚 +* Primero abrir un terminal/PowerShell/CMD (dependiendo de nuestro SO) e ir al directorio de nuestro bot: + ``` + cd ./ruta_del_directorio_del_bot/ + ``` +* Si por ejemplo queremos añadir la librería _weather-js_, deberemos escribir el siguiente comando: + ``` + npm install weather-js + ``` +*** +## 6. Licencia 📄 +Educational Community License v2.0 (ECL-2.0). +## 7. Enlace al Bot 🤖 +> https://t.me/Alinaaa_translator_bot diff --git a/Alina_translator_Telegram_bot/bot.js b/Alina_translator_Telegram_bot/bot.js new file mode 100644 index 0000000..dbf7689 --- /dev/null +++ b/Alina_translator_Telegram_bot/bot.js @@ -0,0 +1,238 @@ +/* + "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)", + "dependencies": { + "i18n": "^0.13.2", + "node-telegram-bot-api": "^0.51.0" +} + +*/ + +/* Bot token and API */ +const TelegramBot = require('node-telegram-bot-api'); +const token = ''; //Here your Bot´s token. +const bot = new TelegramBot(token, {polling:true}); + + +/* Translator */ +//const translate = require('translate-api'); +const translate = require('@vitalets/google-translate-api'); +//const translate = require('google-translate-api'); +//var _from = 'es'; +//var _to = 'en'; + + +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); + } + + 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; + var userIndex = indexOfArray(msg.from); + if(userIndex === -1){ + 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'}); + addUser(msg.from); + } + + 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, "Choose an option: 🇪🇸 🇬🇧 🇷🇺", + { + 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); + 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); + }); + +} + +// Para sobreescribir el archivo users.json: +const fs = require('fs'); +// Archivo con lla información de usuarios: +const usersFile = require("./users.json"); +// Almacena los IDs de los usuarios leidos de "usuers.json": +const _users = JSON.parse(JSON.stringify(usersFile.users)); + +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 i = 0; + + if(_users.length == 0){ + var index = -1; + } else { + while(!encontrado && i < _users.length){ + var index = _users.findIndex(function (_user) { + if(i > 0) return _users[i].id === _user.id; + }); + if(index != -1){ + encontrado = true; + } else { + i++; + } + } + } + + return index; +} \ No newline at end of file diff --git a/Alina_translator_Telegram_bot/users.json b/Alina_translator_Telegram_bot/users.json new file mode 100644 index 0000000..86ac74b --- /dev/null +++ b/Alina_translator_Telegram_bot/users.json @@ -0,0 +1 @@ +{"users":[{"id":-1,"is_bot":false,"first_name":"null","username":"NULL","language_code":"es","from":"es","to":"en"}]} \ No newline at end of file