elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web (Moderador: #!drvy)
| | |-+  [Aporte] Bot de Telegram en Quickjs. (Construye el tuyo)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Aporte] Bot de Telegram en Quickjs. (Construye el tuyo)  (Leído 2,641 veces)
@XSStringManolo
Hacker/Programador
Colaborador
***
Desconectado Desconectado

Mensajes: 2.397


Turn off the red ligth


Ver Perfil WWW
[Aporte] Bot de Telegram en Quickjs. (Construye el tuyo)
« en: 13 Enero 2021, 06:03 am »

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
  1. import * as std from "std";
  2. import * as os from "os";
  3.  
  4. let run = command => {
  5.  let p = std.popen(command, "r"),
  6.  msg = "",
  7.  r = "";
  8.  
  9.  while(( r = p.getline() ) != null) {
  10.    msg += r + "\n";
  11.  }
  12.  return msg;
  13. }
  14.  
  15. let cli = {};
  16. cli.COLORS = {
  17.  RED: "\x1b[31m",
  18.  RESET: "\x1b[0m",
  19.  YELLOW:"\x1b[33m",
  20.  BLUE: "\x1b[34m",
  21.  GREEN: "\x1b[32m"
  22. };
  23.  
  24. for (let i in scriptArgs) {
  25.  switch(scriptArgs[i]) {
  26.    case "-t":
  27.    case "--token":
  28.      cli.token = scriptArgs[+i + +1];
  29.    break;
  30.  
  31.    case "-s":
  32.    case "--save":
  33.      let fd = std.open(".token", "w");
  34.      fd.puts(cli.token);
  35.      fd.close();
  36.    break;
  37.  
  38.    case "-l":
  39.    case "--load":
  40.      cli.token = std.loadFile(".token");
  41.    break;
  42.  
  43.    case "-h":
  44.    case "--help":
  45.      throw `
  46.  
  47. usage: qjs tgbot.js [options]
  48.  -t  --token            Telegram Bot Api Token. https://t.me/BotFather
  49.  -s  --save             Save the token internally to start the bot in the future without manually provide the token each time.
  50.  -l  --load             Use the saved token to start the bot.
  51.  -h  --help             This message.
  52.  -v  --verbose          Show basic feedback to the command line interface.
  53.  -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).
  54.  
  55. Examples:
  56. qjs tgbot.js -t 192829292:iqidkwiexampleunvalidtokeniwjwusjwis -s -v
  57.  
  58. qjs tgbot.js -l -v
  59.  
  60. qjsc -o ctgbot tgbot.js && cp tgbot ~/../usr/bin/
  61. tgbot -l -w 2 -v
  62.  
  63. `;
  64.  
  65.    case "-v":
  66.    case "--verbose":
  67.      cli.v = true;;
  68.    break;
  69.  
  70.    case "-w":
  71.    case "--wait":
  72.      cli.wait = scriptArgs[+i + +1];
  73.    break;
  74.  }
  75. }
  76.  
  77.  
  78. if (!cli.token) {
  79.  throw `${cli.COLORS.RED}No has introducido tu token de telegram.${cli.COLORS.RESET}
  80.  
  81. Si aún no pusiste tu token.
  82. Inicia con: qjs tgbot.js -t 183828181:kqnsiwnskwkziqnsoqnsiqn -s
  83.  
  84. Si ya introduciste tu token.
  85. Inicia con: qjs tgbot.js -l
  86.  
  87. Si aún no tienes un token.
  88. Visita ${cli.COLORS.BLUE}https://t.me/BotFather${cli.COLORS.RESET} y escríbele /newBot
  89.  
  90.  
  91. ESCRIBE ${cli.COLORS.YELLOW}qjs tgbot.js -h${cli.COLORS.RESET} PARA OBTENER LISTA DE COMANDOS.`;
  92. }
  93.  
  94. let bot = () => {
  95. let api = run(`curl https://api.telegram.org/bot${cli.token}/getUpdates --silent`);
  96.  
  97. let apiJson = JSON.parse(api);
  98.  
  99. if (apiJson.ok !== true) {
  100.  throw `Telegram Api Returning An Error:
  101. ${api}`;
  102. }
  103.  
  104. if (!apiJson.result) {
  105.  throw `No results to parse:
  106. ${api}`;
  107. }
  108.  
  109. let process = (text, username, chatId) => {
  110.  let response = "";
  111.  
  112.  
  113.  if (text.substr(0,1) == "/") {
  114.    let recv = text.substring(1).toLowerCase();
  115.    switch(recv) {
  116.      case "start":
  117.        response = "Comandos Disponibles:\n/Placeholder1 Haz esto\n/Placeholder2 Haz Aquello\n";
  118.      break;
  119.  
  120.      case "hola":
  121.        response = `Hola ${username} soy un bot escrito en javascript por @StringManolo.`;
  122.      break;
  123.  
  124.      case "adios":
  125.      case "chao":
  126.        response = `Un placer ${username}! Qué vaya bien.`;
  127.      break;
  128.  
  129.      default:
  130.        response = `No se que significa ${recv}...`;
  131.    }
  132.  
  133.  }
  134.  
  135.  if (response) {
  136.    cli.v && console.log(`Respuesta: ${response}\n`);
  137.    let aux = `https://api.telegram.org/bot${cli.token}/sendMessage?chat_id=${chatId}&text=${encodeURIComponent(response)}`;
  138.    run(`curl "${aux}" --silent`);
  139.  }
  140. }
  141.  
  142.  
  143. let lastId = 0;
  144. for (let i in apiJson.result) {
  145.  if (apiJson.result[i].message &&
  146.  apiJson.result[i].message.text &&
  147.  apiJson.result[i].update_id &&
  148.  apiJson.result[i].message.from.username &&
  149.  apiJson.result[i].message.chat.id) {
  150.    let text = apiJson.result[i].message.text;
  151.    let updateId = apiJson.result[i].update_id;
  152.    let username = apiJson.result[i].message.from.username;
  153.    let chatId = apiJson.result[i].message.chat.id;
  154.    lastId = updateId;
  155.    process(text, username, chatId);
  156.  }
  157. }
  158.  
  159. let borrarMensajesApi = () => {
  160.  run(`curl https://api.telegram.org/bot${cli.token}/getUpdates?offset=${+lastId + 1} --silent`);
  161. }
  162.  
  163. borrarMensajesApi();
  164. cli.v && console.log("Bot process end");
  165. }
  166.  
  167. let i = 0;
  168. for (;;) {
  169.  cli.v && console.log(`Running bot for the ${++i}° time.`);
  170.  bot();
  171.  cli.v && console.log(`Waiting ${(cli.wait || 20)} seconds to save resources.`);
  172.  os.sleep( (cli.wait || 20) * 1000);
  173. }


« Última modificación: 13 Enero 2021, 06:06 am por @XSStringManolo » En línea

Mi perfil de patrocinadores de GitHub está activo! Puedes patrocinarme para apoyar mi trabajo de código abierto 💖

el-brujo
ehn
***
Desconectado Desconectado

Mensajes: 21.586


La libertad no se suplica, se conquista


Ver Perfil WWW
Re: [Aporte] Bot de Telegram en Quickjs. (Construye el tuyo)
« Respuesta #1 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:

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


En línea

Xyzed


Desconectado Desconectado

Mensajes: 306



Ver Perfil
Re: [Aporte] Bot de Telegram en Quickjs. (Construye el tuyo)
« Respuesta #2 en: 13 Enero 2021, 20:51 pm »

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  ;-)
En línea

...
@XSStringManolo
Hacker/Programador
Colaborador
***
Desconectado Desconectado

Mensajes: 2.397


Turn off the red ligth


Ver Perfil WWW
Re: [Aporte] Bot de Telegram en Quickjs. (Construye el tuyo)
« Respuesta #3 en: 13 Enero 2021, 22:08 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!
En línea

Mi perfil de patrocinadores de GitHub está activo! Puedes patrocinarme para apoyar mi trabajo de código abierto 💖

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
¿Se puede entrar en un ordenador desde el tuyo conectado en LAN, sin programas? « 1 2 »
Hacking
BlueMetallia 10 9,315 Último mensaje 19 Noviembre 2011, 02:18 am
por CloudswX
¿Wallpapers? Aporta el tuyo « 1 2 »
Foro Libre
WIитX 12 4,214 Último mensaje 5 Septiembre 2014, 10:53 am
por ivancea96
El simulador de carreras de coches más realista del mundo puede ser tuyo si ...
Noticias
wolfbcn 0 1,164 Último mensaje 29 Julio 2015, 02:18 am
por wolfbcn
El DNIe no es seguro. Cómo saber si el tuyo está afectado por el fallo de ...
Noticias
wolfbcn 0 1,953 Último mensaje 9 Noviembre 2017, 14:01 pm
por wolfbcn
Tutorial básico de Quickjs
Desarrollo Web
@XSStringManolo 2 14,210 Último mensaje 12 Noviembre 2021, 15:50 pm
por @XSStringManolo
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines