-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtgbot.js
More file actions
272 lines (229 loc) · 8.11 KB
/
tgbot.js
File metadata and controls
272 lines (229 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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" };
let javascriptBotFunctions = `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 loggedInUsers = [];
let requestedLogin = [];
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 [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.
-p --password Password to log from Telegram.
-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 -t 192829292:iqidkwiexampleunvalidtokeniwjwusjwis -s -v
qjs tgbot -l -v
qjsc -o ctgbot tgbot && cp ctgbot ~/../usr/bin/
ctgbot -l -w 2 -v
`;
case "-p":
case "--password":
cli.password = scriptArgs[+i + +1];
break;
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 -t 183828181:kqnsiwnskwkziqnsoqnsiqn -s
Si ya introduciste tu token.
Inicia con: qjs tgbot -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 -h${cli.COLORS.RESET} PARA OBTENER LISTA DE COMANDOS.`;
}
let bot = () => {
let api = run(`curl https://api.telegram.org/bot${cli.token}/getUpdates --silent`);
if (!api) {
console.log("Unable to access Telegram Bot Api. Do you have internet conection?");
return;
}
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 = "";
let userRequestedLogin = false;
let userLogged = false;
for (let i in requestedLogin) {
if (requestedLogin[i] == username) {
cli.v && console.log(`${username} requested login previously`);
userRequestedLogin = true;
if (cli.password == text) {
cli.v && console.log(`password match pushing user to loggedInUsersList`);
loggedInUsers.push(username);
response = "Estás loggeado.";
} else {
cli.v && console.log(`${text} is not the password`);
response = "Contraseña incorrecta";
}
}
}
for (let i in requestedLogin) {
if (username == requestedLogin[i]) {
cli.v && console.log(`${username} ended login intent`);
requestedLogin.splice(i, 1);
}
}
if (!userRequestedLogin) {
for (let i in loggedInUsers) {
if (username == loggedInUsers[i]) {
userLogged = true;
}
}
/* Process commands */
if (text.substr(0,1) == "/") {
let recv = text.substring(1).toLowerCase();
if (userLogged) {
cli.v && console.log(`Acceso a comandos especiales permitido para ${username}`);
if (recv.substr(0, 3) == "run") {
cli.v && console.log(`Running command $ ${text.substring(5)}`);
response = run(text.substring(5));
} else if (recv.substr(0, 2) == "js") {
cli.v && console.log(`Running javascript ${text.substring(4)}`);
try {
let fd = std.open(".evaling", "w+");
fd.puts(`${javascriptBotFunctions}${text.substring(4)}`);
fd.close();
response = run(`qjs .evaling 2>&1`);
} catch(err) {
response = `Error running the code: ${err}`;
}
} else if (recv.substr(0, 8) == "shutdown") {
throw "Shutdown ordered by " + username;
} else if (recv.substr(0, 4) == "wait") {
cli.wait = +recv.substring(4);
cli.v && console.log("Wait time changed to " + cli.wait);
response = `Changed wait time to ${cli.wait} seconds`;
} else if (recv.substr(0, 3) == "c++") {
cli.v && console.log(`Running c++ ${text.substring(5)}`);
let fd = std.open(".compiling.cpp", "w+");
fd.puts(`${text.substring(5)}`);
fd.close();
response = run(`g++ -o .compiled .compiling.cpp 2>&1 && chmod +775 .compiled && ./.compiled`);
} else if (recv.substr(0, 6) == "python") {
cli.v && console.log(`Running python ${text.substring(8)}`);
let fd = std.open(".running.py", "w+");
fd.puts(`${text.substring(8)}`);
fd.close();
response = run(`python .running.py 2>&1`);
}
}
switch(recv) {
case "start":
case "help":
response = "Comandos Disponibles:\n/login loggeate con tu contraseña\n/help muestra este mensaje\n";
if (userLogged) {
response += "\nComandos Disponibles Para Usuario Loggeado:\n/help muestra este mensaje\n/run comando corre el comando en bash\n/c++ corre el codigo c++\n/js corre el código javascript en un motor quickjs\n/python corre el código python\n/shutdown detiene permanentemente el bot\n/wait segundos cambia la velocidad de espera entre cada ciclo del bot.\n";
}
break;
case "hola":
response = `Hola ${username} soy un bot escrito en javascript por @StringManolo.`;
break;
case "login":
cli.v && console.log(`${username} requested login`);
response = `Escribe tu contraseña por privado`;
requestedLogin.push(username);
break;
default:
if (!response) {
response = `No se que significa ${recv}...`;
} else {
console.log(`RESP:${response}]`);
}
}
}
}
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");
}
/* Corre el bot cada 10 segundos */
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);
}