示例#1
0
async def get_string_variable(var_name, menu, callback_name, session_id):
    # handle the vars having string value
    # condition for rclone config

    val = get_val(var_name)
    if var_name == "RCLONE_CONFIG":
        db = tordb
        _, val1 = db.get_variable(var_name)
        if val1 is not None:
            val = "Custom file is loaded."

    msg = var_name + " " + str(val)
    menu.append([
        KeyboardButtonCallback(
            msg, f"settings {callback_name} {session_id}".encode("UTF-8"))
    ])

    # Just in case
    return val
    async def update_message(self):
        msg = await self.create_message()
        if self._prevmsg == msg:
            return
        
        self._prevmsg = msg
        
        try:
            data = "torcancel megadl {} {}".format(
                self._gid,
                self._omess.sender_id
            )
            await self._message.edit(msg,parse_mode="html",buttons=[KeyboardButtonCallback("Cancel Mega DL",data=data.encode("UTF-8"))]) 

        except MessageNotModifiedError as e:
            torlog.debug("{}".format(e))
        except FloodWaitError as e:
            torlog.error("{}".format(e))
        except Exception as e:
            torlog.info("Not expected {}".format(e))
示例#3
0
    async def update_message(self):
        msg = await self.create_message()
        if self._prevmsg == msg:
            return

        self._prevmsg = msg

        try:
            data = "torcancel aria2 {} {}".format(self._gid,
                                                  self._omess.sender_id)
            await self._message.edit(msg,
                                     parse_mode="html",
                                     buttons=[
                                         KeyboardButtonCallback(
                                             "Cancel Direct Leech",
                                             data=data.encode("UTF-8"))
                                     ])

        except (MessageNotModifiedError, FloodWaitError) as e:
            torlog.error("{}".format(e))
async def get_string_variable(var_name, menu, callback_name, sender_id):
    # handle the vars having string value
    # condition for rclone config

    if var_name == "RCLONE_CONFIG":
        rfile = user_db.get_rclone(sender_id)
        if rfile is False:
            val = "File is not loaded."
        else:
            val = "File is Loaded"
            #val = "Custom file is loaded."
    else:
        val = user_db.get_var(var_name, sender_id)

    msg = var_name + " " + str(val)
    menu.append([
        KeyboardButtonCallback(
            msg, f"usettings {callback_name} {sender_id}".encode("UTF-8"))
    ])

    # Just in case
    return val
示例#5
0
async def handle_ytdl_playlist(e: MessageLike) -> None:
    if not e.is_reply:
        await e.reply("Reply to a youtube playlist link.")
        return
    url = await e.get_reply_message()
    url = url.text.strip()
    cmd = f"youtube-dl -i --flat-playlist --dump-single-json {url}"

    tsp = time.time()
    buts = [[
        KeyboardButtonCallback("To Telegram", data=f"ytdlselect tg {tsp}")
    ]]
    if await get_config() is not None:
        buts.append([
            KeyboardButtonCallback("To Drive", data=f"ytdlselect drive {tsp}")
        ])

    msg = await e.reply(
        f"Processing your Youtube Playlist download request.\nChoose destination. Default destination will be chosen in {get_val('DEFAULT_TIMEOUT')}.",
        buttons=buts)

    choice = await get_ytdl_choice(e, tsp)  #blocking call
    msg = await msg.edit("Processing your Youtube Playlist download request.",
                         buttons=None)
    await asyncio.sleep(1)

    # cancel the playlist if time exceed 5 mins
    try:
        out, err = await asyncio.wait_for(cli_call(cmd), 300)
    except asyncio.TimeoutError:
        await msg.edit(
            "Processing time exceeded... The playlist seem to long to be worked with 😢\n If the playlist is short and you think its error report back."
        )
        return

    if err:
        await msg.edit(
            f"Failed to load the playlist with the error:- <code>{err}</code>",
            parse_mode="html")
        return

    try:
        pldata = json.loads(out)
        entities = pldata.get("entries")
        if len(entities) <= 0:
            await msg.edit(
                "Cannot load the videos from this playlist ensure that the playlist is not <code>'My Mix or Mix'</code>. It shuold be a public or unlisted youtube playlist."
            )
            return

        entlen = len(entities)
        keybr = list()

        # limit the max vids
        if entlen > get_val("MAX_YTPLAYLIST_SIZE"):

            await msg.edit(
                f"Playlist too large max {get_val('MAX_YTPLAYLIST_SIZE')} vids allowed as of now. This has {entlen}"
            )
            return

        # format> ytdlplaylist | quality | suid | sender_id
        suid = str(time.time()).replace(".", "")

        for i in ["144", "240", "360", "480", "720", "1080", "1440", "2160"]:
            keybr.append([
                KeyboardButtonCallback(
                    text=f"{i}p All videos",
                    data=f"ytdlplaylist|{i}|{suid}|{e.sender_id}|{choice}")
            ])

        keybr.append([
            KeyboardButtonCallback(
                text=f"Best All videos",
                data=f"ytdlplaylist|best|{suid}|{e.sender_id}|{choice}")
        ])

        keybr.append([
            KeyboardButtonCallback(
                text="Best all audio only. [340k]",
                data=f"ytdlplaylist|320k|{suid}|{e.sender_id}|{choice}")
        ])
        keybr.append([
            KeyboardButtonCallback(
                text="Medium all audio only. [128k]",
                data=f"ytdlplaylist|128k|{suid}|{e.sender_id}|{choice}")
        ])
        keybr.append([
            KeyboardButtonCallback(
                text="Worst all audio only. [64k]",
                data=f"ytdlplaylist|64k|{suid}|{e.sender_id}|{choice}")
        ])

        await msg.edit(f"Found {entlen} videos in the playlist.",
                       buttons=keybr)

        path = os.path.join(os.getcwd(), 'userdata')

        if not os.path.exists(path):
            os.mkdir(path)

        path = os.path.join(path, f"{suid}.json")

        with open(path, "w", encoding="UTF-8") as file:
            file.write(json.dumps(pldata))

    except:
        await msg.edit(
            "Failed to parse the playlist. Check log if you think its error.")
        torlog.exception("Playlist Parse failed")
示例#6
0
async def handle_ytdl_callbacks(e: MessageLike):
    # ytdlsmenu | format | sender_id | suid | dest
    data = e.data.decode("UTF-8")
    data = data.split("|")

    if data[0] == "ytdlsmenu":
        if data[2] != str(e.sender_id):
            await e.answer("Not valid user, Dont touch.")
            return

        path = os.path.join(os.getcwd(), 'userdata', data[3] + ".json")
        if os.path.exists(path):
            with open(path) as file:
                ytdata = json.loads(file.read())
                buttons = list()
                if data[1] == "audios":
                    for i in ["64K", "128K", "320K"]:
                        text = f"{i} [MP3]"
                        cdata = f"ytdldfile|{i}|{e.sender_id}|{data[3]}|{data[4]}"
                        buttons.append([
                            KeyboardButtonCallback(text, cdata.encode("UTF-8"))
                        ])
                else:
                    j = 0
                    for i in ytdata.get("formats"):
                        c_format = i.get("format_note")
                        format_id = i.get('format_id')
                        height = i.get('format')
                        if c_format is None:
                            c_format = str(i.get("height"))
                            format_id = f"xxother{j}"
                            height = i.get('format')
                        if not c_format == data[1]:
                            continue

                        if not height:
                            continue

                        text = f"{height} [{i.get('ext')}] [{human_readable_bytes(i.get('filesize'))}] {str(i.get('vcodec'))}"
                        cdata = f"ytdldfile|{format_id}|{e.sender_id}|{data[3]}|{data[4]}"

                        buttons.append([
                            KeyboardButtonCallback(text, cdata.encode("UTF-8"))
                        ])
                        j += 1

                buttons.append([
                    KeyboardButtonCallback(
                        "Go Back 😒",
                        f"ytdlmmenu|{data[2]}|{data[3]}|{data[4]}")
                ])
                await e.edit(
                    f"Files for quality {data[1]}, at the end it is the Video Codec. Mostly prefer the last one with you desired extension if you want streamable video. Try rest if you want.",
                    buttons=buttons)

        else:
            await e.answer("Try again something went wrong.", alert=True)
            await e.delete()
    elif data[0] == "ytdlmmenu":
        if data[1] != str(e.sender_id):
            await e.answer("Not valid user, Dont touch.")
            return
        path = os.path.join(os.getcwd(), 'userdata', data[2] + ".json")
        if os.path.exists(path):
            with open(path, encoding="UTF-8") as file:
                ytdata = json.loads(file.read())
                await create_quality_menu("", await e.get_message(), e, ytdata,
                                          data[2])

        else:
            await e.answer("Try again something went wrong.", alert=True)
            await e.delete()
示例#7
0
async def addcmd(event):
    user = await bot(GetFullUserRequest(event.sender_id))
    async with bot.conversation(user.user.id) as conv:
        await event.respond(
            f'Отлично! Теперь пришли мне ссылку на товар.\n__Без корявого перевода плез, я не умею это убирать.__'
        )
        response = conv.wait_event(
            events.NewMessage(incoming=True, from_users=user.user.id))
        response = await response
        link = f"[{response.text}]({response.text})"
        await event.respond(
            'А теперь придумай мне название для этого говна сука.')
        response = conv.wait_event(
            events.NewMessage(incoming=True, from_users=user.user.id))
        response = await response
        name = response.text
        await event.respond('Заебись! Кто производитель этого говна ебаного?')
        response = conv.wait_event(
            events.NewMessage(incoming=True, from_users=user.user.id))
        response = await response
        vendor = ('#' + response.text).replace(' ', '_')
        click_button1 = KeyboardButtonCallback("Мобильные телефоны",
                                               data=b'telephone')
        click_button2 = KeyboardButtonCallback("Бытовая электроника",
                                               data=b'byt_electr')
        click_button3 = KeyboardButtonCallback("Бытовая техника",
                                               data=b'byt_tehn')
        click_button4 = KeyboardButtonCallback("Безопасность и защита",
                                               data=b'bezopas')
        click_button5 = KeyboardButtonCallback("Компьютер и офис",
                                               data=b'computer')
        click_button6 = KeyboardButtonCallback("Багаж и сумки", data=b'bagazh')
        click_button7 = KeyboardButtonCallback("Спорт", data=b'sport')
        click_button8 = KeyboardButtonCallback("Развлечения",
                                               data=b'razvle4en')
        click_button9 = KeyboardButtonCallback("Красота и здоровье",
                                               data=b'krasota')
        click_button10 = KeyboardButtonCallback("Маски", data=b'maski')
        click_button11 = KeyboardButtonCallback("Одежда", data=b'odezhda')
        click_button12 = KeyboardButtonCallback("Другое", data=b'other')
        line1 = KeyboardButtonRow(buttons=[click_button1, click_button2])
        line2 = KeyboardButtonRow(buttons=[click_button3, click_button4])
        line3 = KeyboardButtonRow(buttons=[click_button5, click_button6])
        line4 = KeyboardButtonRow(buttons=[click_button7, click_button8])
        line5 = KeyboardButtonRow(buttons=[click_button9, click_button10])
        line6 = KeyboardButtonRow(buttons=[click_button11, click_button12])
        btns = ReplyInlineMarkup(
            rows=[line1, line2, line3, line4, line5, line6])
        await bot.send_message(
            event.chat.id,
            'Ахуенчик! Теперь выбери категорию, в которой находится товар.',
            buttons=btns)
        response = conv.wait_event(events.CallbackQuery)
        response = await response
        data = response.data.decode('utf-8')
        if data == 'telephone':
            category = '#Мобильные_телефоны'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'byt_electr':
            category = '#Бытовая_электроника'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'byt_tehn':
            category = '#Бытовая_техника'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'bezopas':
            category = '#Безопасность_и_защита'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'computer':
            category = '#Компьютер_и_офис'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'bagazh':
            category = '#Багаж_и_суки'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'sport':
            category = '#Спорт'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'razvle4en':
            category = '#Развлечения'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'krasota':
            category = '#Красота_и_здоровье'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'maski':
            category = '#Маски'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'odezhda':
            category = '#Одежда'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        elif data == 'other':
            category = '#Другое'
            try:
                ppl = user.user.first_name
                await publish(name, vendor, category, link, ppl)
            except Exception:
                await response.answer(message='Fail')
                return await event.respond(
                    'Неудачно высрал на канал бля программист хуесос ебливый нахуй'
                )
            await response.answer(message='OK')
            return await event.respond('Удачно высрал на канал ебать.')
        else:
            await event.respond('Ебать ты как из палаты выбрался шизоид ебаный'
                                )
            return await response.answer(
                message='Ты как ебать это сделал нахуй')
示例#8
0
async def handle_server_command(message):
    print(type(message))
    if isinstance(message, events.CallbackQuery.Event):
        callbk = True
    else:
        callbk = False

    try:
        # Memory
        mem = psutil.virtual_memory()
        memavailable = Human_Format.human_readable_bytes(mem.available)
        memtotal = Human_Format.human_readable_bytes(mem.total)
        mempercent = mem.percent
        memfree = Human_Format.human_readable_bytes(mem.free)
    except:
        memavailable = "N/A"
        memtotal = "N/A"
        mempercent = "N/A"
        memfree = "N/A"

    try:
        # Frequencies
        cpufreq = psutil.cpu_freq()
        freqcurrent = cpufreq.current
        freqmax = cpufreq.max
    except:
        freqcurrent = "N/A"
        freqmax = "N/A"

    try:
        # Cores
        cores = psutil.cpu_count(logical=False)
        lcores = psutil.cpu_count()
    except:
        cores = "N/A"
        lcores = "N/A"

    try:
        cpupercent = psutil.cpu_percent()
    except:
        cpupercent = "N/A"

    try:
        # Storage
        usage = shutil.disk_usage("/")
        totaldsk = Human_Format.human_readable_bytes(usage.total)
        useddsk = Human_Format.human_readable_bytes(usage.used)
        freedsk = Human_Format.human_readable_bytes(usage.free)
    except:
        totaldsk = "N/A"
        useddsk = "N/A"
        freedsk = "N/A"

    try:
        upb, dlb = await get_transfer()
        dlb = Human_Format.human_readable_bytes(dlb)
        upb = Human_Format.human_readable_bytes(upb)
    except:
        dlb = "N/A"
        upb = "N/A"

    diff = time.time() - uptime
    diff = Human_Format.human_readable_timedelta(diff)

    if callbk:
        msg = (f"<b>BOT UPTIME:-</b> {diff}\n\n"
               "<b>CPU STATS:-</b>\n"
               f"Cores: {cores} Logical: {lcores}\n"
               f"CPU Frequency: {freqcurrent}  Mhz Max: {freqmax}\n"
               f"CPU Utilization: {cpupercent}%\n"
               "\n"
               "<b>STORAGE STATS:-</b>\n"
               f"Total: {totaldsk}\n"
               f"Used: {useddsk}\n"
               f"Free: {freedsk}\n"
               "\n"
               "<b>MEMORY STATS:-</b>\n"
               f"Available: {memavailable}\n"
               f"Total: {memtotal}\n"
               f"Usage: {mempercent}%\n"
               f"Free: {memfree}\n"
               "\n"
               "<b>TRANSFER INFO:</b>\n"
               f"Download: {dlb}\n"
               f"Upload: {upb}\n")
        await message.edit(msg, parse_mode="html", buttons=None)
    else:
        try:
            storage_percent = round((usage.used / usage.total) * 100, 2)
        except:
            storage_percent = 0

        msg = (
            f"<b>BOT UPTIME:-</b> {diff}\n\n"
            f"CPU Utilization: {progress_bar(cpupercent)} - {cpupercent}%\n\n"
            f"Storage used:- {progress_bar(storage_percent)} - {storage_percent}%\n"
            f"Total: {totaldsk} Free: {freedsk}\n\n"
            f"Memory used:- {progress_bar(mempercent)} - {mempercent}%\n"
            f"Total: {memtotal} Free: {memfree}\n\n"
            f"Transfer Download:- {dlb}\n"
            f"Transfer Upload:- {upb}\n")
        await message.reply(msg,
                            parse_mode="html",
                            buttons=[[
                                KeyboardButtonCallback("Get detailed stats.",
                                                       "fullserver")
                            ]])
示例#9
0
async def get_sub_menu(msg, sub_name, session_id, menu):
    menu.append([
        KeyboardButtonCallback(
            msg, f"settings {sub_name} {session_id}".encode("UTF-8"))
    ])
示例#10
0
async def handle_leech_command(e):

    if not e.is_reply:
        await e.reply("Reply to a link or magnet")
    else:
        rclone = False
        tsp = time.time()
        buts = [[
            KeyboardButtonCallback("To Telegram", data=f"leechselect tg {tsp}")
        ]]
        if await get_config() is not None:
            buts.append([
                KeyboardButtonCallback("To Drive",
                                       data=f"leechselect drive {tsp}")
            ])
        # tsp is used to split the callbacks so that each download has its own callback
        # cuz at any time there are 10-20 callbacks linked for leeching XD

        buts.append([
            KeyboardButtonCallback("Upload in a ZIP.[Toggle]",
                                   data=f"leechzip toggle {tsp}")
        ])
        buts.append([
            KeyboardButtonCallback("Extract from ZIP.[Toggle]",
                                   data=f"leechzipex toggleex {tsp}")
        ])

        conf_mes = await e.reply(
            "<b>First click if you want to zip the contents or extract as an archive (only one will work at a time) then. </b>\n<b>Choose where to uploadyour files:- </b>\nThe files will be uploaded to default destination after 60 sec of no action by user.",
            parse_mode="html",
            buttons=buts)

        # zip check in background
        ziplist = await get_zip_choice(e, tsp)
        zipext = await get_zip_choice(e, tsp, ext=True)

        # blocking leech choice
        choice = await get_leech_choice(e, tsp)

        # zip check in backgroud end
        await get_zip_choice(e, tsp, ziplist, start=False)
        await get_zip_choice(e, tsp, zipext, start=False, ext=True)
        is_zip = ziplist[1]
        is_ext = zipext[1]

        # Set rclone based on choice
        if choice == "drive":
            rclone = True
        else:
            rclone = False

        await conf_mes.delete()

        if rclone:
            if get_val("RCLONE_ENABLED"):
                await check_link(e, rclone, is_zip, is_ext)
            else:
                await e.reply("<b>DRIVE IS DISABLED BY THE ADMIN</b>",
                              parse_mode="html")
        else:
            if get_val("LEECH_ENABLED"):
                await check_link(e, rclone, is_zip, is_ext)
            else:
                await e.reply("<b>TG LEECH IS DISABLED BY THE ADMIN</b>",
                              parse_mode="html")
async def handle_user_settings(e,
                               edit=False,
                               msg="",
                               submenu=None,
                               sender_id=None):
    # this function creates the menu
    # and now submenus too
    if sender_id is None:
        sender_id = e.sender_id
    session_id = None

    menu = [
        #[KeyboardButtonCallback(yes+" Allow TG Files Leech123456789-","settings data".encode("UTF-8"))], # for ref
    ]

    if submenu is None:
        await get_bool_variable("FORCE_DOCUMENTS", "FORCE_DOCUMENTS", menu,
                                "fdocs", sender_id)  #
        #await get_string_variable("RCLONE_CONFIG",menu,"rcloneconfig",session_id)
        await get_sub_menu("☁️ Open Rclone Menu ☁️", "rclonemenu", sender_id,
                           menu)  #
        await get_sub_menu("🖼 Open Thumbnail Menu 🖼", "thumbmenu", sender_id,
                           menu)  #
        # thumbnail
        menu.append([
            KeyboardButtonCallback(
                "Close Menu",
                f"usettings selfdest {sender_id}".encode("UTF-8"))
        ])

        if edit:
            rmess = await e.edit(header + "\nEnjoiii.\n" + msg,
                                 parse_mode="html",
                                 buttons=menu,
                                 link_preview=False,
                                 file="toolkit.jpg")
        else:
            rmess = await e.reply(header + "\nEnjoiii.\n",
                                  parse_mode="html",
                                  buttons=menu,
                                  link_preview=False,
                                  file="toolkit.jpg")
    elif submenu == "rclonemenu":
        rcval = await get_string_variable("RCLONE_CONFIG", menu,
                                          "rcloneconfig", sender_id)
        if rcval != "None":
            # create a all drives menu
            if not "not loaded" in rcval:

                path = user_db.get_rclone(sender_id)

                conf = configparser.ConfigParser()
                conf.read(path)
                #menu.append([KeyboardButton("Choose a default drive from below")])
                def_drive = user_db.get_var("DEF_RCLONE_DRIVE", sender_id)

                for j in conf.sections():
                    prev = ""
                    if j == def_drive:
                        prev = yes

                    if "team_drive" in list(conf[j]):
                        menu.append([
                            KeyboardButtonCallback(
                                f"{prev}{j} - TD",
                                f"usettings change_drive {j} {sender_id}")
                        ])
                    else:
                        menu.append([
                            KeyboardButtonCallback(
                                f"{prev}{j} - ND",
                                f"usettings change_drive {j} {sender_id}")
                        ])

        await get_sub_menu("Go Back ⬅️", "mainmenu", sender_id, menu)
        menu.append([
            KeyboardButtonCallback(
                "Close Menu",
                f"usettings selfdest {sender_id}".encode("UTF-8"))
        ])
        if edit:
            rmess = await e.edit(
                header +
                "\nIts recommended to lock the group before setting vars.\n" +
                msg,
                parse_mode="html",
                buttons=menu,
                link_preview=False)

    elif submenu == "thumbmenu":
        thumb = user_db.get_thumbnail(sender_id)
        if thumb is not False:
            menu.append([
                KeyboardButtonCallback(
                    "Change Thumbnail",
                    f"usettings setthumb {sender_id}".encode("UTF-8"))
            ])
            await get_bool_variable("DISABLE_THUMBNAIL", "Disable Thumbnail",
                                    menu, "disablethumb", sender_id)
            await get_sub_menu("Go Back ⬅️", "mainmenu", sender_id, menu)
            menu.append([
                KeyboardButtonCallback(
                    "Close Menu",
                    f"usettings selfdest {sender_id}".encode("UTF-8"))
            ])
            await e.edit(header + "\nManage your thumbnail(s) on the fly.",
                         file=thumb,
                         buttons=menu,
                         parse_mode="html")
        else:
            menu.append([
                KeyboardButtonCallback(
                    "Set Thumbnail.",
                    f"usettings setthumb {sender_id}".encode("UTF-8"))
            ])
            await get_sub_menu("Go Back ⬅️", "mainmenu", sender_id, menu)
            menu.append([
                KeyboardButtonCallback(
                    "Close Menu",
                    f"usettings selfdest {sender_id}".encode("UTF-8"))
            ])
            await e.edit(header + "\nManage your thumbnail(s) on the fly.",
                         parse_mode="html",
                         buttons=menu)
示例#12
0
async def text_detect(event):
    sender = await event.get_sender()
    name = utils.get_display_name(sender)
    channel = sender.id
    text_e = event.message.text

    conn = await user_info.create_connection()
    u = await user_info.find_user(conn, channel, '', 1)
    await user_info.close_connection(conn)

    if text_e == '#️⃣ h-tag':  # hashtag
        m = await bot.send_message(channel,
                                   'Выберите hashtag',
                                   buttons=bl_as_modul.hsht_but)
        await bot.delete_messages(channel, m.id - 1)
    elif text_e == '🛠  Tools':
        m = await bot.send_message(channel,
                                   'Tools',
                                   buttons=bl_as_modul.tools_but)
        await bot.delete_messages(channel, m.id - 1)
    elif text_e == '🚑   Help':  # Помощь
        m = await bot.send_message(channel,
                                   bl_as_modul.HSK,
                                   parse_mode='html',
                                   link_preview=False)
        await bot.delete_messages(channel, m.id - 1)
        try:
            conn = await create_connection()
            u = await user_info.find_user(conn, channel, '',
                                          1)  # а если всего один
            await user_info.update_user(conn, u[0], u[1], u[2], 100, '', '',
                                        u[6], u[7], u[8], u[9], u[10], u[11],
                                        u[12])
            await user_info.close_connection(conn)
        except Exception:
            await bot.send_message(channel,
                                   'У вас нет рабочего канала, выберите его',
                                   parse_mode='html',
                                   link_preview=False)
    elif text_e == '🏹   Send':  # Отправка в канал
        #  НЕ ОТПРАВЛЯЕТ ПОСЛЕ КОМБ ПОЧЕМУ ТО
        #  видео с каментом    pkanal = 11 mm=2
        #  Водяной знак        pkanal = 5     u[3]
        #  Работа со ссылками  pkanal = 6
        #  Картинка с каментом pkanal = 11 mm=1
        #  instant view        pkanal = 22
        #  просто сообщение    pkanal = 9
        # bot.delete_message(message.chat.id, message.message_id)
        #  await bot.delete_messages(channel, id_message)

        conn = await user_info.create_connection()
        u = await user_info.find_user(conn, channel, '', 1)
        await user_info.close_connection(conn)
        if u[3] == 5 or u[3] == 6 or u[3] == 100:
            m = await bot.send_message(
                channel,
                'Пустые сообщения не отправляются в канал',
                parse_mode='html',
                link_preview=False)
            await bot.delete_messages(channel, m.id - 1)

        else:  # Выбираем стиль отправки

            snd_but = types.ReplyInlineMarkup(rows=[
                KeyboardButtonRow(buttons=[
                    KeyboardButtonCallback(text="📦 Schedule", data=b"snd_s")
                ]),
                KeyboardButtonRow(buttons=[
                    KeyboardButtonCallback(text="📦 Schedule & 💣 Delete",
                                           data=b"snd_sd"),
                ]),
                KeyboardButtonRow(buttons=[
                    KeyboardButtonCallback(text="⚡️ Immediately",
                                           data=b"snd_i"),
                ]),
                KeyboardButtonRow(buttons=[
                    KeyboardButtonCallback(text="⚡️ Immediately & 💣 Delete",
                                           data=b"snd_id"),
                ]),
                KeyboardButtonRow(buttons=[
                    KeyboardButtonCallback(text="🔁 Update S&D",
                                           data=b"snd_S&D"),
                ]),
            ])

            m = await bot.send_message(
                channel,
                'Выберите необходимое действие \n <b>Время отправки по Москве</b>',
                parse_mode='html',
                buttons=snd_but)
            await bot.delete_messages(channel, m.id - 1)

    elif text_e.find('://') > 0:  # Работа со ссылками pkanal = 6  6666666

        if text_e.find(' ') == -1:
            if ('youtube.com' in text_e or 'youtu.be' in text_e or 'ok.ru'
                    in text_e) and (u[3] // 100 != 20):  # Загружаем с Ютуб
                link_of_the_video = text_e
                # await message.delete()
                f = tempfile.NamedTemporaryFile(delete=False)
                video_path_out = f'{f.name}.mkv'  # .mkv
                video_path = f.name
                video_path_out_mp4 = f'{f.name}.mp4'
                ydl_opts = {
                    'outtmpl': video_path,
                    'merge_output_format': 'mkv',
                    'noplaylist': 'true',
                    'ignoreerrors': 'true',
                    'quiet': True,
                    'max_filesize': 120000000,
                    'format':
                    'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
                    'filename': video_path_out
                }

                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    video_path = ydl.download([link_of_the_video])

                if not os.path.exists(
                        video_path_out
                ) == 0:  # файл есть   if os.path.exists('/tmp/f.mp4'):
                    video = VideoFileClip(video_path_out)  # mkv --> mp4
                    result = CompositeVideoClip([video])
                    result.write_videofile(video_path_out_mp4,
                                           fps=24,
                                           codec='mpeg4')

                    with open(video_path_out_mp4, 'rb') as fi:

                        info_video = await bot.send_file(channel, fi)

                    # info_video = bot.send_video(message.chat.id, video_path_out_mp4)

                    os.remove(f.name)
                    os.remove(video_path_out)
                    os.remove(video_path_out_mp4)

                    conn = await user_info.create_connection()
                    u = await user_info.find_user(conn, channel, '', 1)
                    await user_info.update_user(conn, u[0], u[1], u[2], 6,
                                                u[4], u[5], u[6], 2, u[8],
                                                info_video.id, video_path,
                                                u[11], u[12])
                    await user_info.close_connection(conn)

                    # file_info_video = bot.get_file(info_video.video.file_id)

                else:  # файла нет
                    # bot.delete_message(message.chat.id, gif.message_id)
                    await bot.send_message(
                        channel,
                        'Слишком большой файл для загрузки,' +
                        "<a href='https://t.me/joinchat/EHLktEzzYJXpERD7UgaHFQ'> пишите мне в чат </a>"
                        + 'какие варианты интересны',
                        parse_mode='html')
                    # предложить  сделать ссылку  на ролик

                    conn = await user_info.create_connection()
                    u = await user_info.find_user(conn, channel, '', 1)
                    await user_info.update_user(conn, u[0], u[1], u[2], 100,
                                                '', '', u[6], 0, u[8], u[9],
                                                '', u[11], u[12])
                    await user_info.close_connection(conn)

            else:  # Читать далее

                conn = await user_info.create_connection()
                u = await user_info.find_user(conn, channel, '', 1)

                if u[3] == 10:
                    # telo = vkanal
                    await user_info.update_user(conn, u[0], u[1], u[2], u[3],
                                                u[4], u[4], u[6], u[7], u[8],
                                                u[9], u[10], u[11], u[12])
                    await user_info.close_connection(conn)
                else:
                    await user_info.update_user(conn, u[0], u[1], u[2], u[3],
                                                text_e, u[5], u[6], u[7], u[8],
                                                u[9], u[10], u[11], u[12])
                    await user_info.close_connection(conn)

                await bot.send_message(
                    channel,
                    'Нужен режим instant view?',
                    buttons=[
                        KeyboardButtonCallback(text="Да", data=b"iv_yes"),
                        KeyboardButtonCallback(text="Нет", data=b"iv_no"),
                    ])
                conn = await user_info.create_connection()
                u = await user_info.find_user(conn, channel, '', 1)
                await user_info.update_user(conn, u[0], u[1], u[2], u[3],
                                            text_e, u[5], u[6], u[7], u[8],
                                            u[9], u[10], u[11], u[12])
                await user_info.close_connection(conn)

        else:  # В сообщении присутствует ссылка, но это сообщение в канал

            telo = text_e  #  + '\n'  # Просто текст

            #  Обрабатываем выделение жирным,
            #  надо переписать это на str.find(), вместо index()

            if round(telo.count('ьь') /
                     2) - telo.count('ьь') / 2 == 0.5 or telo.count('ьь') == 1:
                bot.send_message(
                    channel,
                    'Вы неправильно оформили выделение жирным шрифтом',
                    parse_mode='html',
                    disable_web_page_preview=True)
            else:
                while (True):
                    try:
                        index = telo.index('ьь')
                        telo = telo[:index] + '<b>' + telo[index + 2:]
                        index = telo.index('ьь', index)
                        telo = telo[:index] + '</b>' + telo[index + 2:]
                        conn = await user_info.create_connection(
                        )  # убрать в каждый раздел!!!!!
                        u = await user_info.find_user(conn, channel, '', 1)
                        await user_info.update_user(conn, u[0], u[1], u[2],
                                                    u[3], u[4], telo, u[6],
                                                    u[7], u[8], u[9], u[10],
                                                    u[11], u[12])
                        await user_info.close_connection(conn)

                    except ValueError:
                        break

            if round(telo.count('===') /
                     2) - telo.count('===') / 2 == 0.5 or telo.count(
                         '===') == 1:
                bot.send_message(channel,
                                 'Вы неправильно оформили кнопку',
                                 parse_mode='html',
                                 disable_web_page_preview=True)
            else:
                if telo.find('===') > 0:
                    while (True):
                        try:
                            x1 = telo[:(telo.index('==='))]
                            x2 = telo[(telo.rindex('===') + 3):]  # ссылка
                            x3 = telo[(telo.index('===') +
                                       3):(telo.rindex('==='))]  # кнопка
                            msg = await bot.send_message(
                                channel,
                                x1,
                                parse_mode='html',
                                link_preview=False,
                                buttons=[[
                                    Button.inline(''),
                                    Button.inline('')
                                ], [Button.url(x3, x2.strip())]])

                            conn = await user_info.create_connection()
                            u = await user_info.find_user(conn, channel, '', 1)
                            await user_info.update_user(
                                conn, u[0], u[1], u[2], u[3], u[4], x1, u[6],
                                u[7], u[8], u[9], u[10], x3 + ' ' + x2, u[12])
                            await user_info.close_connection(conn)

                            break
                        except ValueError:
                            break

            if u[3] // 100 == 20:  # кнопка из меню

                x2, x3, x4, x5, x6, x7 = await user_info.processing_button_data(
                    telo)

                if not u[5]:  # для отладки
                    otl = '<>'
                else:
                    otl = u[5]

                msg = await bot.send_message(channel,
                                             otl,
                                             parse_mode='html',
                                             link_preview=False,
                                             buttons=[[
                                                 Button.url(x5, x4.strip()),
                                                 Button.url(x7, x6.strip())
                                             ], [Button.url(x3, x2.strip())]])
                conn = await user_info.create_connection()
                u = await user_info.find_user(conn, channel, '', 1)
                await user_info.update_user(conn, u[0], u[1], u[2], u[3], u[4],
                                            u[5], u[6], u[7], u[8], u[9],
                                            u[10], telo, u[12])
                await user_info.close_connection(conn)

    else:  # Просто текст
        await user_info.just_text(event)
示例#13
0
async def tools_w(event):
    sender = await event.get_sender()
    channel = sender.id
    await bot.delete_messages(channel, event.original_update.msg_id)
    if event.data == b'tools_ch':
        await bot.send_message(channel,
                               'Выберите необходимое действие',
                               buttons=bl_as_modul.hlp_but)
    elif event.data == b'tools_but':
        pkanal = 2000  # признак что кнопка
        conn = await create_connection()
        u = await user_info.find_user(conn, channel, '',
                                      1)  # а если всего один
        pkanal = pkanal + u[3]
        await user_info.update_user(conn, u[0], u[1], u[2], pkanal, '', u[5],
                                    u[6], u[7], u[8], u[9], u[10], u[11],
                                    u[12])
        await user_info.close_connection(conn)

        await bot.send_message(
            channel,
            'отправте до 3_х кнопок в виде' + '\n' + 'ТЕКСТ КНОПКИ Url' +
            '\n' + 'ТЕКСТ КНОПКИ Url' + '\n' + 'ТЕКСТ КНОПКИ Url')

    elif event.data == b'tools_cmb':
        await user_info.combo_f(event)

    elif event.data == b'tools_inf':
        spisok = await sched_send_delete.all_send_ch(event)
        sp = await sched_send_delete.all_sd_keyb(spisok)
        keyb_spisok = types.ReplyInlineMarkup(rows=[
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[0], data=b"schinf1"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[1], data=b"schinf2"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[2], data=b"schinf3"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[3], data=b"schinf4"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[4], data=b"schinf5"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[5], data=b"schinf6"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[6], data=b"schinf7"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[7], data=b"schinf8"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[8], data=b"schinf9"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=sp[9], data=b"schinf10"),
            ]),
        ])

        if spisok:
            await bot.send_message(channel,
                                   'Ваши сообщения',
                                   buttons=keyb_spisok)
        else:
            await bot.send_message(channel, 'У Вас нет отложенных сообщений')
示例#14
0
async def photo_ex(event):
    callbtn = event.data
    sender = await event.get_sender()
    # name = utils.get_display_name(sender)
    channel = sender.id
    id_message = event.message_id

    if callbtn == b"wrkchsel_c":  # выбрать канал

        # await call.message.delete()
        await bot.delete_messages(channel, id_message)
        conn = await user_info.create_connection()
        etud = await user_info.find_user(conn, channel, '', 2)
        chaname = await user_info.Name_ch_(etud)
        await user_info.close_connection(conn)
        hlp_v = types.ReplyInlineMarkup(rows=[
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[0], data=b"wrkchc1"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[1], data=b"wrkchc2"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[2], data=b"wrkchc3"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[3], data=b"wrkchc4"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[4], data=b"wrkchc5"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[5], data=b"wrkchc6"),
            ]),
        ])

        await bot.send_message(channel, 'канал?', buttons=hlp_v)  # 444444

    if callbtn == b"wrkchc1":  # выбираем 1 канал
        await user_info.sel_chan(channel, id_message, 0, 1)
    if callbtn == b"wrkchc2":  # выбираем 2 канал
        await user_info.sel_chan(channel, id_message, 1, 1)
    if callbtn == b"wrkchc3":  # выбираем 3 канал
        await user_info.sel_chan(channel, id_message, 2, 1)
    if callbtn == b"wrkchc4":  # выбираем 4 канал
        await user_info.sel_chan(channel, id_message, 3, 1)
    if callbtn == b"wrkchc5":  # выбираем 5 канал
        await user_info.sel_chan(channel, id_message, 4, 1)
    if callbtn == b"wrkchc6":  # выбираем 6 канал
        await user_info.sel_chan(channel, id_message, 5, 1)

    # if callbtn == b"add_c": #  добавить канал
    #     await bot.delete_messages(channel, id_message)
    #     conn = await user_info.create_connection()
    #     etud = await user_info.find_user(conn, channel, '', 2)
    #     chaname = await user_info.Name_ch_(etud)
    #     await user_info.close_connection(conn)

    if callbtn == b"wrkchdel_c":  # удалить канал
        await bot.delete_messages(channel, id_message)
        conn = await user_info.create_connection()
        etud = await user_info.find_user(conn, channel, '', 2)
        chaname = await user_info.Name_ch_(etud)
        await user_info.close_connection(conn)
        hlp_del = types.ReplyInlineMarkup(rows=[
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[0], data=b"wrkchd1"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[1], data=b"wrkchd2"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[2], data=b"wrkchd3"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[3], data=b"wrkchd4"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[4], data=b"wrkchd5"),
            ]),
            KeyboardButtonRow(buttons=[
                KeyboardButtonCallback(text=chaname[5], data=b"wrkchd6"),
            ]),
        ])
        await bot.send_message(channel, 'канал?', buttons=hlp_del)  # 444444

    if callbtn == b"wrkchd1":  # выбираем 1 канал
        await user_info.sel_chan(channel, id_message, 0, 2)
    if callbtn == b"wrkchd2":  # выбираем 2 канал
        await user_info.sel_chan(channel, id_message, 1, 2)
    if callbtn == b"wrkchd3":  # выбираем 3 канал
        await user_info.sel_chan(channel, id_message, 2, 2)
    if callbtn == b"wrkchd4":  # выбираем 4 канал
        await user_info.sel_chan(channel, id_message, 3, 2)
    if callbtn == b"wrkchd5":  # выбираем 5 канал
        await user_info.sel_chan(channel, id_message, 4, 2)
    if callbtn == b"wrkchd6":  # выбираем 6 канал
        await user_info.sel_chan(channel, id_message, 5, 2)
    if callbtn == b"wrkchotval":  # выйти из меню работы с каналами
        await bot.delete_messages(channel, id_message)
示例#15
0
    '<b>Отправить боту видеофайл</b> возвращается видео с бегущей строкой вашего канала.' \
    '\n' \
    '<b>Отправка боту ссылки</b>' \
    '\n' \
    '<b>- на ютуб</b> возвращает видеофайл' \
    '\n' \
    '<b>- на ваш канал</b> в последующем, если вам надо, добавляет в тег гиперссылку на канал, пишет на картинке, отправленной боту вашу ссылку, добавляет в видео бегущую строку с вашей ссылкой.' \
    '\n' \
    '<b>любая другая</b> ссылка добавляется к тексту гиперссылкой со словами “Читать далее…"' \
    '\n' \
    'Все вопросы и предложения по работе бота только в чате моего канала.' \
    '<a href="https://t.me/joinchat/UxMjcxD8b7UY00vf"> Подписаться на канал</a>'

markup1 = types.ReplyInlineMarkup(rows=[
    KeyboardButtonRow(buttons=[
        KeyboardButtonCallback(text="Tk", data="tk"),
        KeyboardButtonCallback(text="Gs", data=b"/gs"),
        KeyboardButtonCallback(text="Bal", data=b"/bal"),
    ]),
    KeyboardButtonRow(buttons=[
        KeyboardButtonCallback(text="Task", data=b"/task"),
        KeyboardButtonCallback(text="Games", data=b"/games"),
        KeyboardButtonCallback(text="Balance", data=b"/balance"),
    ])
])

Main_menu_btn_old = [[
    Button.text('News'),
    Button.text('Think'),
    Button.text('ADS'),
    Button.text('Hands'),
示例#16
0
async def chelp(event):
    await event.edit(
        "Help",
        buttons=[[KeyboardButtonCallback(text="Test Button", data="test")]])
示例#17
0
async def mixFileup(path,
                    message,
                    force_edit,
                    database=None,
                    thumb_path=None,
                    user_msg=None):
    queue = message.client.queue
    if database is not None:
        if database.get_cancel_status(message.chat_id, message.id):
            # add os remove here
            return None
    if not os.path.exists(path):
        return None
    #todo improve this uploading ✔️
    file_name = os.path.basename(path)
    file_size = os.path.getsize(path)
    metadata = extractMetadata(createParser(path))
    ometa = metadata
    if metadata is not None:
        # handle none for unknown
        metadata = metadata.exportDictionary()
        try:
            mime = metadata.get("Common").get("MIME type")
        except:
            mime = metadata.get("Metadata").get("MIME type")

        ftype = mime.split("/")[0]
        ftype = ftype.lower().strip()
    else:
        ftype = "unknown"
    if not force_edit:
        if user_msg is None:
            sup_mes = await message.get_reply_message()
        else:
            sup_mes = user_msg

        data = "upcancel {} {} {}".format(message.chat_id, message.id,
                                          sup_mes.sender_id)
        buts = [KeyboardButtonCallback("Cancel upload.", data.encode("UTF-8"))]
        msg = await message.reply("Uploading {}".format(file_name),
                                  buttons=buts)
    else:
        msg = message
        #print(metadata)
    uploader_id = None
    if queue is not None:
        torlog.info(f"Waiting for the worker here for {file_name}")
        msg = await msg.edit(
            f"{msg.text} - Waiting for a uploaders to get free")
        uploader_id = await queue.get()
        torlog.info(
            f"Waiting over for the worker here for {file_name} aquired worker {uploader_id}"
        )
    out_msg = None
    start_time = time.time()
    tout = get_val("EDIT_SLEEP_SECS")
    opath = path

    try:
        email = env_email
        api_key = env_api_key
        upload_url = "https://ul.mixdrop.co/api"
        async with aiohttp.ClientSession() as session:
            data = {'file': open(path, "rb"), 'email': email, 'key': api_key}
            response = await session.post(upload_url, data=data)
            link = await response.json()
            #            dl_b = f"https://mixdrop.co/f/{link['result']['fileref']}"
            torlog.info("success")
    except Exception as e:
        if str(e).find("cancel") != -1:
            torlog.info("cancled an upload lol")
            await msg.delete()
        else:
            torlog.info(traceback.format_exc())
    finally:
        if queue is not None:
            await queue.put(uploader_id)
            torlog.info(f"Freed uploader with id {uploader_id}")
    if out_msg is None:
        return None
    if out_msg.id != msg.id:
        await msg.delete()

    return out_msg
示例#18
0
文件: sl_tm.py 项目: SGKbot/AltBot
import bl_as_modul
import aiosqlite
from telethon.tl import types
from telethon.tl.types import (
    KeyboardButtonRow,
    KeyboardButtonCallback,
)

from datetime import date, datetime, timedelta

mdate_db = cfg.user_db  # './mdate.db'
bot = bl_as_modul.client

tempAM_but = types.ReplyInlineMarkup(rows=[
    KeyboardButtonRow(buttons=[
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="12", data=b"timeam12"),
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="  ", data=b"s"),
    ]),
    KeyboardButtonRow(buttons=[
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="11", data=b"timeam11"),
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text="  ", data=b"s"),
        KeyboardButtonCallback(text=" 1", data=b"timeam1"),
        KeyboardButtonCallback(text="  ", data=b"s"),
async def register_torrent(entity,message,user_msg=None,magnet=False,file=False):
    client = await get_client()

    #refresh message
    message = await message.client.get_messages(message.chat_id,ids=message.id)
    if user_msg is None:
        omess = await message.get_reply_message()
    else:
        omess = user_msg

    if magnet:
        torlog.info(f"magnet :- {magnet}")
        torrent = await add_torrent_magnet(entity,message)
        if isinstance(torrent,bool):
            return False
        torlog.info(torrent)
        if torrent.progress == 1 and torrent.completion_on > 1:
            await message.edit("The provided torrent was already completly downloaded.")
            return True
        else:
            
            pincode = randint(1000,9999)
            db = tor_db
            db.add_torrent(torrent.hash,pincode)
            
            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)
            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit("Download will be automatically started after 180s of no action.",buttons=[
                [
                    KeyboardButtonUrl("Choose File from link",urll),
                    KeyboardButtonCallback("Get Pincode",data=pincodetxt.encode("UTF-8"))
                ],
                [
                    KeyboardButtonCallback("Done Selecting Files.",data=f"doneselection {omess.sender_id} {omess.id}".encode("UTF-8"))
                ]
            ])

            await get_confirm(omess)

            message = await message.edit(buttons=[KeyboardButtonCallback("Cancel Leech",data=data.encode("UTF-8"))])

            db.disable_torrent(torrent.hash)
            

            task = QBTask(torrent, message, client)
            await task.set_original_mess(omess)
            return await update_progress(client,message,torrent, task)
    if file:
        torrent = await add_torrent_file(entity,message)
        if isinstance(torrent,bool):
            return False
        torlog.info(torrent)
        
        if torrent.progress == 1:
            await message.edit("The provided torrent was already completly downloaded.")
            return True
        else:
            pincode = randint(1000,9999)
            db = tor_db
            db.add_torrent(torrent.hash,pincode)
            
            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)

            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit(buttons=[
                [
                    KeyboardButtonUrl("Choose File from link",urll),
                    KeyboardButtonCallback("Get Pincode",data=pincodetxt.encode("UTF-8"))
                ],
                [
                    KeyboardButtonCallback("Done Selecting Files.",data=f"doneselection {omess.sender_id} {omess.id}".encode("UTF-8"))
                ]
            ])

            await get_confirm(omess)

            message = await message.edit(buttons=[KeyboardButtonCallback("Cancel Leech",data=data.encode("UTF-8"))])

            db.disable_torrent(torrent.hash)
            
            task = QBTask(torrent, message, client)
            await task.set_original_mess(omess)
            return await update_progress(client,message,torrent, task)
async def check_progress_for_dl(aria2, gid, event, previous_message, rdepth = 0, user_msg=None):
    try:
        file = aria2.get_download(gid)
        complete = file.is_complete
        if not complete:
            if not file.error_message:
                msg = ""
                downloading_dir_name = "N/A"
                try:
                    downloading_dir_name = str(file.name)
                except:
                    pass
                mem_chk = [84 , 73 , 77 , 69 , 
                    95 , 
                    83 , 84 , 65 , 
                    84]
                memstr=""
                for i in mem_chk:
                    memstr += chr(i)
                if os.environ.get(memstr, False):
                    return
                msg = f"\nDownloading File: <code>{downloading_dir_name}</code>"
                msg += f"\n<b>Down:</b> {file.download_speed_string()} 🔽 <b>Up</b>: {file.upload_speed_string()} 🔼"
                msg += f"\n<b>Progress:</b> {file.progress_string()}"
                msg += f"\n<b>Size:</b> {file.total_length_string()}"
                msg += f"\n<b>Info:</b>| P: {file.connections} |"
                msg += f"\n<b>Using engine:</b> <code>aria2 for directlink</code>"
                if file.seeder is False:
                    """https://t.me/c/1220993104/670177"""
                    msg += f"| S: {file.num_seeders} |"
                # msg += f"\nStatus: {file.status}"
                msg += f"\nETA: {file.eta_string()}"
                #msg += f"\n<code>/cancel {gid}</code>"
                
                # format :- torcancel <provider> <identifier>
                if user_msg is None:
                    mes = await event.get_reply_message()
                else:
                    mes = user_msg
                data = f"torcancel aria2 {gid} {mes.sender_id}"
                
                # LOGGER.info(msg)
                if msg != previous_message:
                    if rdepth < 3:
                        await event.edit(msg,parse_mode="html", buttons=[KeyboardButtonCallback("Cancel Direct Leech",data=data.encode("UTF-8"))])
                    else:
                        await event.edit(msg,parse_mode="html")
                    previous_message = msg
            else:
                msg = file.error_message
                await event.edit(f"`{msg}`",parse_mode="html", buttons=None)
                torlog.error(f"The aria download faild due to this reason:- {msg}")
                return False
            await asyncio.sleep(get_val("EDIT_SLEEP_SECS"))
            
            # TODO idk not intrested in using recursion here
            return await check_progress_for_dl(
                aria2, gid, event, previous_message,user_msg=mes
            )
        else:
            await event.edit(f"Download completed: <code>{file.name}</code> to path <code>{file.name}</code>",parse_mode="html", buttons=None)
            return True
    except aria2p.client.ClientException as e:
        if " not found" in str(e) or "'file'" in str(e):
            fname = "N/A"
            try:
                fname = file.name
            except:pass

            await event.edit(
                "Download Canceled :\n<code>{}</code>".format(fname),
                parse_mode="html"
            )
            torlog.error("Errored due to ta client error.")
            return False
        pass
    except MessageNotModifiedError:
        pass
    except RecursionError:
        file.remove(force=True)
        await event.edit(
            "Download Auto Canceled :\n\n"
            "Your Torrent/Link {} is Dead.".format(
                file.name
            ),
            parse_mode="html"
        )
        return False
    except Exception as e:
        torlog.info(str(e))
        if " not found" in str(e) or "'file'" in str(e):
            await event.edit(
                "Download Canceled :\n<code>{}</code>".format(file.name),
                parse_mode="html"
            )
            return False
        else:
            torlog.info(str(e))
            await event.edit("<u>error</u> :\n<code>{}</code> \n\n#error".format(str(e)),parse_mode="html")
            return False
示例#21
0
async def confirm_buttons(e,val):
    # add the confirm buttons at the bottom of the message
    await e.edit(f"Confirm the input :- <u>{val}</u>",buttons=[KeyboardButtonCallback("Yes","confirmsetting true"),KeyboardButtonCallback("No","confirmsetting false")],parse_mode="html")
示例#22
0
async def rclone_upload(path, message, user_msg, dest_drive, dest_base,
                        edit_time, conf_path, task):
    # this function will need a driver for him :o
    if not os.path.exists(path):
        torlog.info(f"Returning none cuz the path {path} not found")
        await task.set_inactive(f"Returning none cuz the path {path} not found"
                                )
        return None
    omsg = user_msg
    await task.set_original_message(omsg)
    upload_db.register_upload(omsg.chat_id, omsg.id)
    data = "upcancel {} {} {}".format(omsg.chat_id, omsg.id, omsg.sender_id)
    buts = [KeyboardButtonCallback("Cancel upload.", data.encode("UTF-8"))]

    msg = await message.reply(
        "<b>Uploading to configured drive.... will be updated soon.",
        parse_mode="html",
        buttons=buts)
    await task.set_message(msg)

    if os.path.isdir(path):
        # handle dirs
        new_dest_base = os.path.join(dest_base, os.path.basename(path))
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg, task)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            task.cancel = True
            await task.set_inactive("Canceled Rclone Upload")
            return task

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path)
        torlog.info(f"Upload folder id :- {gid}")

        folder_link = f"https://drive.google.com/folderview?id={gid[0]}"

        buttons = []
        buttons.append([KeyboardButtonUrl("Drive URL", folder_link)])
        gd_index = get_val("GD_INDEX_URL")
        if gd_index:
            index_link = "{}/{}/".format(gd_index.strip("/"), gid[1])
            index_link = requote_uri(index_link)
            torlog.info("index link " + str(index_link))
            buttons.append([KeyboardButtonUrl("Index URL", index_link)])

        txtmsg = "<a href='tg://user?id={}'>Done</a>\n#uploads\nUPLOADED FOLDER :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(txtmsg, buttons=buttons, parse_mode="html")
        await msg.delete()

    else:
        new_dest_base = dest_base
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg, task)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            task.cancel = True
            await task.set_inactive("Canceled Rclone Upload")
            return task

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path, False)
        torlog.info(f"Upload folder id :- {gid}")

        buttons = []

        file_link = f"https://drive.google.com/file/d/{gid[0]}/view"
        buttons.append([KeyboardButtonUrl("Drive URL", file_link)])
        gd_index = get_val("GD_INDEX_URL")
        if gd_index:
            index_link = "{}/{}".format(gd_index.strip("/"), gid[1])
            index_link = requote_uri(index_link)
            torlog.info("index link " + str(index_link))
            buttons.append([KeyboardButtonUrl("Index URL", index_link)])

        txtmsg = "<a href='tg://user?id={}'>Done</a>\n#uploads\nUPLOADED FILE :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(txtmsg, buttons=buttons, parse_mode="html")
        await msg.delete()

    upload_db.deregister_upload(message.chat_id, message.id)
    await task.set_inactive()
    return task
示例#23
0
async def handle_settings(e,
                          edit=False,
                          msg="",
                          submenu=None,
                          session_id=None):
    # this function creates the menu
    # and now submenus too
    await handle_time_cmd()
    if session_id is None:
        session_id = time.time()
        db = tordb
        db.set_variable("SETTING_AUTH_CODE", str(session_id))
        SessionVars.update_var("SETTING_AUTH_CODE", str(session_id))

    menu = [
        #[KeyboardButtonCallback(yes+" Allow TG Files Leech123456789-","settings data".encode("UTF-8"))], # for ref
    ]

    if submenu is None:
        await get_bool_variable("LOCKED_USERS", "Lock the Group", menu,
                                "usrlock", session_id)
        await get_bool_variable("FORCE_DOCUMENTS", "FORCE_DOCUMENTS", menu,
                                "fdocs", session_id)
        await get_bool_variable(
            "METAINFO_BOT",
            "[MetainfoRoBot]Get metadata of files in this group.", menu,
            "metainfo", session_id)
        await get_string_variable("COMPLETED_STR", menu, "compstr", session_id)
        await get_string_variable("REMAINING_STR", menu, "remstr", session_id)
        await get_int_variable("TG_UP_LIMIT", menu, "tguplimit", session_id)
        await get_int_variable("MAX_TORRENT_SIZE", menu, "maxtorsize",
                               session_id)
        await get_int_variable("MAX_YTPLAYLIST_SIZE", menu, "maxytplsize",
                               session_id)
        await get_int_variable("EDIT_SLEEP_SECS", menu, "editsleepsec",
                               session_id)
        #await get_string_variable("RCLONE_CONFIG",menu,"rcloneconfig",session_id)
        await get_sub_menu("☁️ Open Rclone Menu ☁️", "rclonemenu", session_id,
                           menu)
        await get_sub_menu("🕹️ Control Actions 🕹️", "ctrlacts", session_id,
                           menu)
        menu.append([
            KeyboardButtonCallback(
                "Close Menu",
                f"settings selfdest {session_id}".encode("UTF-8"))
        ])

        if edit:
            rmess = await e.edit(
                header +
                "\nIts recommended to lock the group before setting vars.\n" +
                msg,
                parse_mode="html",
                buttons=menu,
                link_preview=False)
        else:
            rmess = await e.reply(
                header +
                "\nIts recommended to lock the group before setting vars.\n",
                parse_mode="html",
                buttons=menu,
                link_preview=False)
    elif submenu == "rclonemenu":
        rcval = await get_string_variable("RCLONE_CONFIG", menu,
                                          "rcloneconfig", session_id)
        if rcval != "None":
            # create a all drives menu
            if rcval == "Custom file is loaded.":
                db = tordb
                _, fdata = db.get_variable("RCLONE_CONFIG")

                path = os.path.join(os.getcwd(), "rclone.conf")

                # find alternative to this
                with open(path, "wb") as fi:
                    fi.write(fdata)

                conf = configparser.ConfigParser()
                conf.read(path)
                #menu.append([KeyboardButton("Choose a default drive from below")])
                def_drive = get_val("DEF_RCLONE_DRIVE")

                for j in conf.sections():
                    prev = ""
                    if j == def_drive:
                        prev = yes

                    if "team_drive" in list(conf[j]):
                        menu.append([
                            KeyboardButtonCallback(
                                f"{prev}{j} - TD",
                                f"settings change_drive {j} {session_id}")
                        ])
                    else:
                        menu.append([
                            KeyboardButtonCallback(
                                f"{prev}{j} - ND",
                                f"settings change_drive {j} {session_id}")
                        ])

        await get_sub_menu("Go Back ⬅️", "mainmenu", session_id, menu)
        menu.append([
            KeyboardButtonCallback(
                "Close Menu",
                f"settings selfdest {session_id}".encode("UTF-8"))
        ])
        if edit:
            rmess = await e.edit(
                header +
                "\nIts recommended to lock the group before setting vars.\n" +
                msg,
                parse_mode="html",
                buttons=menu,
                link_preview=False)

    elif submenu == "ctrlacts":
        await get_bool_variable("RCLONE_ENABLED", "Enable Rclone.", menu,
                                "rcloneenable", session_id)
        await get_bool_variable("LEECH_ENABLED", "Enable Leech.", menu,
                                "leechenable", session_id)
        await get_bool_variable("FAST_UPLOAD",
                                "Enable Fast Upload.(Turn off if errored)",
                                menu, "fastupload", session_id)
        await get_bool_variable(
            "EXPRESS_UPLOAD",
            "Enable Express Upload.(read README on github for more info)(Turn off if errored)",
            menu, "expressupload", session_id)
        await get_bool_variable(
            "FORCE_DOCS_USER", "Not Implemented.User will choose force docs.",
            menu, "forcedocsuser", session_id)

        await get_sub_menu("Go Back ⬅️", "mainmenu", session_id, menu)
        menu.append([
            KeyboardButtonCallback(
                "Close Menu",
                f"settings selfdest {session_id}".encode("UTF-8"))
        ])
        if edit:
            rmess = await e.edit(
                header +
                "\nIts recommended to lock the group before setting vars.\n" +
                msg,
                parse_mode="html",
                buttons=menu,
                link_preview=False)
示例#24
0
async def upload_a_file(path,message,force_edit,database=None,thumb_path=None,user_msg=None):
    if get_val("EXPRESS_UPLOAD"):
        return await upload_single_file(path, message, force_edit, database, thumb_path, user_msg)
    queue = message.client.queue
    if database is not None:
        if database.get_cancel_status(message.chat_id,message.id):
            # add os remove here
            return None
    if not os.path.exists(path):
        return None
        
    if user_msg is None:
        user_msg = await message.get_reply_message()
    
    #todo improve this uploading ✔️
    file_name = os.path.basename(path)
    caption_str = ""
    caption_str += "<code>"
    caption_str += file_name
    caption_str += "</code>"
    metadata = extractMetadata(createParser(path))
    ometa = metadata
    
    if metadata is not None:
        # handle none for unknown
        metadata = metadata.exportDictionary()
        try:
            mime = metadata.get("Common").get("MIME type")
        except:
            mime = metadata.get("Metadata").get("MIME type")

        ftype = mime.split("/")[0]
        ftype = ftype.lower().strip()
    else:
        ftype = "unknown"
    #print(metadata)
    

    if not force_edit:        
        data = "upcancel {} {} {}".format(message.chat_id,message.id,user_msg.sender_id)
        buts = [KeyboardButtonCallback("Cancel upload.",data.encode("UTF-8"))]
        msg = await message.reply("📤 **Uploading:** `{}`".format(file_name),buttons=buts)

    else:
        msg = message

    uploader_id = None
    if queue is not None:
        torlog.info(f"Waiting for the worker here for {file_name}")
        msg = await msg.edit(f"{msg.text}\n⌛ Waiting for a uploaders to get free... ")
        uploader_id = await queue.get()
        torlog.info(f"Waiting over for the worker here for {file_name} aquired worker {uploader_id}")

    out_msg = None
    start_time = time.time()
    tout = get_val("EDIT_SLEEP_SECS")
    opath = path
    
    if user_msg is not None:
        dis_thumb = user_db.get_var("DISABLE_THUMBNAIL", user_msg.sender_id)
        if dis_thumb is False or dis_thumb is None:
            thumb_path = user_db.get_thumbnail(user_msg.sender_id)
            if not thumb_path:
                thumb_path = None
    
    try:
        if get_val("FAST_UPLOAD"):
            torlog.info("Fast upload is enabled")
            with open(path,"rb") as filee:
                path = await upload_file(message.client,filee,file_name,
                lambda c,t: progress(c,t,msg,file_name,start_time,tout,message,database)
                )

        if user_msg is not None:
            force_docs = user_db.get_var("FORCE_DOCUMENTS",user_msg.sender_id)  
        else:
            force_docs = None
        
        if force_docs is None:
            force_docs = get_val("FORCE_DOCUMENTS")
    
        if message.media and force_edit:
            out_msg = await msg.edit(
                file=path,
                text=caption_str
            )
        else:
            
            if ftype == "video" and not force_docs:
                try:
                    if thumb_path is not None:
                        thumb = thumb_path
                    else:
                        thumb = await thumb_manage.get_thumbnail(opath)
                except:
                    thumb = None
                    torlog.exception("Error in thumb")
                try:
                    attrs, _ = get_attributes(opath,supports_streaming=True)
                    out_msg = await msg.client.send_file(
                        msg.to_id,
                        file=path,
                        parse_mode="html",
                        thumb=thumb,
                        caption=caption_str,
                        reply_to=message.id,
                        supports_streaming=True,
                        progress_callback=lambda c,t: progress(c,t,msg,file_name,start_time,tout,message,database),
                        attributes=attrs
                    )
                except VideoContentTypeInvalidError:
                    attrs, _ = get_attributes(opath,force_document=True)
                    torlog.warning("Streamable file send failed fallback to document.")
                    out_msg = await msg.client.send_file(
                        msg.to_id,
                        file=path,
                        parse_mode="html",
                        caption=caption_str,
                        thumb=thumb,
                        reply_to=message.id,
                        force_document=True,
                        progress_callback=lambda c,t: progress(c,t,msg,file_name,start_time,tout,message,database),
                        attributes=attrs
                    )
                except Exception:
                    torlog.error("Error:- {}".format(traceback.format_exc()))
            elif ftype == "audio" and not force_docs:
                # not sure about this if
                attrs, _ = get_attributes(opath)
                out_msg = await msg.client.send_file(
                    msg.to_id,
                    file=path,
                    parse_mode="html",
                    caption=caption_str,
                    reply_to=message.id,
                    progress_callback=lambda c,t: progress(c,t,msg,file_name,start_time,tout,message,database),
                    attributes=attrs
                )
            else:
                if force_docs:
                    attrs, _ = get_attributes(opath,force_document=True)
                    out_msg = await msg.client.send_file(
                        msg.to_id,
                        file=path,
                        parse_mode="html",
                        caption=caption_str,
                        reply_to=message.id,
                        force_document=True,
                        progress_callback=lambda c,t: progress(c,t,msg,file_name,start_time,tout,message,database),
                        attributes=attrs,
                        thumb=thumb_path
                    )
                else:
                    attrs, _ = get_attributes(opath)
                    out_msg = await msg.client.send_file(
                        msg.to_id,
                        file=path,
                        parse_mode="html",
                        caption=caption_str,
                        reply_to=message.id,
                        progress_callback=lambda c,t: progress(c,t,msg,file_name,start_time,tout,message,database),
                        attributes=attrs,
                        thumb=thumb_path
                    )
    except Exception as e:
        if str(e).find("cancel") != -1:
            torlog.info("Canceled an upload lol")
            await msg.edit(f"Failed to upload {e}")
        else:
            torlog.exception("In Tele Upload")
            await msg.edit(f"Failed to upload {e}")
    finally:
        if queue is not None:
            await queue.put(uploader_id)
            torlog.info(f"Freed uploader with id {uploader_id}")
                

    if out_msg is None:
        return None
    if out_msg.id != msg.id:
        await msg.delete()
    
    return out_msg
async def rclone_upload(path, message, user_msg, dest_drive, dest_base,
                        edit_time, conf_path):
    # this function will need a driver for him :o
    if not os.path.exists(path):
        torlog.info(f"Returning none cuz the path {path} not found")
        return None
    omsg = user_msg
    upload_db.register_upload(omsg.chat_id, omsg.id)
    data = "upcancel {} {} {}".format(omsg.chat_id, omsg.id, omsg.sender_id)
    buts = [KeyboardButtonCallback("Cancel upload.", data.encode("UTF-8"))]

    msg = await message.reply(
        "<b>Uploading to configured drive in background mode........",
        parse_mode="html",
        buttons=buts)
    if os.path.isdir(path):
        # handle dirs
        new_dest_base = os.path.join(dest_base, os.path.basename(path))
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            return True

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path)
        torlog.info(f"Upload folder id :- {gid}")

        folder_link = f"https://drive.google.com/folderview?id={gid}"
        txtmsg = "<a href='tg://user?id={}'>Done</a>\n<a href='https://groups.google.com/g/troymods'>Join This Link to Download From Google Drive</a>\n#uploads\nUPLOADED FOLDER :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(
            txtmsg,
            buttons=[[KeyboardButtonUrl("Drive URL", folder_link)]],
            parse_mode="html")
        await msg.delete()

    else:
        new_dest_base = dest_base
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            return True

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path, False)
        torlog.info(f"Upload folder id :- {gid}")

        file_link = f"https://drive.google.com/file/d/{gid}/view"

        txtmsg = "<a href='tg://user?id={}'>Done</a>\n#uploads\nUPLOADED FILE :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(txtmsg,
                         buttons=[[KeyboardButtonUrl("Drive URL", file_link)]],
                         parse_mode="html")
        await msg.delete()

    upload_db.deregister_upload(message.chat_id, message.id)
    return True
示例#26
0
async def create_status_user_menu(event):

    tasks = Status()
    tors = 0
    row = []
    Buttons = []

    msg = "Currently Running: For You- \nClick on the task No. that you want to cancel.\n"
    for i in tasks.Tasks:
        if await i.is_active():

            try:
                if isinstance(i, QBTask):
                    omsg = await i.get_original_message()
                    if not (event.sender_id == omsg.sender_id):
                        continue
                    data = "torcancel {} {}".format(i.hash, omsg.sender_id)
                if isinstance(i, ARTask):
                    if not (event.sender_id == await i.get_sender_id()):
                        continue
                    data = "torcancel aria2 {} {}".format(
                        await i.get_gid(), await i.get_sender_id())
                if isinstance(i, TGUploadTask):
                    if not event.sender_id == await i.get_sender_id():
                        continue
                    message = await i.get_message()
                    data = "upcancel {} {} {}".format(message.chat_id,
                                                      message.id, await
                                                      i.get_sender_id())
                if isinstance(i, RCUploadTask):
                    omsg = await i.get_original_message()
                    if not event.sender_id == omsg.sender_id:
                        continue
                    data = "upcancel {} {} {}".format(omsg.chat_id, omsg.id,
                                                      omsg.sender_id)
            except:
                tors += 1
                torlog.exception("In status msg")
                continue

            msg += get_num(tors) + " " + await i.create_message()
            msg += "\n"

            row.append(
                KeyboardButtonCallback(get_num(tors),
                                       data=data.encode("UTF-8")))
            if len(row) >= 4:
                Buttons.append(row)
                row = []

            tors += 1

    if row:
        Buttons.append(row)

    if not Buttons:
        Buttons = None

    if len(msg) > 3600:
        chunks, chunk_size = len(msg), len(msg) // 4
        msgs = [msg[i:i + chunk_size] for i in range(0, chunks, chunk_size)]

        for j in msgs:
            memsg = await event.reply(j, parse_mode="html", buttons=Buttons)
            to_del.append([memsg, time.time()])
            await asyncio.sleep(1)
    else:
        memsg = await event.reply(msg, parse_mode="html", buttons=Buttons)
        to_del.append([memsg, time.time()])
示例#27
0
async def upload_handel(path,message,from_uid,files_dict,job_id=0,force_edit=False,updb=None,from_in=False,thumb_path=None, user_msg=None, task=None):
    # creting here so connections are kept low
    if updb is None:
        # Central object is not used its Acknowledged 
        updb = TtkUpload()

    #logging.info("Uploading Now:- {}".format(path))

    if os.path.isdir(path):
        logging.info("Uplaoding the directory:- {}".format(path))

        directory_contents = os.listdir(path)
        directory_contents.sort()
        try:
            # maybe way to refresh?!
            message = await message.client.get_messages(message.chat_id,ids=[message.id])
            message = message[0]
        except:pass

        try:
            message = await message.edit("{}\n📦 Found **{}** files for this download.".format(message.text,len(directory_contents)))
        except:
            torlog.warning("Too much folders will stop the editing of this message")
        
        if not from_in:
            updb.register_upload(message.chat_id,message.id)
            if user_msg is None:
                sup_mes = await message.get_reply_message()
            else:
                sup_mes = user_msg
            
            if task is not None:
                await task.set_message(message)
                await task.set_original_message(sup_mes)
            
            data = "upcancel {} {} {}".format(message.chat_id,message.id,sup_mes.sender_id)
            buts = [KeyboardButtonCallback("Cancel upload.",data.encode("UTF-8"))]
            message = await message.edit(buttons=buts)


        for file in directory_contents:
            if updb.get_cancel_status(message.chat_id,message.id):
                continue

            await upload_handel(
                os.path.join(path,file),
                message,
                from_uid,
                files_dict,
                job_id,
                force_edit,
                updb,
                from_in=True,
                thumb_path=thumb_path,
                user_msg=user_msg,
                task=task
            )
        
        if not from_in:
            if updb.get_cancel_status(message.chat_id,message.id):
                task.cancel = True
                await task.set_inactive()
                await message.edit("`{}` - Canceled By user.".format(message.text),buttons=None)
            else:
                await message.edit(buttons=None)
            updb.deregister_upload(message.chat_id,message.id)

    else:
        logging.info("Uploading the file:- {}".format(path))
        if os.path.getsize(path) > get_val("TG_UP_LIMIT"):
            # the splitted file will be considered as a single upload ;)
            
            
            metadata = extractMetadata(createParser(path))
            
            if metadata is not None:
                # handle none for unknown
                metadata = metadata.exportDictionary()
                try:
                    mime = metadata.get("Common").get("MIME type")
                except:
                    mime = metadata.get("Metadata").get("MIME type")

                ftype = mime.split("/")[0]
                ftype = ftype.lower().strip()
            else:
                ftype = "unknown"
            
            if ftype == "video":    
                todel = await message.reply("⚠ **FILE LAGRE THEN THRESHOLD, SPLITTING NOW. **\n⌛ **Processing.....** ```Using Algo FFMPEG SPLIT```") 
                split_dir = await vids_helpers.split_file(path,get_val("TG_UP_LIMIT"))
                await todel.delete()
            else:
                todel = await message.reply("⚠ **FILE LAGRE THEN THRESHOLD, SPLITTING NOW. **\n⌛ **Processing.....** ```Using Algo FFMPEG SPLIT```") 
                split_dir = await zip7_utils.split_in_zip(path,get_val("TG_UP_LIMIT"))
                await todel.delete()
            
            if task is not None:
                await task.add_a_dir(split_dir)
            
            dircon = os.listdir(split_dir)
            dircon.sort()

            if not from_in:
                updb.register_upload(message.chat_id,message.id)
                if user_msg is None:
                    sup_mes = await message.get_reply_message()
                else:
                    sup_mes = user_msg

                if task is not None:
                    await task.set_message(message)
                    await task.set_original_message(sup_mes)

                data = "upcancel {} {} {}".format(message.chat_id,message.id,sup_mes.sender_id)
                buts = [KeyboardButtonCallback("Cancel upload.",data.encode("UTF-8"))]
                await message.edit(buttons=buts)

            for file in dircon:
                if updb.get_cancel_status(message.chat_id,message.id):
                    continue
            
                await upload_handel(
                    os.path.join(split_dir,file),
                    message,
                    from_uid,
                    files_dict,
                    job_id,
                    force_edit,
                    updb=updb,
                    from_in=True,
                    thumb_path=thumb_path,
                    user_msg=user_msg,
                    task=task
                )
            
            try:
                shutil.rmtree(split_dir)
                os.remove(path)
            except:pass
            
            if not from_in:
                if updb.get_cancel_status(message.chat_id,message.id):
                    task.cancel = True
                    await task.set_inactive()
                    await message.edit("`{}` - Canceled By user.".format(message.text),buttons=None)
                else:
                    await message.edit(buttons=None)
                updb.deregister_upload(message.chat_id,message.id)
            # spliting file logic blah blah
        else:
            if not from_in:
                updb.register_upload(message.chat_id,message.id)
                if user_msg is None:
                    sup_mes = await message.get_reply_message()
                else:
                    sup_mes = user_msg
                
                if task is not None:
                    await task.set_message(message)
                    await task.set_original_message(sup_mes)

                if task is not None:
                    await task.set_message(message)
                    await task.set_original_message(sup_mes)

                data = "upcancel {} {} {}".format(message.chat_id,message.id,sup_mes.sender_id)
                buts = [KeyboardButtonCallback("Cancel upload.",data.encode("UTF-8"))]
                await message.edit(buttons=buts)
            #print(updb)
            if black_list_exts(path):
                if task is not None:
                    await task.uploaded_file(os.path.basename(path))
                sentmsg = None
            else:
                sentmsg = await upload_a_file(
                    path,
                    message,
                    force_edit,
                    updb,
                    thumb_path,
                    user_msg=user_msg
                )

            if not from_in:
                if updb.get_cancel_status(message.chat_id,message.id):
                    task.cancel = True
                    await task.set_inactive()
                    await message.edit("`{}` - Canceled By user.".format(message.text),buttons=None)
                else:
                    await message.edit(buttons=None)
                updb.deregister_upload(message.chat_id,message.id)

            if sentmsg is not None:
                if task is not None:
                    await task.uploaded_file(os.path.basename(path))
                files_dict[os.path.basename(path)] = sentmsg.id

    return files_dict
示例#28
0
async def check_progress_for_dl(aria2, gid, event, previous_message, rdepth = 0, user_msg=None):
    try:
        file = aria2.get_download(gid)
        complete = file.is_complete
        if not complete:
            if not file.error_message:
                msg = ""
                downloading_dir_name = "getting data... "
                try:
                    downloading_dir_name = str(file.name)
                except:
                    pass

                msg = f"\n<b>📥 Downloading:</b> <code>{downloading_dir_name}</code>"
                msg += f"\n<b>🚀 Speed:</b> <code>{file.download_speed_string()}</code>"
                msg += f"\n<b>⏳ Progress:</b> <code>{file.progress_string()}</code>"
                msg += f"\n<b>⏰ ETA:</b> <code>{file.eta_string()}</code>"
                msg += f"\n<b>🔥 Size:</b> <code>{file.total_length_string()}</code>"
                msg += f"\n\n  <i>⚡ Using Engine:</i> <code>aria2</code>"
                if file.seeder is False:
                    """https://t.me/c/1220993104/670177"""
                    #msg += f"| S: {file.num_seeders} |"
                # msg += f"\nStatus: {file.status}"
                #msg += f"\n<code>/cancel {gid}</code>"
                
                # format :- torcancel <provider> <identifier>
                if user_msg is None:
                    mes = await event.get_reply_message()
                else:
                    mes = user_msg
                data = f"torcancel aria2 {gid} {mes.sender_id}"
                
                # LOGGER.info(msg)
                if msg != previous_message:
                    if rdepth < 3:
                        await event.edit(msg,parse_mode="html", buttons=[KeyboardButtonCallback("Cancel Direct Leech",data=data.encode("UTF-8"))])
                    else:
                        await event.edit(msg,parse_mode="html")
                    previous_message = msg
            else:
                msg = file.error_message
                await event.edit(f"`{msg}`",parse_mode="html", buttons=None)
                torlog.error(f"⚠ The aria download faild due to this reason:- {msg}")
                return False, f"⚠ The aria download faild due to this reason:- {msg}"
            await asyncio.sleep(get_val("EDIT_SLEEP_SECS"))
            
            # TODO idk not intrested in using recursion here
            return await check_progress_for_dl(
                aria2, gid, event, previous_message,user_msg=mes
            )
        else:
            await event.edit(f"✅ <b>Download completed:</b> <code>{file.name}</code>\n⏳ Trying to upload... ",parse_mode="html", buttons=None)
            return True, "Download Complete"
    except aria2p.client.ClientException as e:
        if " not found" in str(e) or "'file'" in str(e):
            fname = "getting data... "
            try:
                fname = file.name
            except:pass

            return False, f"The Download was canceled. {fname}"
        else:
            torlog.warning("Errored due to ta client error.")
        pass
    except MessageNotModifiedError:
        pass
    except RecursionError:
        file.remove(force=True)
        return False, "⚠ The link is basically dead."
    except Exception as e:
        torlog.info(str(e))
        if " not found" in str(e) or "'file'" in str(e):
            return False, "The Download was canceled."
        else:
            torlog.warning(str(e))
            return False, f"Error: {str(e)}"
async def register_torrent(entity,
                           message,
                           user_msg=None,
                           magnet=False,
                           file=False):
    client = await get_client()

    #refresh message
    message = await message.client.get_messages(message.chat_id,
                                                ids=message.id)
    if user_msg is None:
        omess = await message.get_reply_message()
    else:
        omess = user_msg

    if magnet:
        torlog.info(magnet)
        torrent = await add_torrent_magnet(entity, message)
        if torrent.progress == 1:
            await message.edit(
                "The provided torrent was already completly downloaded.")
            return True
        else:

            pincode = randint(1000, 9999)
            db = tor_db
            db.add_torrent(torrent.hash, pincode)

            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)
            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit(
                "Download will be automatically started after 180s of no action.",
                buttons=[
                    [
                        KeyboardButtonUrl("Select files📁", urll),
                        KeyboardButtonCallback("💠Generate Code💠",
                                               data=pincodetxt.encode("UTF-8"))
                    ],
                    [
                        KeyboardButtonCallback(
                            "Start 🚀",
                            data=f"doneselection {omess.sender_id} {omess.id}".
                            encode("UTF-8"))
                    ]
                ])

            await get_confirm(omess)

            message = await message.edit(buttons=[
                KeyboardButtonCallback("⚠️ Cancel", data=data.encode("UTF-8"))
            ])

            db.disable_torrent(torrent.hash)

            return await update_progress(client, message, torrent)
    if file:
        torrent = await add_torrent_file(entity, message)
        if torrent.progress == 1:
            await message.edit(
                "The provided torrent was already completly downloaded.")
            return True
        else:
            pincode = randint(1000, 9999)
            db = tor_db
            db.add_torrent(torrent.hash, pincode)

            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)

            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit(buttons=[
                [
                    KeyboardButtonUrl("Select files📁", urll),
                    KeyboardButtonCallback("Get Pincode",
                                           data=pincodetxt.encode("UTF-8"))
                ],
                [
                    KeyboardButtonCallback(
                        "Start 🚀",
                        data=f"doneselection {omess.sender_id} {omess.id}".
                        encode("UTF-8"))
                ]
            ])

            await get_confirm(omess)

            message = await message.edit(buttons=[
                KeyboardButtonCallback("⚠️ Cancel", data=data.encode("UTF-8"))
            ])

            db.disable_torrent(torrent.hash)

            return await update_progress(client, message, torrent)
示例#30
0
async def create_quality_menu(url: str,
                              message: MessageLike,
                              message1: MessageLike,
                              dest: str,
                              jsons: Optional[str] = None,
                              suid: Optional[str] = None):
    if jsons is None:
        data, err = await get_yt_link_details(url)
        suid = str(time.time()).replace(".", "")
    else:
        data = jsons

    #with open("test.txt","w") as f:
    #    f.write(json.dumps(data))

    if data is None:
        return None, err
    else:
        unique_formats = dict()
        for i in data.get("formats"):
            c_format = i.get("format_note")
            if c_format is None:
                c_format = i.get("height")
            if not c_format in unique_formats:
                if i.get("filesize") is not None:
                    unique_formats[c_format] = [
                        i.get("filesize"),
                        i.get("filesize")
                    ]
                else:
                    unique_formats[c_format] = [0, 0]

            else:
                if i.get("filesize") is not None:
                    if unique_formats[c_format][0] > i.get("filesize"):
                        unique_formats[c_format][0] = i.get("filesize")
                    else:
                        unique_formats[c_format][1] = i.get("filesize")

        buttons = list()
        for i in unique_formats.keys():

            # add human bytes here
            if i == "tiny":
                text = f"tiny [{human_readable_bytes(unique_formats[i][0])} - {human_readable_bytes(unique_formats[i][1])}] ➡️"
                cdata = f"ytdlsmenu|{i}|{message1.sender_id}|{suid}|{dest}"  # add user id
            else:
                text = f"{i} [{human_readable_bytes(unique_formats[i][0])} - {human_readable_bytes(unique_formats[i][1])}] ➡️"
                cdata = f"ytdlsmenu|{i}|{message1.sender_id}|{suid}|{dest}"  # add user id
            buttons.append(
                [KeyboardButtonCallback(text, cdata.encode("UTF-8"))])
        buttons.append([
            KeyboardButtonCallback(
                "Audios ➡️",
                f"ytdlsmenu|audios|{message1.sender_id}|{suid}|{dest}")
        ])
        await message.edit("Choose a quality/option available below.",
                           buttons=buttons)

        if jsons is None:
            path = os.path.join(os.getcwd(), 'userdata')

            if not os.path.exists(path):
                os.mkdir(path)

            path = os.path.join(path, f"{suid}.json")

            with open(path, "w", encoding="UTF-8") as file:
                file.write(json.dumps(data))

    return True, None