-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbnet.py
More file actions
383 lines (345 loc) · 12.5 KB
/
bnet.py
File metadata and controls
383 lines (345 loc) · 12.5 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import sys
import re
import telebot
from telebot import types
import time
import json
import urllib
import random
import os
import six
import socket
import requests
from collections import OrderedDict
from colorclass import Color
from io import StringIO
print(Color(
'{autored}[{/red}{autoyellow}+{/yellow}{autored}]{/red} {autocyan} Bnet iniciado.{/cyan}'))
import sqlite3
con = sqlite3.connect('bnet.db',check_same_thread = False)
c = con.cursor()
pkmn = ""
TOKEN = ''
usuarios = [line.rstrip('\n') for line in open('users.txt')]
admins = [1896312]
bot = telebot.TeleBot(TOKEN)
hora = time.strftime("%Y-%m-%d %H:%M:%S")
try:
bot.send_message(admins[0], "@BattleNet_Bot ha sido encendido")
except Exception as e:
bot.send_message(admins[0], str(e))
def listener(messages):
for m in messages:
cid = m.chat.id
uid = m.from_user.id
uname = m.from_user.username
mct = m.chat.title
ufm = m.from_user.first_name
if m.text:
mensaje = f"{{autogreen}}User:{{/green}} {ufm}\n"
if cid < 0:
mensaje += f"{{autoyellow}}Chat:{{/yellow}} {mct}\n"
mensaje += f"{{autored}}Hora:{{/red}} {hora}\n"
mensaje += f"{{autocyan}}UserID:{{/cyan}} [{uid}]"
mensaje += f"{{autoblue}} ChatID:{{/blue}} [{cid}]"
mensaje += "\n"
mensaje += f"{{automagenta}}Mensaje:{{/magenta}} {m.text}\n"
mensaje += "{autoblack}-------------------------------{/black}\n"
else:
mensaje += f"{{autored}}Hora:{{/red}} {hora}\n"
mensaje += f"{{autocyan}}UserID:{{/cyan}} [{uid}] "
mensaje += f"{{automagenta}}Mensaje:{{/magenta}} {m.text}\n"
mensaje += "{autoblack}-------------------------------{/black}\n"
if m.text.startswith("/"):
with open('log.txt', 'a') as f:
f.write(message)
with open('id.txt', 'a') as f:
f.write(f'@{uname} [{uid}]\n')
print (Color(str(mensaje)))
bot.set_update_listener(listener)
@bot.message_handler(commands=['start'])
def command_start(m):
cid = m.chat.id
comandos = "Avaible commands on @BattleNet\_Bot:\n"
comandos += "`/add` - The format of the command is `/add Battletag` where `Battletag` is your Battletag (or Blizzard ID).\n"
comandos += "`/edit` - The format of the command is `/edit Battletag` where `Battletag` is your Battletag (or Blizzard ID).\n"
comandos += "`/list` - List of the Battletags.\n"
comandos += "`/mybt` - You don't remember your Battletag? NP BRUH! I got ya!\n"
comandos += "`/del` - The format of the command is `/del My Battletag`."
bot.send_message(cid, comandos, parse_mode="Markdown")
@bot.message_handler(commands=['eg'])
def command_eg(m):
cid = m.chat.id
EG = existeGrupo(cid)
if(EG == 1):
bot.send_message(cid, "El grupo existe en la BD",
parse_mode="Markdown")
else:
bot.send_message(cid, "El grupo NO existe en la BD",
parse_mode="Markdown")
def existeGrupo(cid):
c.execute(f"SELECT COUNT(*) FROM GRUPO WHERE idGrupo ='{cid}'")
try:
for i in c:
print("Vamos a ver si el select de grupo ha devuelto algún elemento")
print(f'El resultado del select es: {i[0]}')
EG =i[0]
except Exception as e:
print(e)
print("Estamos aquí porque el select nos ha devuelto un elemento vacío")
EG = 0
return EG
def existeUser(uid):
c.execute(f"SELECT COUNT(*) FROM Usuarios WHERE idUsuario ='{uid}'")
try:
for i in c:
print("Vamos a ver si el select de Usuarios ha devuelto algún elemento")
print(f"El resultado del select es: {i[0]}")
EU =i[0]
except Exception as e:
print(e)
print("Estamos aquí porque el select nos ha devuelto un elemento vacío")
EU = 0
return EU
def existeUserGru(uid,cid):
c.execute(f"SELECT COUNT(*) FROM UsuGrupo WHERE idUsuarioFK ='{uid}' AND idGrupoFK ='{cid}'")
try:
for i in c:
print("Vamos a ver si el select de UsuGrupo ha devuelto algún elemento")
print(f"El resultado del select es: {i[0]}")
EUG =i[0]
except Exception as e:
print(e)
print("Estamos aquí porque el select nos ha devuelto un elemento vacío")
EUG = 0
print(f"Vamos a devolver el valor de EUG que es {EUG}")
return EUG
@bot.message_handler(commands=['list'])
def command_id(m):
cid = m.chat.id
uname = m.from_user.username
uid = m.from_user.id
arrayl = []
try:
print("entro en el try")
c.execute(f"SELECT idUsuario,ALIAS,Battletag FROM Usuarios INNER JOIN UsuGrupo ON Usuarios.idUsuario = UsuGrupo.idUsuarioFK WHERE UsuGrupo.idGrupoFK ='{cid}' ORDER BY Alias ASC")
print("hago el for?")
for i in c:
print("1")
Alias_resultado = f'{i[1]}: '
print("2)" + str(Alias_resultado))
btag_resultado = i[2]
print("3)" + str(btag_resultado))
p = f'*{Alias_resultado}* `{btag_resultado}`'
print("4" + str(p))
arrayl.append(p)
print("5")
f = str(arrayl).replace(" '","").replace("'","")
f = f.replace(",", "\n").replace("[","").replace("]","")
if not f:
f = "The DB is empty. Please add yourself with `/add Battletag` where `Battletag` is your Battletag or Blizzard ID."
print(str(f))
bot.send_message(cid, f'{f}', parse_mode = "Markdown")
con.commit()
else:
print(str(f))
bot.send_message(cid, f'{f}', parse_mode = "Markdown")
con.commit()
except:
bot.send_message(cid, "An error ocurred. Report to @Intervencion.")
@bot.message_handler(commands=['add'])
def command_addbtag(m):
cid = m.chat.id
uid = m.from_user.id
mct = m.chat.title
ufm = m.from_user.first_name
ulm = m.from_user.last_name
if (m.from_user.username is None):
if (ulm == None):
uname = ufm
else:
uname = f'{ufm} {ulm}'
else:
uname = m.from_user.username
if(cid>0):
bot.send_message(cid,"This only works in groups.")
elif(cid<0):
print(str(cid))
print("VAMOS A LEERLO SIN TRY")
try:
btag = m.text.split(' ', 1)[1].capitalize()
print(str(btag))
if re.match("^(\w+)#(\d{4,5})$", btag):
print("He entrado comprovando que el patrón es bueno")
print("voy a mirar si el grupo ya existe")
EG = existeGrupo(cid)
if (EG == 0):
print("El Grupo no existe, ergo tengo que crearlo")
print(m.chat.title)
print(f"El nombre del chat es: {mct}")
print("Ahora vamos a hacer el insert en el grupo")
try:
c.execute(f"INSERT INTO Grupo (idGrupo,NombreGrup) VALUES ('{cid}','{mct}')")
print(f"El id del grupo {cid}")
nocapital = uname.capitalize()
EU = existeUser(uid)
if(EU == 0):
c.execute(f"INSERT INTO Usuarios (idUsuario,ALIAS,Battletag) VALUES ('{uid}','@{nocapital}','{btag}')")
print("ESTOY DEBAJO DEL IF de ENTRE USUARIO = 0")
c.execute(f"INSERT INTO UsuGrupo(idUsuarioFK,idGrupoFK) VALUES ('{uid}','{cid}')")
bot.send_message(cid, f"*{uname}* has been added to the DB with Battletag *{btag}*.", parse_mode="Markdown")
con.commit()
except sqlite3.Error as e:
print(e)
bot.send_message(cid, f"*{uname}* has been added to the DB with Battletag *{btag}*.", parse_mode="Markdown")
elif(EG == 1):
print("El grupo sí existe")
nocapital = uname.capitalize()
try:
EU = existeUser(uid)
if(EU == 0):
c.execute(f"INSERT INTO Usuarios (idUsuario,ALIAS,Battletag) VALUES ('{uid}', '@{nocapital}','{btag}')")
print("ESTOY DEBAJO DEL IF de ENTRE USUARIO = 0 Y AHORA VOY A COMPROBAR EUG")
EUG = existeUserGru(uid,cid)
print("Sabemos que EUG vale " + str(EUG))
if(EUG == 0):
print("Entro cuando no existe la combinación usuario - grupo")
c.execute(f"INSERT INTO UsuGrupo(idUsuarioFK,idGrupoFK) VALUES ('{uid}','{cid}')")
bot.send_message(cid, f"*{uname}* has been added to the DB with Battletag *{btag}*.", parse_mode="Markdown")
if(EUG == 1):
bot.send_message(cid, "You have already introduced your Battletag in this group, if you want to edit it use `/edit`", parse_mode="Markdown")
con.commit()
except sqlite3.Error as e:
print(e)
bot.send_message(cid, "You have already introduced your Battletag in this group, if you want to edit it use `/edit`", parse_mode="Markdown")
else:
bot.send_message(cid, "ElseError: The format of the command is `/add Battletag` where `Battletag` is your Battletag (or Blizzard ID).", parse_mode="Markdown")
except:
bot.send_message(cid, "ExceptError: The format of the command is `/add Battletag` where `Battletag` is your Battletag (or Blizzard ID).", parse_mode="Markdown")
@bot.message_handler(commands=['edit'])
def command_editbtag(m):
cid = m.chat.id
uid = m.from_user.id
ufm = m.from_user.first_name
ulm = m.from_user.last_name
if (m.from_user.username is None):
uname = f"{ufm} {ulm}"
else:
uname = m.from_user.username
try:
btag = m.text.split(' ', 1)[1].capitalize()
print(str(btag))
if re.match("^(\w+)#(\d{4,5})$", btag):
try:
c.execute(f"UPDATE Usuarios SET 'Battletag' = '{btag}','Alias'='@{uname}' WHERE idUsuario = {uid}")
bot.send_message(cid, f"*{uname}* now have Battletag *{btag}*.", parse_mode = "Markdown")
con.commit()
except sqlite3.Error:
bot.send_message(cid, "ExceptError: The format of the command is `/add Battletag` where `Battletag` is your Battletag (or Blizzard ID).", parse_mode="Markdown")
else:
bot.send_message(cid, "ElseError: The format of the command is `/add Battletag` where `Battletag` is your Battletag (or Blizzard ID).", parse_mode="Markdown")
except:
bot.send_message(cid, "ExceptError: The format of the command is `/add Battletag` where `Battletag` is your Battletag (or Blizzard ID).", parse_mode="Markdown")
@bot.message_handler(commands=['del'])
def command_deletebtag(m):
cid = m.chat.id
uid = m.from_user.id
ufm = m.from_user.first_name
ulm = m.from_user.last_name
if (m.from_user.username is None):
if (ulm is None):
uname = ufm
else:
uname = f'{ufm} {ulm}'
else:
uname = m.from_user.username
try:
btag = m.text.split(' ', 1)[1].upper()
print(btag)
if (str(btag).startswith("MY BATTLETAG")):
reply = "Your Battletag is not in the DB."
try:
print("1")
c.execute(f"SELECT Battletag FROM Usuarios WHERE idUsuario ='{uid}'")
print("2")
for i in c:
print("3")
if i[0] is None:
print("4")
reply = "Your Battletag is not in the DB."
else:
print("5")
btag = i[0]
c.execute(f"DELETE FROM Usuarios WHERE Battletag = '{btag}'")
print("11")
c.execute(f"DELETE FROM UsuGrupo WHERE idUsuarioFK ='{uid}'")
print("12")
reply = "Your Battletag have been deleted from the BD."
bot.send_message(cid, reply, parse_mode = "Markdown")
con.commit()
except sqlite3.Error:
bot.send_message(cid, "ExceptError: The format of the command is `/del My Battletag`.", parse_mode="Markdown")
else:
bot.send_message(cid, "ElseError: The format of the command is `/del My Battletag`.", parse_mode="Markdown")
except:
bot.send_message(cid, "ExceptError: The format of the command is `/del My Battletag`.", parse_mode="Markdown")
@bot.message_handler(commands=['mybt'])
def command_mibtag(m):
cid = m.chat.id
uid = m.from_user.id
ufm = m.from_user.first_name
ulm = m.from_user.last_name
if (m.from_user.username is None):
uname = f"{ufm} {ulm}"
else:
uname = m.from_user.username
try:
c.execute(f"SELECT ALIAS,Battletag from Usuarios WHERE idUsuario={uid}")
for i in c:
Alias_resultado = f"{i[0]} "
btag_resultado = i[1]
if (btag_resultado == None):
bot.send_message(cid, f'Your Battletag is not in the DB.', parse_mode = "Markdown")
con.commit()
else:
bot.send_message(cid, f'*{Alias_resultado}*: `{btag_resultado}`', parse_mode = "Markdown")
con.commit()
except:
bot.send_message(cid, "Your Battletag is not in the DB.", parse_mode = "Markdown")
from config import *
@bot.message_handler(commands=['exec'])
def command_exec(m):
cid = m.chat.id
uid = m.from_user.id
if uid in admins:
if len(m.text.split()) == 1:
bot.send_message(
cid,
"Uso: /exec _<code>_ - Ejecuta el siguiente bloque de código.",
parse_mode="Markdown")
return
cout = StringIO()
sys.stdout = cout
cerr = StringIO()
sys.stderr = cerr
code = ' '.join(m.text.split(' ')[1:])
try:
exec(code)
except Exception as e:
bot.send_message(cid, send_exception(e), parse_mode="Markdown")
else:
if cout.getvalue():
bot.send_message(cid, str(cout.getvalue()))
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
@bot.message_handler(commands=['restart'])
def command_restart(m):
if m.from_user.id in admins:
try:
os.execl(sys.executable, sys.executable, *sys.argv)
except:
bot.send_message(cid, "Mal código tete")
else:
bot.send_message(cid, "Comando reservado a SU.")
bot.skip_pending = True
bot.polling(none_stop=True)