File size: 7,580 Bytes
ebd6e65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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("<b>¡Se le ha asignado el papel de administrador!</b>", parse_mode="HTML")
    if not user_id in users:
        await event.reply("<b>¡Acceso no autorizado!</b>", parse_mode="HTML")
        raise ValueError(f"({user_id}) No es un usuario autorizado")
    if "/start" == text:
        await event.reply("<b><{Bienvenid@ a BitFlush}></b>\n<code>Bot privado de descargas gratis automatizado...</code>", 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("<b>DESCARGANDO</b>",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"<b>[{round((current/total)*100)}%] {nam}</b>"
                            bar = f"<b>[</b>"
                            prog = round(int(15*(current/total)),0)
                            deprog = 15-prog
                            bar += ("-"*prog)+"|"
                            bar += ("-"*deprog)+"<b>]</b>"
                            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"<b>✓ DESCARGADO</b>\n<code>{name}</code>", 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 = "<b>↓DESCARGANDO</b>"
        if type == "up":
            text1 = "<b>↑SUBIENDO</b>"
        bar = f"<i>{round((current/total)*100,1)}%</i> <b>[</b>"
        prog = round(int(15*(current/total)),0)
        deprog = 15-prog
        bar += ("-"*prog)+"|"
        bar += ("-"*deprog)+"<b>]</b>"
        if len(process) > 1:
            infopro = f"\n+{len(process)-1} procesos..."
        else:
            infopro = ""
        if basedata[code+"auto-act"]:
            alertact = ""
        else:
            alertact = "\n<i> ∆ Siempre puede usar el botón de Actualizar para ver el progreso.</i>"
        try:
            await client.edit_message(user_id, msg_id, f"{text1}\n\n<b>Nombre:</b> <code>{name}</code>\n<b>Progreso:</b> {bar}\n<b>Tamaño:</b> <code>{sizeof_fmt(total)}</code>\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\n<b>Nombre:</b> <code>{name}</code>\n<b>Progreso:</b> {bar}\n<b>Tamaño:</b> <code>{sizeof_fmt(total)}</code>\n\n<b>[{random.randint(10000,99999)}] ✓ Actualizado</b>{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()