[Aporte] Bot de Telegram en Quickjs. (Construye el tuyo)

(1/1)

@XSStringManolo:
Me apetecía programar una IA en javascript y necesitaba alguna forma de pasarle input, asique decidí hacer un bot de telegram.
Como ya van varios bots que hago, alguno salió algo buggeado y posiblemente en el futuro haga otros parecidos, decidí hacer un bot/nucleo a partir del cual pueda escribir cualquier bot.

Asique este bot tiene lo básico y mínimo indispensable que se puede necesitar para un bot. Le metí varios argumentos cli básicos para configurar el bot, meterle el token y ver su uso.
También le metí que responda al telegram a unos pocos comandos de ejemplo.

De momento no encontré ningún bug. Si encuentro alguno o meto algún cambio interesante o importante, lo añadiré aquí.

Código
import * as std from "std";
import * as os from "os";
 
let run = command => {
 let p = std.popen(command, "r"),
 msg = "",
 r = "";
 
 while(( r = p.getline() ) != null) {
   msg += r + "\n";
 }
 return msg;
}
 
let cli = {};
cli.COLORS = {
 RED: "\x1b[31m",
 RESET: "\x1b[0m",
 YELLOW:"\x1b[33m",
 BLUE: "\x1b[34m",
 GREEN: "\x1b[32m"
};
 
for (let i in scriptArgs) {
 switch(scriptArgs[i]) {
   case "-t":
   case "--token":
     cli.token = scriptArgs[+i + +1];
   break;
 
   case "-s":
   case "--save":
     let fd = std.open(".token", "w");
     fd.puts(cli.token);
     fd.close();
   break;
 
   case "-l":
   case "--load":
     cli.token = std.loadFile(".token");
   break;
 
   case "-h":
   case "--help":
     throw `
 
usage: qjs tgbot.js [options]
 -t  --token            Telegram Bot Api Token. https://t.me/BotFather
 -s  --save             Save the token internally to start the bot in the future without manually provide the token each time.
 -l  --load             Use the saved token to start the bot.
 -h  --help             This message.
 -v  --verbose          Show basic feedback to the command line interface.
 -w  --wait             Bot delay in seconds. (Can process multiple messages at once, so you don't need a really low number to don't fallback).
 
Examples:
qjs tgbot.js -t 192829292:iqidkwiexampleunvalidtokeniwjwusjwis -s -v
 
qjs tgbot.js -l -v
 
qjsc -o ctgbot tgbot.js && cp tgbot ~/../usr/bin/
tgbot -l -w 2 -v
 
`;
 
   case "-v":
   case "--verbose":
     cli.v = true;;
   break;
 
   case "-w":
   case "--wait":
     cli.wait = scriptArgs[+i + +1];
   break;
 }
}
 
 
if (!cli.token) {
 throw `${cli.COLORS.RED}No has introducido tu token de telegram.${cli.COLORS.RESET}
 
Si aún no pusiste tu token.
Inicia con: qjs tgbot.js -t 183828181:kqnsiwnskwkziqnsoqnsiqn -s
 
Si ya introduciste tu token.
Inicia con: qjs tgbot.js -l
 
Si aún no tienes un token.
Visita ${cli.COLORS.BLUE}https://t.me/BotFather${cli.COLORS.RESET} y escríbele /newBot
 
 
ESCRIBE ${cli.COLORS.YELLOW}qjs tgbot.js -h${cli.COLORS.RESET} PARA OBTENER LISTA DE COMANDOS.`;
}
 
let bot = () => {
let api = run(`curl https://api.telegram.org/bot${cli.token}/getUpdates --silent`);
 
let apiJson = JSON.parse(api);
 
if (apiJson.ok !== true) {
 throw `Telegram Api Returning An Error:
${api}`;
}
 
if (!apiJson.result) {
 throw `No results to parse:
${api}`;
}
 
let process = (text, username, chatId) => {
 let response = "";
 
 
 if (text.substr(0,1) == "/") {
   let recv = text.substring(1).toLowerCase();
   switch(recv) {
     case "start":
       response = "Comandos Disponibles:\n/Placeholder1 Haz esto\n/Placeholder2 Haz Aquello\n";
     break;
 
     case "hola":
       response = `Hola ${username} soy un bot escrito en javascript por @StringManolo.`;
     break;
 
     case "adios":
     case "chao":
       response = `Un placer ${username}! Qué vaya bien.`;
     break;
 
     default:
       response = `No se que significa ${recv}...`;
   }
 
 }
 
 if (response) {
   cli.v && console.log(`Respuesta: ${response}\n`);
   let aux = `https://api.telegram.org/bot${cli.token}/sendMessage?chat_id=${chatId}&text=${encodeURIComponent(response)}`;
   run(`curl "${aux}" --silent`);
 }
}
 
 
let lastId = 0;
for (let i in apiJson.result) {
 if (apiJson.result[i].message &&
 apiJson.result[i].message.text &&
 apiJson.result[i].update_id &&
 apiJson.result[i].message.from.username &&
 apiJson.result[i].message.chat.id) {
   let text = apiJson.result[i].message.text;
   let updateId = apiJson.result[i].update_id;
   let username = apiJson.result[i].message.from.username;
   let chatId = apiJson.result[i].message.chat.id;
   lastId = updateId;
   process(text, username, chatId);
 }
}
 
let borrarMensajesApi = () => {
 run(`curl https://api.telegram.org/bot${cli.token}/getUpdates?offset=${+lastId + 1} --silent`);
}
 
borrarMensajesApi();
cli.v && console.log("Bot process end");
}
 
let i = 0;
for (;;) {
 cli.v && console.log(`Running bot for the ${++i}° time.`);
 bot();
 cli.v && console.log(`Waiting ${(cli.wait || 20)} seconds to save resources.`);
 os.sleep( (cli.wait || 20) * 1000);
}

el-brujo:
¿Qué funcionalidades tiene el bot? A parte de saludar xD

¿Qué ideas tienes?

Estaría bien crear un RSS Feed de noticias, por ejemplo o servicios de red

Algunos bots interesantes son:

Citar

@CheckHostBot
Check host availability with http and ping checks.

Citar

@UtilityTools_Bot
List of commands:

➥ /settings - view the bot settings
➥ /setlanguage - allows you to change the language of the bot
➥ /skyperesolver (username) - you will get the last known IP of the user on Skype
➥ /skype2ip (ip) - search for a matching IP's in the Skype database.
➥ /cloudflare - /cloudflareresolver (domain) - does a brute force on the most common subdomains in order to search for the real IP
➥ /dnslookup - /dnsresolver (domain) - get the DNS records from a domain
➥ /shortlink (bit.ly/target) - find the contents of the link
➥ /zonetransfer (target) - tool zonetransfer
➥ /reverseip (target) - see the domain from IP
➥ /subnetcal (192.168.1.1/24) - determine the properties of a network subnet
➥ /httpheader (target) - see the http header, reveal system and web application details
➥ /subdomain (target) - looking for web subdomains
➥ /whois (target) - determine the registered owner of a domain or IP address block with the whois tool.
➥ /reversedns (domain) - find Reverse DNS records for an IP address or a range of IP addresses.
➥ /testping (domain) - allows you to test connectivity to a host
➥ /traceroute (target) - allows you to trace the path of an Internet connection
➥ /nmap (target) - tool nmap
➥ /geoip (ip) - tool to find the ip location
➥ /ddos - send many request packets
➥ /layer4 - for layer4 and layer3
➥ /layer7 - for layer7
➥ /randpw (lenght) - generate password
➥ /scancms (target) - to scan the cms website
➥ /ipinfo (ip) - see the information of an ip
➥ /id - see your telegram ID
➥ /chatid - allows you to see the telegram id of the chat in which the command was typed
➥ /time - see the time from the bot
➥ /echo - dark secret
➥ /creator - see the creator of the bot
➥ insult (victim) - insults the victim (also via Reply)
➥ /createproxy - generate a proxy
➥ /sms (prefix)(number) text - free sms | BETA
➥ /shitstorm - shitstorm a group
➥ /fakeidentity - generate an fakeidentity
➥ /instagram - tool to find info of an ig user
➥ /coder - information about coder

 Total commands ➵ 35

Hace poco estuve mirando bots de telegram y los hay muy variados temas:

Los mejores bots de Telegram
https://blog.elhacker.net/2020/10/los-mejores-bots-de-telegram-ayuda-descargar-recomendados.html

Xyzed:
Interesante, no estoy familiarizado con Telegram (aunque tendré que hacerlo, está evolucionando más rápido que nunca).
Felicidades por los primeros avances y gracias por el aporte, quizás lo utilice como guía en estos días  ;-)

@XSStringManolo:
Cita de: el-brujo en 13 Enero 2021, 20:03 pm

¿Qué funcionalidades tiene el bot? A parte de saludar xD

¿Qué ideas tienes?

Estaría bien crear un RSS Feed de noticias, por ejemplo o servicios de red

Algunos bots interesantes son:

Hace poco estuve mirando bots de telegram y los hay muy variados temas:

Los mejores bots de Telegram
https://blog.elhacker.net/2020/10/los-mejores-bots-de-telegram-ayuda-descargar-recomendados.html


El bot por sí no hace nada, solo saluda y acepta argumentos por la terminal o la cmd (no lo probé en windows pero debería ir)

Es más que nada para que la gente lo use como base para escribir su bot sin tener que programarlo todo de 0. Como si fuese una librería por decirlo de alguna forma.

Tengo algún bot creado tipo troyano para loggearte y controlar el dispositivo en el que corre el bot. Al ser en quickjs puede usar el motor directamente para controlar el dispositivo con código javascript o con comandos.

Hay un montón de cosas que se pueden hacer. Estaba pensando en una IA que hable, pero es complicada de programar. También un rpg pero también algo complicado. A ver si a la larga van saliendo cosas.

El feed de noticias mola, pero debe ser mucho rollo de parsear. Tengo que mirarlo!

Navegación

[0] Índice de Mensajes