from telethon import events, utils, Button, TelegramClient
import asyncio, os, requests, time, re, sys, threading, random, subprocess, json
from bs4 import BeautifulSoup
from FastTelethon import download_file, upload_file
api_id = os.getenv("API_ID")
api_hash = os.getenv("API_HASH")
token = os.getenv("BOT_TOKEN")
client = TelegramClient("BitFlush", api_id, api_hash)
class Uploader:
def __init__(self, mode, host, username, password, unique, hash):
self.mode = mode
self.host = host
self.username = username
self.password = password
self.unique = unique
self.hash = hash
class Timer:
def __init__(self, time_between=2):
self.start_time = time.time()
self.time_between = time_between
def can_send(self):
if time.time() > (self.start_time + self.time_between):
self.start_time = time.time()
return True
return False
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.2f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.2f%s%s" % (num, 'Yi', suffix)
if not os.path.exists("./telegram"):
os.mkdir("./telegram")
client.start(bot_token=token)
users = []
process = []
basedata = {}
@client.on(events.NewMessage())
async def mybot(event):
global basedata
global process
text = event.raw_text
user_id = event.message.chat.id
msg_id = event.message.id
user_name = event.message.chat.username
if len(users) == 0:
users.append(user_id)
await event.reply("¡Se le ha asignado el papel de administrador!", parse_mode="HTML")
if not user_id in users:
await event.reply("¡Acceso no autorizado!", parse_mode="HTML")
raise ValueError(f"({user_id}) No es un usuario autorizado")
if "/start" == text:
await event.reply("<{Bienvenid@ a BitFlush}>\nBot privado de descargas gratis automatizado...", parse_mode="HTML")
elif "/add " in text:
user = int(text.replace("/add", ""))
users.append(user)
await event.reply("Usuario añadido")
elif "/ban " in text:
user = int(text.replace("/ban", ""))
users.append(user)
await event.reply("Usuario borrado")
elif event.document and user_id in users:
code = str(random.randint(100000,999999))
process.append(code)
while not code == process[0]:
await asyncio.sleep(3)
basedata[code] = "down:0/0"+"|CARGANDO..."
basedata[code+"auto-act"] = True
msg = await event.reply("DESCARGANDO",parse_mode="HTML",buttons=[Button.inline("CANCELAR",b'del|'+code.encode('utf-8'))])
caption = event.message.message
mime_type = str(event.media.document.mime_type)
extension = mime_type.split("/")[1]
if event.file.name:
name = event.file.name
else:
if caption:
name = str(caption).split("\n")[0]+"."+extension
else:
name = "document_"+str(time.strftime("%d_%H_%M_%S"))+"."+extension
if os.path.exists("./files/"+name):
name = name.replace(".", f"_{str(time.strftime('%d%H%M%S'))}.")
if len(name) > 20:
nam = name[:10]+"..."
else:
nam = name
timer = Timer()
async def progress_bar(current, total):
if not code in process:
raise ValueError(f"Se detuvo el proceso {code}")
basedata[code] = "down:"+str(current)+"/"+str(total)+"|"+nam
if basedata[code+"auto-act"]:
text1 = f"[{round((current/total)*100)}%] {nam}"
bar = f"["
prog = round(int(15*(current/total)),0)
deprog = 15-prog
bar += ("-"*prog)+"|"
bar += ("-"*deprog)+"]"
if len(process) > 1:
infopro = "+"+str(len(process)-1)
else:
infopro = "0"
if timer.can_send():
await msg.edit(f"{text1}\n[{infopro}]{bar}", parse_mode="HTML", buttons=[Button.inline("CANCELAR", b'del|'+code.encode("utf8"))])
with open("./telegram/down_"+name, "wb") as out:
await download_file(event.client, event.document, out, progress_callback=progress_bar)
await msg.edit(f"✓ DESCARGADO\n{name}", parse_mode="HTML")
os.rename("./telegram/down_"+name, "./telegram/"+name)
basedata[code] = None
process.remove(code)
@client.on(events.CallbackQuery)
async def callback_query(event):
global basedata
global process
user_id = event.query.user_id
msg_id = event.query.msg_id
data = event.query.data.decode("utf-8")
orden = str(data).split("|")[0]
if orden == "autoact":
code = str(data).split("|")[1]
basedata[code+"auto-act"] = True
await client.edit_message(user_id, msg_id, "Auto-Actualización activada", parse_mode="HTML")
if orden == "del":
code = str(data).split("|")[1]
try:
process.remove(code)
except:
None
await client.delete_messages(user_id, msg_id)
if orden == "act":
code = str(data).split("|")[1]
if not code in process:
raise ValueError("Se intentó actualizar un proceso ya completado")
rsplit = basedata[code].split(":")
type = rsplit[0]
content = rsplit[1].split("|")
data = content[0].split("/")
name = content[1]
current = int(data[0])
total = int(data[1])
if total == 0:
total = 1
if type == "down":
text1 = "↓DESCARGANDO"
if type == "up":
text1 = "↑SUBIENDO"
bar = f"{round((current/total)*100,1)}% ["
prog = round(int(15*(current/total)),0)
deprog = 15-prog
bar += ("-"*prog)+"|"
bar += ("-"*deprog)+"]"
if len(process) > 1:
infopro = f"\n+{len(process)-1} procesos..."
else:
infopro = ""
if basedata[code+"auto-act"]:
alertact = ""
else:
alertact = "\n ∆ Siempre puede usar el botón de Actualizar para ver el progreso."
try:
await client.edit_message(user_id, msg_id, f"{text1}\n\nNombre: {name}\nProgreso: {bar}\nTamaño: {sizeof_fmt(total)}\n{alertact}{infopro}", parse_mode="HTML", buttons=[[Button.inline("ACTUALIZAR", b'act|'+code.encode("utf8")),Button.inline("CANCELAR", b'del|'+code.encode("utf8"))],[Button.inline("AUTO-ACTUALIZAR",b'autoact|'+code.encode('utf-8'))]])
except:
await client.edit_message(user_id, msg_id, f"{text1}\n\nNombre: {name}\nProgreso: {bar}\nTamaño: {sizeof_fmt(total)}\n\n[{random.randint(10000,99999)}] ✓ Actualizado{infopro}", parse_mode="HTML", buttons=[[Button.inline("ACTUALIZAR", b'act|'+code.encode("utf8")), Button.inline("CANCELAR", b'del|'+code.encode("utf8"))],[Button.inline("AUTO-ACTUALIZAR",b'autoact|'+code.encode('utf-8'))]])
print("CONECTADO")
client.run_until_disconnected()