Exemple #1
0
async def args_triggerer(client, query):
    if args[query.from_user.id]:
        args[query.from_user.id] = False
        await query.message.edit_reply_markup(
            types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(
                    '✅ stdin' if stdin[query.from_user.id] else '❌ stdin',
                    callback_data="stdin_trigger"),
                types.InlineKeyboardButton(
                    '✅ args' if args[query.from_user.id] else '❌ args',
                    callback_data="args_trigger")
            ]]))
        await query.answer("args was Disabled")
    else:
        args[query.from_user.id] = True
        await query.message.edit_reply_markup(
            types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(
                    '✅ stdin' if stdin[query.from_user.id] else '❌ stdin',
                    callback_data="stdin_trigger"),
                types.InlineKeyboardButton(
                    '✅ args' if args[query.from_user.id] else '❌ args',
                    callback_data="args_trigger")
            ]]))
        await query.answer("args was Enabled")
async def config_menu(_, message):
    await message.reply(
        f"**Hello {message.from_user.mention}**,\n\n**If you want to add or set Variable in Heroku use** `/setvar`\n\n**If you want to delete Variable in Heroku use `/delvar`**\n\n**WARNING! Very Recommended to do this command in private since it's contain Bot info.**\n\n**Here's This is Slam-MirrorBot Current Configs**",
        reply_markup=types.InlineKeyboardMarkup(
            [[types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'), types.InlineKeyboardButton(f"BOT CONFIG", callback_data='docs_1')]]
        )
    )
async def voice_handler(_, message):
    file_size = message.audio or message.video or message.voice
    if max_file < file_size.file_size:
        await message.reply_text("**⚠� Max file size has been reached.**")
        return
    file = await message.download(f'{bot.rnd_id()}.mp3')
    r = (await bot.recognize(file)).get('track', None)
    os.remove(file)
    if r is None:
        await message.reply_text('**⚠� Cannot recognize the audio**')
        return
    out = f'**Title**: `{r["title"]}`\n'
    out += f'**Artist**: `{r["subtitle"]}`\n'
    buttons = types.InlineKeyboardMarkup(
        [[
            types.InlineKeyboardButton(
                '🎼 Related Songs',
                switch_inline_query_current_chat=f'related {r["key"]}',
            ),
            types.InlineKeyboardButton('🔗 Share',
                                       url=f'{r["share"]["html"]}')
        ], [types.InlineKeyboardButton('🎵 Listen', url=f'{r["url"]}')],
         [
             types.InlineKeyboardButton(
                 f'💿 More Tracks from {r["subtitle"]}',
                 switch_inline_query_current_chat=
                 f'tracks {r["artists"][0]["id"]}',
             )
         ]])
    await message.reply_photo(r['images']['coverarthq'],
                              caption=out,
                              reply_markup=buttons)
async def rclone_command_f(client, message):
    """/rclone command"""
    LOGGER.info(
        f"rclone command from chatid:{message.chat.id}, userid:{message.from_user.id}"
    )
    if message.from_user.id == OWNER_ID and message.chat.type == "private":
        config.read("rclone_bak.conf")
        sections = list(config.sections())
        inline_keyboard = []
        for section in sections:
            ikeyboard = [
                pyrogram.InlineKeyboardButton(
                    section, callback_data=(f"rclone_{section}").encode("UTF-8")
                )
            ]
            inline_keyboard.append(ikeyboard)
        config.read("rclone.conf")
        section = config.sections()[0]
        msg_text = f"""Default section of rclone config is: **{section}**\n\n
There are {len(sections)} sections in your rclone.conf file, 
please choose which section you want to use:"""
        ikeyboard = [
            pyrogram.InlineKeyboardButton(
                "‼️ Cancel ‼️", callback_data=(f"rcloneCancel").encode("UTF-8")
            )
        ]
        inline_keyboard.append(ikeyboard)
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        await message.reply_text(text=msg_text, reply_markup=reply_markup)
    else:
        await message.reply_text("You have no permission!")
        LOGGER.warning(
            f"uid={message.from_user.id} have no permission to edit rclone config!"
        )
Exemple #5
0
async def except_hook(errtype, value, tback):
    sys.__excepthook__(errtype, value, tback)
    errors = traceback.format_exception(etype=errtype, value=value, tb=tback)
    button = types.InlineKeyboardMarkup([[
        types.InlineKeyboardButton("🐞 Report bugs",
                                   callback_data="report_errors")
    ]])
    text = "An error has accured!\n\n```{}```\n".format("".join(errors))
    if errtype == ModuleNotFoundError:
        text += "\nHint: `pip install -r requirements.txt`"
    await setbot.send_message(Owner, text, reply_markup=button)
Exemple #6
0
async def paste_log_neko(client, query):
    if query.from_user.id == OWNER_ID or SUDO_USER_ID:
        j = open("error.log", "r")
        data = await nekobin.neko(j.read())
        keyb = types.InlineKeyboardMarkup(
            [[types.InlineKeyboardButton("Pasted!", url=f"{data}")]])
        await query.message.edit_caption("Successfully Nekofied",
                                         reply_markup=keyb)
    else:
        await client.answer_callback_query(query.id,
                                           "'Blue Button Must Press', huh?",
                                           show_alert=True)
Exemple #7
0
async def logs_chat(_, message: Message):
    keyb = types.InlineKeyboardMarkup(
        [
            [
                types.InlineKeyboardButton(
                    "Paste on Nekobin", callback_data="paste_log_nekobin"
                )
            ]
        ]
    )
    await message.reply_document(
        "error.log", reply_markup=keyb
    )
Exemple #8
0
async def start_handle(client, message):
    if len(message.text.split()) >= 2:
        if message.text.split()[1] == 'help_inline':
            await message.reply(
                "**How to use @pistonexecbot via inline\n\n type in `@pistonexecbot` <language> <code>**\n\n See /langs for loaded languages",
                reply_markup=types.InlineKeyboardMarkup(
                    [
                        [
                            types.InlineKeyboardButton(
                                'Example',
                                switch_inline_query_current_chat='python3 print("Hello World")'
                            )
                        ]
                    ]
                )
            )
    else:
        await message.reply(
            "**Usage**\n"
            "`/execute` or `/execute [language]` if you want to go for a quick code execution.\n\n"
            "Executing files are not supported yet but will in future\n\n"
            "you can also use me via inline:\n`@pistonexecbot python3 print('Hello World')`\n\n"
            "all available languages can be seen on /langs"
        )
Exemple #9
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text(
        f"<a href='tg://user?id={g_id}'>🔊</a> Now Uploading to ☁️ Cloud!!!"
    )
    if not os.path.exists("rclone.conf"):
        with open("rclone.conf", "w+", newline="\n", encoding="utf-8") as fole:
            fole.write(f"{RCLONE_CONFIG}")
    if os.path.exists("rclone.conf"):
        with open("rclone.conf", "r+") as file:
            con = file.read()
            gUP = re.findall("\[(.*)\]", con)[0]
            LOGGER.info(gUP)
    destination = f"{DESTINATION_FOLDER}"
    file_upload = str(Path(file_upload).resolve())
    LOGGER.info(file_upload)
    if os.path.isfile(file_upload):
        g_au = [
            "rclone",
            "copy",
            "--config=rclone.conf",
            f"{file_upload}",
            f"{gUP}:{destination}",
            "-v",
        ]
        LOGGER.info(g_au)
        tmp = await asyncio.create_subprocess_exec(
            *g_au, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
        )
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode("utf-8"))
        LOGGER.info(cess.decode("utf-8"))
        gk_file = re.escape(os.path.basename(file_upload))
        LOGGER.info(gk_file)
        with open("filter.txt", "w+", encoding="utf-8") as filter:
            print(f"+ {gk_file}\n- *", file=filter)

        t_a_m = [
            "rclone",
            "lsf",
            "--config=rclone.conf",
            "-F",
            "i",
            "--filter-from=filter.txt",
            "--files-only",
            f"{gUP}:{destination}",
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *t_a_m, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
        )
        # os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        gautam = gau.decode().strip()
        LOGGER.info(gau.decode())
        LOGGER.info(tam.decode())
        # os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gjay = size(os.path.getsize(file_upload))
        button = []
        button.append(
            [pyrogram.InlineKeyboardButton(
                text="☁️ CloudUrl ☁️", url=f"{gauti}")]
        )
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{os.path.basename(file_upload)}"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append(
                [
                    pyrogram.InlineKeyboardButton(
                        text="ℹ️ IndexUrl ℹ️", url=f"{tam_link}"
                    )
                ]
            )
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: Uploaded successfully `{os.path.basename(file_upload)}` <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup,
        )
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt = os.path.join(destination, os.path.basename(file_upload))
        LOGGER.info(tt)
        t_am = [
            "rclone",
            "copy",
            "--config=rclone.conf",
            f"{file_upload}",
            f"{gUP}:{tt}",
            "-v",
        ]
        LOGGER.info(t_am)
        tmp = await asyncio.create_subprocess_exec(
            *t_am, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
        )
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode("utf-8"))
        LOGGER.info(cess.decode("utf-8"))
        g_file = re.escape(os.path.basename(file_upload))
        LOGGER.info(g_file)
        with open("filter1.txt", "w+", encoding="utf-8") as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)

        g_a_u = [
            "rclone",
            "lsf",
            "--config=rclone.conf",
            "-F",
            "i",
            "--filter-from=filter1.txt",
            "--dirs-only",
            f"{gUP}:{destination}",
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *g_a_u, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
        )
        # os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode("utf-8"))
        # os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gjay = size(getFolderSize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append(
            [pyrogram.InlineKeyboardButton(
                text="☁️ CloudUrl ☁️", url=f"{gautii}")]
        )
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{os.path.basename(file_upload)}/"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append(
                [
                    pyrogram.InlineKeyboardButton(
                        text="ℹ️ IndexUrl ℹ️", url=f"{tam_link}"
                    )
                ]
            )
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: Uploaded successfully `{os.path.basename(file_upload)}` <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup,
        )
        shutil.rmtree(file_upload)
        await del_it.delete()
async def extract_youtube_dl_formats(url, cf_name, yt_dl_user_name,
                                     yt_dl_pass_word, user_working_dir):
    command_to_exec = [
        "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest", "-j",
        url
    ]
    if "hotstar" in url:
        command_to_exec.append("--geo-bypass-country")
        command_to_exec.append("IN")
    #
    if yt_dl_user_name is not None:
        command_to_exec.append("--username")
        command_to_exec.append(yt_dl_user_name)
    if yt_dl_pass_word is not None:
        command_to_exec.append("--password")
        command_to_exec.append(yt_dl_pass_word)

    LOGGER.info(command_to_exec)
    process = await asyncio.create_subprocess_exec(
        *command_to_exec,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    e_response = stderr.decode().strip()
    LOGGER.info(e_response)
    t_response = stdout.decode().strip()
    LOGGER.info(t_response)
    # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
    if e_response:
        # logger.warn("Status : FAIL", exc.returncode, exc.output)
        error_message = e_response.replace(
            "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.",
            "")
        return None, error_message, None
    if t_response:
        # logger.info(t_response)
        x_reponse = t_response
        response_json = []
        if "\n" in x_reponse:
            for yu_r in x_reponse.split("\n"):
                response_json.append(json.loads(yu_r))
        else:
            response_json.append(json.loads(x_reponse))
        # response_json = json.loads(x_reponse)
        save_ytdl_json_path = user_working_dir + \
            "/" + str("ytdleech") + ".json"
        with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
            json.dump(response_json, outfile, ensure_ascii=False)
        # logger.info(response_json)
        inline_keyboard = []
        #
        thumb_image = DEF_THUMB_NAIL_VID_S
        #
        for current_r_json in response_json:
            #
            thumb_image = current_r_json.get("thumbnail", thumb_image)
            #
            duration = None
            if "duration" in current_r_json:
                duration = current_r_json["duration"]
            if "formats" in current_r_json:
                for formats in current_r_json["formats"]:
                    format_id = formats.get("format_id")
                    format_string = formats.get("format_note")
                    if format_string is None:
                        format_string = formats.get("format")
                    format_ext = formats.get("ext")
                    approx_file_size = ""
                    if "filesize" in formats:
                        approx_file_size = humanbytes(formats["filesize"])
                    dipslay_str_uon = " " + format_string + " (" + format_ext.upper(
                    ) + ") " + approx_file_size + " "
                    cb_string_video = "{}|{}|{}".format(
                        "video", format_id, format_ext)
                    ikeyboard = []
                    if "drive.google.com" in url:
                        if format_id == "source":
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    dipslay_str_uon,
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                    else:
                        if format_string is not None and not "audio only" in format_string:
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    dipslay_str_uon,
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                        else:
                            # special weird case :\
                            ikeyboard = [
                                pyrogram.InlineKeyboardButton(
                                    "SVideo [" + "] ( " + approx_file_size +
                                    " )",
                                    callback_data=(
                                        cb_string_video).encode("UTF-8"))
                            ]
                    inline_keyboard.append(ikeyboard)
                if duration is not None:
                    cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3")
                    cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3")
                    cb_string = "{}|{}|{}".format("audio", "320k", "mp3")
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "64 kbps" + ")",
                            callback_data=cb_string_64.encode("UTF-8")),
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "128 kbps" + ")",
                            callback_data=cb_string_128.encode("UTF-8"))
                    ])
                    inline_keyboard.append([
                        pyrogram.InlineKeyboardButton(
                            "MP3 " + "(" + "320 kbps" + ")",
                            callback_data=cb_string.encode("UTF-8"))
                    ])
            else:
                format_id = current_r_json["format_id"]
                format_ext = current_r_json["ext"]
                cb_string_video = "{}|{}|{}".format("video", format_id,
                                                    format_ext)
                inline_keyboard.append([
                    pyrogram.InlineKeyboardButton(
                        "SVideo",
                        callback_data=(cb_string_video).encode("UTF-8"))
                ])
            break
        reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard)
        # LOGGER.info(reply_markup)
        if cf_name:
            succss_mesg = f"""Select the desired format | {cf_name}"""
        else:
            succss_mesg = f"""Select the desired format"""
        LOGGER.info(succss_mesg)
        return thumb_image, succss_mesg, reply_markup
Exemple #11
0
async def config_button(_, query):
    data = query.data.split('_')[1]
    if data == '1':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Telegram Config ]**\n\n**BOT_TOKEN:** `{BOT_TOKEN}`\n\n**TELEGRAM_API:** `{TELEGRAM_API}`\n\n**TELEGRAM_HASH:** `{TELEGRAM_HASH}`\n\n**TELEGRAPH_TOKEN:** `{telegraph_token}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_10'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_2')
            ]]))
    elif data == '2':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Drive and Index Config ]**\n\n**GDRIVE_FOLDER_ID:** `{parent_id}`\n\n**IS_TEAM_DRIVE:** `{IS_TEAM_DRIVE}`\n\n**USE_SERVICE_ACCOUNTS:** `{USE_SERVICE_ACCOUNTS}`\n\n**INDEX_URL:** `{INDEX_URL}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_1'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_3')
            ]]))
    elif data == '3':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Mega and Uptobox Config ]**\n\n**MEGA_API_KEY:** `{MEGA_API_KEY}`\n\n**MEGA_EMAIL_ID:** `{MEGA_EMAIL_ID}`\n\n**MEGA_PASSWORD:** `{MEGA_PASSWORD}`\n\n**UPTOBOX_TOKEN:** `{UPTOBOX_TOKEN}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_2'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_4')
            ]]))
    elif data == '4':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Stop Duplicate Config ]**\n\n**STOP_DUPLICATE_MIRROR:** `{STOP_DUPLICATE_MIRROR}`\n\n**STOP_DUPLICATE_CLONE:** `{STOP_DUPLICATE_CLONE}`\n\n**STOP_DUPLICATE_MEGA:** `{STOP_DUPLICATE_MEGA}`\n\n**[ Block Mega Config ]**\n\n**BLOCK_MEGA_FOLDER:** `{BLOCK_MEGA_FOLDER}`\n\n**BLOCK_MEGA_LINKS:** `{BLOCK_MEGA_LINKS}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_3'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_5')
            ]]))
    elif data == '5':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Limit Size Config ]**\n\n**TORRENT_DIRECT_LIMIT:** `{TORRENT_DIRECT_LIMIT}`\n\n**TAR_UNZIP_LIMIT:** `{TAR_UNZIP_LIMIT}`\n\n**CLONE_LIMIT:** `{CLONE_LIMIT}`\n\n**MEGA_LIMIT:** `{MEGA_LIMIT}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_4'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_6')
            ]]))
    elif data == '6':
        user = sudo = ''
        user += '\n'.join(str(id) for id in AUTHORIZED_CHATS)
        sudo += '\n'.join(str(id) for id in SUDO_USERS)
        return await query.message.edit(
            __header__.format(data) +
            f"**[ User ID Config ]**\n\n**OWNER_ID:** `{OWNER_ID}`\n\n**AUTHORIZED_CHATS:**\n`{user}`\n\n**SUDO_USERS:**\n`{sudo}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_5'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_7')
            ]]))
    elif data == '7':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Button Config ]**\n\n**BUTTON_FOUR_NAME:** `{BUTTON_FOUR_NAME}`\n\n**BUTTON_FOUR_URL:** `{BUTTON_FOUR_URL}`\n\n**BUTTON_FIVE_NAME:** `{BUTTON_FIVE_NAME}`\n\n**BUTTON_FIVE_URL:** `{BUTTON_FIVE_URL}`\n\n**BUTTON_SIX_NAME:** `{BUTTON_SIX_NAME}`\n\n**BUTTON_SIX_URL:** `{BUTTON_SIX_URL}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_6'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_8')
            ]]))
    elif data == '8':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Heroku Config ]**\n\n**HEROKU_API_KEY:** `{HEROKU_API_KEY}`\n\n**HEROKU_APP_NAME:** `{HEROKU_APP_NAME}`\n\n**[ Shortener Config ]**\n\n**SHORTENER:** `{SHORTENER}`\n\n**SHORTENER_API:** `{SHORTENER_API}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_7'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_9')
            ]]))
    elif data == '9':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Others Config ]**\n\n**VIEW_LINK:** `{VIEW_LINK}`\n\n**DOWNLOAD_STATUS_UPDATE_INTERVAL:** `{DOWNLOAD_STATUS_UPDATE_INTERVAL}`\n\n**IGNORE_PENDING_REQUESTS:** `{IGNORE_PENDING_REQUESTS}`\n\n**AUTO_DELETE_MESSAGE_DURATION:** `{AUTO_DELETE_MESSAGE_DURATION}`\n\n**DOWNLOAD_DIR:** `{DOWNLOAD_DIR}`\n\n**IMAGE_URL:** `{IMAGE_URL}`\n\n**DATABASE_URL:** `{DB_URI}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_8'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_10')
            ]]))
    elif data == '10':
        return await query.message.edit(
            __header__.format(data) +
            f"**[ Visual Config ]**\n\n**FINISHED_PROGRESS_STR:** `{FINISHED_PROGRESS_STR}`\n\n**UNFINISHED_PROGRESS_STR:** `{UNFINISHED_PROGRESS_STR}`",
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}",
                                           callback_data='docs_9'),
                types.InlineKeyboardButton(f"{emoji.CROSS_MARK}",
                                           callback_data='docs_end'),
                types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}",
                                           callback_data='docs_1')
            ]]))
    elif data == 'end':
        return await query.message.delete()
Exemple #12
0
async def alive(client, message):
    try:
        stdin[message.from_user.id]
        args[message.from_user.id]
    except KeyError:
        stdin[message.from_user.id] = False
        args[message.from_user.id] = False
    buttons = []
    buton = types.InlineKeyboardMarkup([[
        types.InlineKeyboardButton(
            '✅ stdin' if stdin[message.from_user.id] else '❌ stdin',
            callback_data="stdin_trigger"),
        types.InlineKeyboardButton(
            '✅ args' if args[message.from_user.id] else '❌ args',
            callback_data="args_trigger")
    ]])

    if len(message.text.split(None, 1)) == 2:
        lan = message.text.split(None, 1)[1]
        if lan not in lang_names:
            await message.reply("Wrong language of choice!")
            return
        else:
            codes = "**Language**: `{}`\n\nGive me a code to execute:".format(
                lan)
    else:
        for l in langs:
            buttons.append(
                [types.KeyboardButton(l.language + " " + (l.version or ""))])
        language = await client.ask(
            message.chat.id,
            f"pick a language from Keyboard:",
            reply_markup=types.ReplyKeyboardMarkup(buttons),
            reply_to_message_id=message.message_id)
        lan = language.text.split(None, 1)
        if lan[0] not in lang_names:
            await message.reply("Wrong language of choice",
                                reply_markup=types.ReplyKeyboardRemove())
            return
        try:
            for l in langs:
                if lan[0] == l.language:
                    codes = "**Language**: `{}`\n**Version**: `{}`\n\nGive me a code to execute:".format(
                        l.language, l.version)
        except IndexError:
            codes = "**Language**: `{}`\n\nGive me a code to execute:".format(
                lan[0])
    await message.reply("got it!", reply_markup=types.ReplyKeyboardRemove())
    source = await client.ask(message.chat.id,
                              text=codes,
                              reply_to_message_id=message.message_id,
                              reply_markup=buton)
    if stdin[message.from_user.id]:
        std = await client.ask(
            message.chat.id,
            text="give me your input to the code",
            reply_to_message_id=message.message_id,
        )
        std = std.text
    else:
        std = None
    if args[message.from_user.id]:
        arg = await client.ask(
            message.chat.id,
            text="give me arguments to the code separated by a 'space'",
            reply_to_message_id=message.message_id,
        )
        arg = arg.text.split(" ")
    else:
        arg = None
    start_time = time.time()
    for l in langs:
        if lan[0] == l.language:
            output = await piston.execute(language=lan if len(
                message.text.split(None, 1)) == 2 else lan[0],
                                          source=source.text,
                                          version=l.version,
                                          stdin=std,
                                          args=arg)
    out = "**-Result-**\n"
    try:
        if output.language:
            out += f"**Language**: ```{output.language}```\n\n"
        # if output.output:
        #     out += f"**Output**:\n```{output.output}```\n\n"
        if output.run:
            out += f"**Stdout**:\n```{output.run.output}```\n\n"
        await message.reply(
            out,
            reply_markup=types.InlineKeyboardMarkup([[
                types.InlineKeyboardButton(
                    'stats', callback_data=f'stats-{start_time}-{time.time()}')
            ]]))

    except AttributeError as err:
        await message.reply(f"Code Execution was not Successful!\n```{err}```")
async def config_button(_, query):
    data = query.data.split('_')[1]
    if data == '1':
        return await query.message.edit(
            __header__.format(data)
            + f"**[ Telegram Config ]**\n\n**Bot Token:** `{BOT_TOKEN}`\n\n**Telegram API:** `{TELEGRAM_API}`\n\n**Telegram HASH:** `{TELEGRAM_HASH}`\n\n**Telegraph Token:** `{telegraph_token}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_9'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_2')
                    ]
                ]
            )
        )
    elif data == '2':
        return await query.message.edit(
            __header__.format(data)
            + f"**[ Drive and Index Config ]**\n\n**Drive Folder:** `{parent_id}`\n\n**Using Team Drive:** `{IS_TEAM_DRIVE}`\n\n**Using Service Account:** `{USE_SERVICE_ACCOUNTS}`\n\n**Index Url:** `{INDEX_URL}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_1'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_3')
                    ]
                ]
            )
        )
    elif data == '3':
        return await query.message.edit(
            __header__.format(data)
            + f"**[ Mega and Uptobox Config ]**\n\n**Mega API:** `{MEGA_API_KEY}`\n\n**Mega Email:** `{MEGA_EMAIL_ID}`\n\n**Mega Password:** `{MEGA_PASSWORD}`\n\n**Uptobox Token:** `{UPTOBOX_TOKEN}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_2'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_4')
                    ]
                ]
            )
        )
    elif data == '4':
        return await query.message.edit(
            __header__.format(data)
            + f"**[ Stop Duplicate Config ]**\n\n**Mirror:** `{STOP_DUPLICATE_MIRROR}`\n\n**Clone:** `{STOP_DUPLICATE_CLONE}`\n\n**Mega:** `{STOP_DUPLICATE_MEGA}`\n\n**[ Block Mega Config ]**\n\n**Folder:** `{BLOCK_MEGA_FOLDER}`\n\n**Link:** `{BLOCK_MEGA_LINKS}`\n\n",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_3'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_5')
                    ]
                ]
            )
        )
    elif data == '5':
        return await query.message.edit(
            __header__.format(data)
            + f"**[ Limit Size Config ]**\n\n**Torrent and Direct:** `{TORRENT_DIRECT_LIMIT}`\n\n**Tar and Unzip:** `{TAR_UNZIP_LIMIT}`\n\n**Clone:** `{CLONE_LIMIT}`\n\n**Mega:** `{MEGA_LIMIT}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_4'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_6')
                    ]
                ]
            )
        )
    elif data == '6':
        user = sudo = ''
        user += '\n'.join(str(id) for id in AUTHORIZED_CHATS)
        sudo += '\n'.join(str(id) for id in SUDO_USERS)
        return await query.message.edit(
            __header__.format(data)
            + f"**[ User ID Config ]**\n\n**Owner ID:** `{OWNER_ID}`\n\n**Authorized Chat:**\n`{user}`\n\n**Sudo Users:**\n`{sudo}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_5'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_7')
                    ]
                ]
            )
        )
    elif data == '7':
        return await query.message.edit(
            __header__.format(data)
            + f"**[ Button Config ]**\n\n**Button Four Name:** `{BUTTON_FOUR_NAME}`\n\n**Button Four Url:** `{BUTTON_FOUR_URL}`\n\n**Button Five Name:** `{BUTTON_FIVE_NAME}`\n\n**Button Five Url:** `{BUTTON_FIVE_URL}`\n\n**Button Six Name:** `{BUTTON_SIX_NAME}`\n\n**Button Six Url:** `{BUTTON_SIX_URL}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_6'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_8')
                    ]
                ]
            )
        )
    elif data == '8':
        return await query.message.edit(
            __header__.format(data)
            + f"**[ Heroku Config ]**\n\n**Heroku Name:** `{HEROKU_APP_NAME}`\n\n**Heroku API:** `{HEROKU_API_KEY}`\n\n**[ Shortener Config ]**\n\n**Shortener Name:** `{SHORTENER}`\n\n**Shortener API:** `{SHORTENER_API}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_7'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_9')
                    ]
                ]
            )
        )
    elif data == '9':
        return await query.message.edit(
            __header__.format(data)
            + f" **[ Others Config ]**\n\n**View Link:** `{VIEW_LINK}`\n\n**Status Interval:** `{DOWNLOAD_STATUS_UPDATE_INTERVAL}`\n\n**Ignore Pending Request:** `{IGNORE_PENDING_REQUESTS}`\n\n**Delete Message Duration:** `{AUTO_DELETE_MESSAGE_DURATION}`\n\n**Directory:** `{DOWNLOAD_DIR}`\n\n**Image Url:** `{IMAGE_URL}`\n\n**Database Url:** `{DB_URI}`",
            reply_markup=types.InlineKeyboardMarkup(
                [
                    [
                        types.InlineKeyboardButton(f"{emoji.LEFT_ARROW}", callback_data='docs_8'),
                        types.InlineKeyboardButton(f"{emoji.CROSS_MARK}", callback_data='docs_end'),
                        types.InlineKeyboardButton(f"{emoji.RIGHT_ARROW}", callback_data='docs_1')
                    ]
                ]
            )
        )
    elif data == 'end':
        return await query.message.delete()
Exemple #14
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text(
        f"<a href='tg://user?id={g_id}'>🔊</a> 𝙉𝙤𝙬 𝙐𝙥𝙡𝙤𝙖𝙙𝙞𝙣𝙜 𝙩𝙤 ☁️ 𝘾𝙡𝙤𝙪𝙙!!!")
    #subprocess.Popen(('touch', 'rclone.conf'), stdout = subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n", encoding='utf-8') as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        g_au = [
            'rclone', 'copy', '--config=./rclone.conf', f'./{file_upload}',
            'DRIVE:'
            f'{destination}', '-v'
        ]
        tmp = await asyncio.create_subprocess_exec(
            *g_au,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        gk_file = re.escape(file_upload)
        LOGGER.info(gk_file)
        with open('filter.txt', 'w+', encoding='utf-8') as filter:
            print(f"+ {gk_file}\n- *", file=filter)

        t_a_m = [
            'rclone', 'lsf', '--config=./rclone.conf', '-F', 'i',
            "--filter-from=./filter.txt", "--files-only", 'DRIVE:'
            f'{destination}'
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *t_a_m,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        #os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        LOGGER.info(gau_link)
        gjay = size(os.path.getsize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: Uploaded successfully `{file_upload}` <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt = os.path.join(destination, file_upload)
        LOGGER.info(tt)
        t_am = [
            'rclone', 'copy', '--config=./rclone.conf', f'./{file_upload}',
            'DRIVE:'
            f'{tt}', '-v'
        ]
        tmp = await asyncio.create_subprocess_exec(
            *t_am,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        g_file = re.escape(file_upload)
        LOGGER.info(g_file)
        with open('filter1.txt', 'w+', encoding='utf-8') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)

        g_a_u = [
            'rclone', 'lsf', '--config=./rclone.conf', '-F', 'i',
            "--filter-from=./filter1.txt", "--dirs-only", 'DRIVE:'
            f'{destination}'
        ]
        gau_tam = await asyncio.create_subprocess_exec(
            *g_a_u,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        #os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        LOGGER.info(gau_link)
        gjay = size(getFolderSize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([
            pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️",
                                          url=f"{gau_link}")
        ])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([
                pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️",
                                              url=f"{tam_link}")
            ])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(
            f"🤖: Uploaded successfully `{file_upload}` <a href='tg://user?id={g_id}'>🤒</a>\n📀 Size: {gjay}",
            reply_markup=button_markup)
        shutil.rmtree(file_upload)
        await del_it.delete()
Exemple #15
0
async def inline_exec(client, query):
    string = query.query
    offset = int(query.offset or 0)
    answers = []
    if string == '':
        for l in langs[offset:offset + NEXT_OFFSET]:
            answers.append(
                types.InlineQueryResultArticle(
                    title=l.language,
                    description=l.version or None,
                    input_message_content=types.InputTextMessageContent(
                        "**Language:** `{}`{}\nPress the button below to Execute your code:"
                        .format(l.language,
                                '\n**Version:** `{}`'.format(l.version)
                                or '')),
                    reply_markup=types.InlineKeyboardMarkup([[
                        types.InlineKeyboardButton(
                            'Execute',
                            switch_inline_query_current_chat=l.language + " ")
                    ]])))
    elif string.split()[0] in lang_names:
        if len(string.split()) == 1:
            await client.answer_inline_query(
                query.id,
                results=answers,
                switch_pm_text=f'Give a code to Excute in {string.split()[0]}',
                switch_pm_parameter='help_inline',
            )
            return
        source = string.split(None, 1)[1]
        start_time = time.time()
        for l in langs:
            if string.split()[0] == l.language:
                out = await piston.execute(language=string.split()[0],
                                           version=l.version,
                                           source=source)
        try:

            msg = f"**Language:** `{out.language}-{out.version}`\n\n**Code:**\n```{source}```\n\n"
            if out.run:
                msg += f"**Output:**\n```{out.run.output}```\n\n"
            answers.append(
                types.InlineQueryResultArticle(
                    "Output:",
                    description=out.run.stdout or out.run.stderr,
                    input_message_content=types.InputTextMessageContent(
                        msg, parse_mode='markdown'),
                    reply_markup=types.InlineKeyboardMarkup(
                        [[
                            types.InlineKeyboardButton(
                                'stats',
                                callback_data=
                                f'stats-{start_time}-{time.time()}')
                        ],
                         [
                             types.InlineKeyboardButton(
                                 'Fork',
                                 switch_inline_query_current_chat=
                                 f'{out.language} {source}'),
                             types.InlineKeyboardButton(
                                 'Try Again',
                                 switch_inline_query_current_chat=
                                 f'{out.language} '),
                         ]])))
            execute[query.from_user.id] = True
        except AttributeError as err:
            answers.append(
                types.InlineQueryResultArticle(
                    "Error",
                    description=str(err),
                    input_message_content=types.InputTextMessageContent(
                        str(err), )))
        return await client.answer_inline_query(
            query.id,
            results=answers,
            cache_time=0,
        )
    try:
        await client.answer_inline_query(
            query.id,
            results=answers,
            next_offset=str(offset + NEXT_OFFSET),
            cache_time=0,
        )
    except errors.exceptions.bad_request_400.QueryIdInvalid:
        return
Exemple #16
0
    async def link_gen_size(self):
        if self.name is not None:
            _drive = ""
            if self.name == self.filee:
                _flag = "--files-only"
                _up = "File"
                _ui = ""
            else:
                _flag = "--dirs-only"
                _up = "Folder"
                _drive = "folderba"
                _ui = "/"
            g_name = re.escape(self.name)
            LOGGER.info(g_name)
            destination = f'{DESTINATION_FOLDER}'

            with open('filter1.txt', 'w+', encoding='utf-8') as filter1:
                print(f"+ {g_name}{_ui}\n- *", file=filter1)

            g_a_u = [
                'rclone', 'lsf', '--config=./rclone.conf', '-F', 'i',
                "--filter-from=./filter1.txt", f"{_flag}",
                f'DRIVE:{destination}'
            ]
            LOGGER.info(g_a_u)
            gau_tam = await asyncio.create_subprocess_exec(
                *g_a_u,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE)
            gau, tam = await gau_tam.communicate()
            LOGGER.info(gau)
            gautam = gau.decode("utf-8")
            LOGGER.info(gautam)
            LOGGER.info(tam.decode('utf-8'))

            if _drive == "folderba":
                gautii = f"https://drive.google.com/folderview?id={gautam}"
            else:
                gautii = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"

            LOGGER.info(gautii)
            gau_link = re.search("(?P<url>https?://[^\s]+)",
                                 gautii).group("url")
            LOGGER.info(gau_link)
            button = []
            button.append([
                pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️",
                                              url=f"{gau_link}")
            ])
            if INDEX_LINK:
                if _flag == "--files-only":
                    indexurl = f"{INDEX_LINK}/{self.name}"
                else:
                    indexurl = f"{INDEX_LINK}/{self.name}/"
                tam_link = requests.utils.requote_uri(indexurl)
                LOGGER.info(tam_link)
                button.append([
                    pyrogram.InlineKeyboardButton(text="ℹ️ IndexUrl ℹ️",
                                                  url=f"{tam_link}")
                ])
            button_markup = pyrogram.InlineKeyboardMarkup(button)
            msg = await self.lsg.edit_text(
                f"🤖: {_up} cloned successfully in your Cloud <a href='tg://user?id={self.u_id}'>🤒</a>\
                \n📀 Info: Calculating...",
                reply_markup=button_markup,
                parse_mode="html")
            g_cmd = [
                'rclone', 'size', '--config=rclone.conf',
                f'DRIVE:{destination}/{self.name}'
            ]
            LOGGER.info(g_cmd)
            gaut_am = await asyncio.create_subprocess_exec(
                *g_cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE)
            gaut, am = await gaut_am.communicate()
            g_autam = gaut.decode("utf-8")
            LOGGER.info(g_autam)
            LOGGER.info(am.decode('utf-8'))
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await msg.edit_text(
                f"🤖: {_up} cloned successfully in your Cloud <a href='tg://user?id={self.u_id}'>🤒</a>\
                \n📀 Info:\n{g_autam}",
                reply_markup=button_markup,
                parse_mode="html")
Exemple #17
0
async def upload_to_gdrive(file_upload, message, messa_ge, g_id):
    await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
    del_it = await message.edit_text("<b> Now Uploading to Drive.....</b>")
    #subprocess.Popen(('touch', 'rclone.conf'), stdout = subprocess.PIPE)
    with open('rclone.conf', 'a', newline="\n", encoding = 'utf-8') as fole:
        fole.write("[DRIVE]\n")
        fole.write(f"{RCLONE_CONFIG}")
    destination = f'{DESTINATION_FOLDER}'
    if os.path.isfile(file_upload):
        g_au = ['rclone', 'copy', '--config=/app/rclone.conf', f'/app/{file_upload}', 'DRIVE:'f'{destination}', '-v']
        tmp = await asyncio.create_subprocess_exec(*g_au, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        gk_file = re.escape(file_upload)
        LOGGER.info(gk_file)
        with open('filter.txt', 'w+', encoding = 'utf-8') as filter:
            print(f"+ {gk_file}\n- *", file=filter)
            
        t_a_m = ['rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i', "--filter-from=/app/filter.txt", "--files-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*t_a_m, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter.txt")
        gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gauti).group("url")
        LOGGER.info(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}"
        #tam_link = requests.utils.requote_uri(indexurl)
        gjay = size(os.path.getsize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="💥 GOOGLE DRIVE URL 💥", url=f"{gau_link}")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([pyrogram.InlineKeyboardButton(text="⚡INDEX LINK⚡", url=f"{tam_link}")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: {file_upload} <b>has been Uploaded successfully to your Cloud</b> <a href='tg://user?id={g_id}'>😋</a>\n<b>Total Size😯</b>: {gjay}", reply_markup=button_markup)
        #await message.edit_text(f"""🤖: {file_upload} has been Uploaded successfully to your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FileLink</a>\nℹ️ Direct URL:  <a href="{tam_link}">IndexLink</a>""")
        os.remove(file_upload)
        await del_it.delete()
    else:
        tt= os.path.join(destination, file_upload)
        LOGGER.info(tt)
        t_am = ['rclone', 'copy', '--config=/app/rclone.conf', f'/app/{file_upload}', 'DRIVE:'f'{tt}', '-v']
        tmp = await asyncio.create_subprocess_exec(*t_am, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        pro, cess = await tmp.communicate()
        LOGGER.info(pro.decode('utf-8'))
        LOGGER.info(cess.decode('utf-8'))
        g_file = re.escape(file_upload)
        LOGGER.info(g_file)
        with open('filter1.txt', 'w+', encoding = 'utf-8') as filter1:
            print(f"+ {g_file}/\n- *", file=filter1)
            
        g_a_u = ['rclone', 'lsf', '--config=/app/rclone.conf', '-F', 'i', "--filter-from=/app/filter1.txt", "--dirs-only", 'DRIVE:'f'{destination}']
        gau_tam = await asyncio.create_subprocess_exec(*g_a_u, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        #os.remove("filter1.txt")
        gau, tam = await gau_tam.communicate()
        LOGGER.info(gau)
        gautam = gau.decode("utf-8")
        LOGGER.info(gautam)
        LOGGER.info(tam.decode('utf-8'))
        #os.remove("filter1.txt")
        gautii = f"https://drive.google.com/folderview?id={gautam}"
        gau_link = re.search("(?P<url>https?://[^\s]+)", gautii).group("url")
        LOGGER.info(gau_link)
        #indexurl = f"{INDEX_LINK}/{file_upload}/"
        #tam_link = requests.utils.requote_uri(indexurl)
        #print(tam_link)
        gjay = size(getFolderSize(file_upload))
        LOGGER.info(gjay)
        button = []
        button.append([pyrogram.InlineKeyboardButton(text="💥 GOOGLE DRIVE URL 💥", url=f"{gau_link}")])
        if INDEX_LINK:
            indexurl = f"{INDEX_LINK}/{file_upload}/"
            tam_link = requests.utils.requote_uri(indexurl)
            LOGGER.info(tam_link)
            button.append([pyrogram.InlineKeyboardButton(text="⚡ INDEX LINK ⚡", url=f"{tam_link}")])
        button_markup = pyrogram.InlineKeyboardMarkup(button)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await messa_ge.reply_text(f"🤖: <b>Folder has been Uploaded successfully to {tt} in your Cloud</b> <a href='tg://user?id={g_id}'>😋</a>\n<b>Total Size😯</b>: {gjay}", reply_markup=button_markup)
        #await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        #await messa_ge.reply_text(f"""🤖: Folder has been Uploaded successfully to {tt} in your cloud 🤒\n\n☁️ Cloud URL:  <a href="{gau_link}">FolderLink</a>\nℹ️ Index Url:. <a href="{tam_link}">IndexLink</a>""")
        shutil.rmtree(file_upload)
        await del_it.delete()
async def inline_func(client, query):
    string = query.query.lower()
    answers = []
    if string == '':
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text='Need help? Click here',
            switch_pm_parameter='help_inline',
        )
        return
    if string.split()[0] == 'related':
        if len(string.split()) == 1:
            await client.answer_inline_query(
                query.id,
                results=answers,
                switch_pm_text='Input Song ID',
                switch_pm_parameter='help_inline',
            )
            return
        try:
            track_id = int(string.split(None, 1)[1])
        except ValueError:
            return
        try:
            for x in (await bot.related(track_id)):
                try:
                    result = (x['images']['coverarthq'],
                              x['images']['coverart'], x['title'],
                              x['subtitle'], x['share']['href'],
                              x['share']['html'])
                except KeyError:
                    result = (None, None, x['title'], x['subtitle'],
                              x['share']['href'], x['share']['html'])
                image, thumb, title, artist, link, share = result
                answers.append(
                    types.InlineQueryResultArticle(
                        title=title,
                        description=artist,
                        thumb_url=thumb,
                        input_message_content=types.InputTextMessageContent(
                            f'**Title**: {title}\n**Artist**: {artist}[\u200c\u200c\u200e]({image})'
                        ),
                        reply_markup=types.InlineKeyboardMarkup(
                            [[
                                types.InlineKeyboardButton('🔗 Share',
                                                           url=f'{share}')
                            ],
                             [
                                 types.InlineKeyboardButton('🎵 Listen',
                                                            url=f'{link}')
                             ]])))
        except TypeError:
            return await client.answer_inline_query(
                query.id,
                results=answers,
                switch_pm_text='cannot find the Song',
                switch_pm_parameter='help_inline',
            )
            return
    elif string.split()[0] == 'artist':
        if len(string.split()) == 1:
            await client.answer_inline_query(
                query.id,
                results=answers,
                switch_pm_text='Input Artist Name',
                switch_pm_parameter='help_inline',
            )
            return
        artists = await bot.get_artist(string.split(None, 1)[1])
        if artists is None:
            return await client.answer_inline_query(
                query.id,
                results=answers,
                switch_pm_text='Cannot find the Artist',
                switch_pm_parameter='help_inline',
            )
            return
        for artist in artists:
            answers.append(
                types.InlineQueryResultArticle(
                    title=artist.name,
                    description=None,
                    thumb_url=artist.avatar or None,
                    input_message_content=types.InputTextMessageContent(
                        f'**Artist name:**{artist.name} [\u200c\u200c\u200e]({artist.avatar})'
                    ),
                    reply_markup=types.InlineKeyboardMarkup([[
                        types.InlineKeyboardButton('🔗 More Info',
                                                   url=f'{artist.url}')
                    ]])))
    elif string.split()[0] == 'tracks':
        if len(string.split()) == 1:
            await client.answer_inline_query(
                query.id,
                results=answers,
                switch_pm_text='Input Artist ID',
                switch_pm_parameter='help_inline',
            )
            return
        tracks = await bot.get_artist_tracks(string.split(None, 1)[1])
        if tracks is None:
            return await client.answer_inline_query(
                query.id,
                results=answers,
                switch_pm_text='Cannot find the Artist',
                switch_pm_parameter='help_inline',
            )
            return
        for track in tracks:
            answers.append(
                types.InlineQueryResultArticle(
                    title=track.title,
                    description=track.subtitle,
                    thumb_url=track.apple_music_url or None,
                    input_message_content=types.InputTextMessageContent(
                        f'**Title:** {track.title}\n**Artist**: {track.subtitle} [\u200c\u200c\u200e]({track.apple_music_url})'
                    ),
                    reply_markup=types.InlineKeyboardMarkup([[
                        types.InlineKeyboardButton('🎵 Listen',
                                                   url=f'{track.shazam_url}')
                    ]])))
    await client.answer_inline_query(
        query.id,
        results=answers,
        cache_time=0,
    )