Example #1
0
async def start(bot, cmd):
    usr_cmdall1 = cmd.text
    if usr_cmdall1.startswith("/start subinps"):
        if AUTH_CHANNEL:
            invite_link = await bot.create_chat_invite_link(int(AUTH_CHANNEL))
            try:
                user = await bot.get_chat_member(int(AUTH_CHANNEL),
                                                 cmd.from_user.id)
                if user.status == "kicked":
                    await bot.send_message(
                        chat_id=cmd.from_user.id,
                        text="Sorry Sir, You are Banned to use me.",
                        parse_mode="markdown",
                        disable_web_page_preview=True)
                    return
            except UserNotParticipant:
                ident, file_id = cmd.text.split("_-_-_-_")
                await bot.send_message(
                    chat_id=cmd.from_user.id,
                    text="**Please Join My Updates Channel to use this Bot!**",
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            InlineKeyboardButton("🤖 Join Updates Channel",
                                                 url=invite_link.invite_link)
                        ],
                         [
                             InlineKeyboardButton(
                                 " 🔄 Try Again",
                                 callback_data=f"checksub#{file_id}")
                         ]]),
                    parse_mode="markdown")
                return
            except Exception:
                await bot.send_message(chat_id=cmd.from_user.id,
                                       text="Something went Wrong.",
                                       parse_mode="markdown",
                                       disable_web_page_preview=True)
                return
        try:
            ident, file_id = cmd.text.split("_-_-_-_")
            filedetails = await get_file_details(file_id)
            for files in filedetails:
                title = files.file_name
                size = files.file_size
                f_caption = files.caption
                if CUSTOM_FILE_CAPTION:
                    try:
                        f_caption = CUSTOM_FILE_CAPTION.format(
                            file_name=title,
                            file_size=size,
                            file_caption=f_caption)
                    except Exception as e:
                        print(e)
                        f_caption = f_caption
                if f_caption is None:
                    f_caption = f"{files.file_name}"
                buttons = [[
                    InlineKeyboardButton('Search again',
                                         switch_inline_query_current_chat=''),
                    InlineKeyboardButton('More Bots',
                                         url='https://t.me/subin_works/122')
                ]]
                await bot.send_cached_media(
                    chat_id=cmd.from_user.id,
                    file_id=file_id,
                    caption=f_caption,
                    reply_markup=InlineKeyboardMarkup(buttons))
        except Exception as err:
            await cmd.reply_text(f"Something went wrong!\n\n**Error:** `{err}`"
                                 )
    elif len(cmd.command) > 1 and cmd.command[1] == 'subscribe':
        invite_link = await bot.create_chat_invite_link(int(AUTH_CHANNEL))
        await bot.send_message(
            chat_id=cmd.from_user.id,
            text="**Please Join My Updates Channel to use this Bot!**",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("🤖 Join Updates Channel",
                                     url=invite_link.invite_link)
            ]]))
    else:
        await cmd.reply_text(
            START_MSG,
            parse_mode="Markdown",
            disable_web_page_preview=True,
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("Search Here",
                                     switch_inline_query_current_chat=''),
                InlineKeyboardButton("Other Bots",
                                     url="https://t.me/subin_works/122")
            ], [InlineKeyboardButton("About", callback_data="about")]]))
Example #2
0
async def answer(bot, query):
    """Show search results for given inline query"""

    if AUTH_CHANNEL and not await is_subscribed(bot, query):
        await query.answer(results=[],
                           cache_time=0,
                           switch_pm_text='You have to subscribe my channel to use the bot',
                           switch_pm_parameter="subscribe")
        return

    results = []
    if '|' in query.query:
        string, file_type = query.query.split('|', maxsplit=1)
        string = string.strip()
        file_type = file_type.strip().lower()
    else:
        string = query.query.strip()
        file_type = None

    offset = int(query.offset or 0)
    reply_markup = get_reply_markup(query=string)
    files, next_offset = await get_search_results(string,
                                                  file_type=file_type,
                                                  max_results=10,
                                                  offset=offset)

    for file in files:
        title=file.file_name
        size=file.file_size
        f_caption=file.caption
        if CUSTOM_FILE_CAPTION:
            try:
                f_caption=CUSTOM_FILE_CAPTION.format(file_name=title, file_size=size, file_caption=f_caption)
            except Exception as e:
                print(e)
                f_caption=f_caption
        if f_caption is None:
            f_caption = f"{file.file_name}"
        results.append(
            InlineQueryResultCachedDocument(
                title=file.file_name,
                file_id=file.file_id,
                caption=f_caption,
                description=f'Size: {get_size(file.file_size)}\nType: {file.file_type}',
                reply_markup=reply_markup))

    if results:
        switch_pm_text = f"{emoji.FILE_FOLDER} Results"
        if string:
            switch_pm_text += f" for {string}"

        try:
            await query.answer(results=results,
                           is_personal = True,
                           cache_time=cache_time,
                           switch_pm_text=switch_pm_text,
                           switch_pm_parameter="start",
                           next_offset=str(next_offset))
        except Exception as e:
            logging.exception(str(e))
            await query.answer(results=[], is_personal=True,
                           cache_time=cache_time,
                           switch_pm_text=str(e)[:63],
                           switch_pm_parameter="error")
    else:

        switch_pm_text = f'{emoji.CROSS_MARK} No results'
        if string:
            switch_pm_text += f' for "{string}"'

        await query.answer(results=[],
                           is_personal = True,
                           cache_time=cache_time,
                           switch_pm_text=switch_pm_text,
                           switch_pm_parameter="okay")
Example #3
0
async def cb_handler(client: Client, query: CallbackQuery):
    clicked = query.from_user.id
    try:
        typed = query.message.reply_to_message.from_user.id
    except:
        typed = query.from_user.id
        pass
    if (clicked == typed):

        if query.data.startswith("next"):
            ident, index, keyword = query.data.split("_")
            try:
                data = BUTTONS[keyword]
            except KeyError:
                await query.answer(
                    "You are using this for one of my old message, please send the request again.",
                    show_alert=True)
                return

            if int(index) == int(data["total"]) - 2:
                buttons = data['buttons'][int(index) + 1].copy()

                buttons.append([
                    InlineKeyboardButton(
                        "⏪ BACK",
                        callback_data=f"back_{int(index)+1}_{keyword}")
                ])
                buttons.append([
                    InlineKeyboardButton(
                        f"📃 Pages {int(index)+2}/{data['total']}",
                        callback_data="pages")
                ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
                return
            else:
                buttons = data['buttons'][int(index) + 1].copy()

                buttons.append([
                    InlineKeyboardButton(
                        "⏪ BACK",
                        callback_data=f"back_{int(index)+1}_{keyword}"),
                    InlineKeyboardButton(
                        "NEXT ⏩",
                        callback_data=f"next_{int(index)+1}_{keyword}")
                ])
                buttons.append([
                    InlineKeyboardButton(
                        f"📃 Pages {int(index)+2}/{data['total']}",
                        callback_data="pages")
                ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
                return

        elif query.data.startswith("back"):
            ident, index, keyword = query.data.split("_")
            try:
                data = BUTTONS[keyword]
            except KeyError:
                await query.answer(
                    "You are using this for one of my old message, please send the request again.",
                    show_alert=True)
                return

            if int(index) == 1:
                buttons = data['buttons'][int(index) - 1].copy()

                buttons.append([
                    InlineKeyboardButton(
                        "NEXT ⏩",
                        callback_data=f"next_{int(index)-1}_{keyword}")
                ])
                buttons.append([
                    InlineKeyboardButton(
                        f"📃 Pages {int(index)}/{data['total']}",
                        callback_data="pages")
                ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
                return
            else:
                buttons = data['buttons'][int(index) - 1].copy()

                buttons.append([
                    InlineKeyboardButton(
                        "⏪ BACK",
                        callback_data=f"back_{int(index)-1}_{keyword}"),
                    InlineKeyboardButton(
                        "NEXT ⏩",
                        callback_data=f"next_{int(index)-1}_{keyword}")
                ])
                buttons.append([
                    InlineKeyboardButton(
                        f"📃 Pages {int(index)}/{data['total']}",
                        callback_data="pages")
                ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
                return
        elif query.data == "about":
            buttons = [[
                InlineKeyboardButton('Update Channel',
                                     url='https://t.me/subin_works'),
                InlineKeyboardButton(
                    'Source Code',
                    url='https://github.com/subinps/Media-Search-bot')
            ]]
            await query.message.edit(
                text=
                "<b>Developer : <a href='https://t.me/subinps_bot'>SUBIN</a>\nLanguage : <code>Python3</code>\nLibrary : <a href='https://docs.pyrogram.org/'>Pyrogram asyncio</a>\nSource Code : <a href='https://github.com/subinps/Media-Search-bot'>Click here</a>\nUpdate Channel : <a href='https://t.me/subin_works'>XTZ Bots</a> </b>",
                reply_markup=InlineKeyboardMarkup(buttons),
                disable_web_page_preview=True)

        elif query.data.startswith("subinps"):
            ident, file_id = query.data.split("#")
            filedetails = await get_file_details(file_id)
            for files in filedetails:
                title = files.file_name
                size = files.file_size
                f_caption = files.caption
                if CUSTOM_FILE_CAPTION:
                    try:
                        f_caption = CUSTOM_FILE_CAPTION.format(
                            file_name=title,
                            file_size=size,
                            file_caption=f_caption)
                    except Exception as e:
                        print(e)
                        f_caption = f_caption
                if f_caption is None:
                    f_caption = f"{files.file_name}"
                buttons = [[
                    InlineKeyboardButton('More Bots',
                                         url='https://t.me/subin_works/122'),
                    InlineKeyboardButton('Update Channel',
                                         url='https://t.me/subin_works')
                ]]

                await query.answer()
                await client.send_cached_media(
                    chat_id=query.from_user.id,
                    file_id=file_id,
                    caption=f_caption,
                    reply_markup=InlineKeyboardMarkup(buttons))
        elif query.data.startswith("checksub"):
            if AUTH_CHANNEL and not await is_subscribed(client, query):
                await query.answer(
                    "I Like Your Smartness, But Don't Be Oversmart 😒",
                    show_alert=True)
                return
            ident, file_id = query.data.split("#")
            filedetails = await get_file_details(file_id)
            for files in filedetails:
                title = files.file_name
                size = files.file_size
                f_caption = files.caption
                if CUSTOM_FILE_CAPTION:
                    try:
                        f_caption = CUSTOM_FILE_CAPTION.format(
                            file_name=title,
                            file_size=size,
                            file_caption=f_caption)
                    except Exception as e:
                        print(e)
                        f_caption = f_caption
                if f_caption is None:
                    f_caption = f"{title}"
                buttons = [[
                    InlineKeyboardButton('More Bots',
                                         url='https://t.me/subin_works/122'),
                    InlineKeyboardButton('Update Channel',
                                         url='https://t.me/subin_works')
                ]]

                await query.answer()
                await client.send_cached_media(
                    chat_id=query.from_user.id,
                    file_id=file_id,
                    caption=f_caption,
                    reply_markup=InlineKeyboardMarkup(buttons))

        elif query.data == "pages":
            await query.answer()
    else:
        await query.answer("കൌതുകും ലേശം കൂടുതൽ ആണല്ലേ👀", show_alert=True)
Example #4
0
async def start(client, message: pyrogram.types.Message):

    if message.chat.type in ['group', 'supergroup']:
        buttons = [[
            InlineKeyboardButton('Developers', url='https://t.me/CrazyBotsz'),
            InlineKeyboardButton(
                'Source Code 🧾',
                url='https://github.com/CrazyBotsz/Adv-Auto-Filter-Bot-V2')
        ],
                   [
                       InlineKeyboardButton(
                           '➕ Add Me To Your Groups ➕',
                           url=f'http://t.me/{temp.U_NAME}?startgroup=true')
                   ], [InlineKeyboardButton('Help ⚙', callback_data='admin')]]

        reply_markup = InlineKeyboardMarkup(buttons)
        if not START_IMAGE_URL:
            await message.reply(script.START_TXT.format(
                (message.from_user.mention
                 if message.from_user else message.chat.title),
                temp.U_NAME,
                temp.B_NAME,
            ),
                                reply_markup=reply_markup)
        else:
            await message.reply_photo(
                photo=START_IMAGE_URL,
                caption=script.START_TXT.format(
                    (message.from_user.mention
                     if message.from_user else message.chat.title),
                    temp.U_NAME,
                    temp.B_NAME,
                ),
                reply_markup=reply_markup)
        await asyncio.sleep(
            2
        )  # 😢 https://github.com/EvamariaTG/EvaMaria/blob/master/plugins/p_ttishow.py#L17 😬 wait a bit, before checking.

        if not await db.get_chat(message.chat.id):
            total = await client.get_chat_members_count(message.chat.id)
            await client.send_message(
                LOG_CHANNEL,
                script.LOG_TEXT_G.format(message.chat.title, message.chat.id,
                                         total, "Unknown"))
            await db.add_chat(message.chat.id, message.chat.title)
        return

    if not await db.is_user_exist(message.from_user.id):
        await db.add_user(message.from_user.id, message.from_user.first_name)
        await client.send_message(
            LOG_CHANNEL,
            script.LOG_TEXT_P.format(message.from_user.id,
                                     message.from_user.mention))

    if len(message.command) != 2:

        buttons = [[
            InlineKeyboardButton('Developers', url='https://t.me/CrazyBotsz'),
            InlineKeyboardButton(
                'Source Code 🧾',
                url='https://github.com/CrazyBotsz/Adv-Auto-Filter-Bot-V2')
        ],
                   [
                       InlineKeyboardButton(
                           '➕ Add Me To Your Groups ➕',
                           url=f'http://t.me/{temp.U_NAME}?startgroup=true')
                   ], [InlineKeyboardButton('Help ⚙', callback_data='admin')]]

        reply_markup = InlineKeyboardMarkup(buttons)

        await message.reply_photo(
            photo=START_IMAGE_URL if START_IMAGE_URL else random.choice(PICS),
            caption=script.START_TXT.format(
                (message.from_user.mention
                 if message.from_user else message.chat.title),
                temp.U_NAME,
                temp.B_NAME,
            ),
            reply_markup=reply_markup)
        return

    if AUTH_CHANNEL and not await is_subscribed(client, message):
        try:
            invite_link = await client.create_chat_invite_link(
                int(AUTH_CHANNEL))
        except ChatAdminRequired:
            logger.error("Make sure Bot is admin in Forcesub channel")
            return
        btn = [[
            InlineKeyboardButton("🤖 Join Updates Channel",
                                 url=invite_link.invite_link)
        ]]

        if message.command[1] != "subscribe":
            kk, file_id = message.command[1].split("_", 1)
            pre = 'checksubp' if kk == 'filep' else 'checksub'
            btn.append([
                InlineKeyboardButton(" 🔄 Try Again",
                                     callback_data=f"{pre}#{file_id}")
            ])
        await client.send_message(
            chat_id=message.from_user.id,
            text="**Please Join My Updates Channel to use this Bot!**",
            reply_markup=InlineKeyboardMarkup(btn),
            parse_mode="markdown")
        return

    if len(message.command) == 2 and message.command[1] in [
            "subscribe", "error", "okay", "help"
    ]:

        buttons = [[
            InlineKeyboardButton('Developers', url='https://t.me/CrazyBotsz'),
            InlineKeyboardButton(
                'Source Code 🧾',
                url='https://github.com/CrazyBotsz/Adv-Auto-Filter-Bot-V2')
        ],
                   [
                       InlineKeyboardButton(
                           '➕ Add Me To Your Groups ➕',
                           url=f'http://t.me/{temp.U_NAME}?startgroup=true')
                   ], [InlineKeyboardButton('Help ⚙', callback_data='admin')]]

        reply_markup = InlineKeyboardMarkup(buttons)
        await message.reply_photo(
            photo=START_IMAGE_URL if START_IMAGE_URL else random.choice(PICS),
            caption=script.START_TXT.format(message.from_user.mention,
                                            temp.U_NAME, temp.B_NAME),
            reply_markup=reply_markup,
            parse_mode='html')
        return
    data = message.command[1]
    try:
        pre, file_id = data.split('_', 1)
    except:
        file_id = data
        pre = ""
    if data.split("-", 1)[0] == "BATCH":
        sts = await message.reply("Please wait")
        file_id = data.split("-", 1)[1]
        msgs = BATCH_FILES.get(file_id)
        if not msgs:
            file = await client.download_media(file_id)
            try:
                with open(file) as file_data:
                    msgs = json.loads(file_data.read())
            except:
                await sts.edit("FAILED")
                return await client.send_message(LOG_CHANNEL,
                                                 "UNABLE TO OPEN FILE.")
            os.remove(file)
            BATCH_FILES[file_id] = msgs
        for msg in msgs:
            title = msg.get("title")
            size = get_size(int(msg.get("size", 0)))
            f_caption = msg.get("caption", "")
            if BATCH_FILE_CAPTION:
                try:
                    f_caption = BATCH_FILE_CAPTION.format(
                        file_name='' if title is None else title,
                        file_size='' if size is None else size,
                        file_caption='' if f_caption is None else f_caption)
                except Exception as e:
                    logger.exception(e)
                    f_caption = f_caption
            if f_caption is None:
                f_caption = f"{title}"
            try:
                await client.send_cached_media(
                    chat_id=message.from_user.id,
                    file_id=msg.get("file_id"),
                    caption=f_caption,
                    protect_content=msg.get('protect', False),
                )
            except FloodWait as e:
                await asyncio.sleep(e.x)
                logger.warning(f"Floodwait of {e.x} sec.")
                await client.send_cached_media(
                    chat_id=message.from_user.id,
                    file_id=msg.get("file_id"),
                    caption=f_caption,
                    protect_content=msg.get('protect', False),
                )
            except Exception as e:
                logger.warning(e, exc_info=True)
                continue
            await asyncio.sleep(1)
        await sts.delete()
        return
    elif data.split("-", 1)[0] == "DSTORE":
        sts = await message.reply("Please wait")
        b_string = data.split("-", 1)[1]
        decoded = (
            base64.urlsafe_b64decode(b_string + "=" *
                                     (-len(b_string) % 4))).decode("ascii")
        try:
            f_msg_id, l_msg_id, f_chat_id, protect = decoded.split("_", 3)
        except:
            f_msg_id, l_msg_id, f_chat_id = decoded.split("_", 2)
            protect = "/pbatch" if PROTECT_CONTENT else "batch"
        diff = int(l_msg_id) - int(f_msg_id)
        async for msg in client.iter_messages(int(f_chat_id), int(l_msg_id),
                                              int(f_msg_id)):
            if msg.media:
                media = getattr(msg, msg.media)
                if BATCH_FILE_CAPTION:
                    try:
                        f_caption = BATCH_FILE_CAPTION.format(
                            file_name=getattr(media, 'file_name', ''),
                            file_size=getattr(media, 'file_size', ''),
                            file_caption=getattr(msg, 'caption', ''))
                    except Exception as e:
                        logger.exception(e)
                        f_caption = getattr(msg, 'caption', '')
                else:
                    media = getattr(msg, msg.media)
                    file_name = getattr(media, 'file_name', '')
                    f_caption = getattr(msg, 'caption', file_name)
                try:
                    await msg.copy(message.chat.id,
                                   caption=f_caption,
                                   protect_content=True
                                   if protect == "/pbatch" else False)
                except FloodWait as e:
                    await asyncio.sleep(e.x)
                    await msg.copy(message.chat.id,
                                   caption=f_caption,
                                   protect_content=True
                                   if protect == "/pbatch" else False)
                except Exception as e:
                    logger.exception(e)
                    continue
            elif msg.empty:
                continue
            else:
                try:
                    await msg.copy(message.chat.id,
                                   protect_content=True
                                   if protect == "/pbatch" else False)
                except FloodWait as e:
                    await asyncio.sleep(e.x)
                    await msg.copy(message.chat.id,
                                   protect_content=True
                                   if protect == "/pbatch" else False)
                except Exception as e:
                    logger.exception(e)
                    continue
            await asyncio.sleep(1)
        return await sts.delete()

    files_ = await get_file_details(file_id)
    if not files_:
        pre, file_id = ((
            base64.urlsafe_b64decode(data + "=" *
                                     (-len(data) % 4))).decode("ascii")).split(
                                         "_", 1)
        try:
            msg = await client.send_cached_media(
                chat_id=message.from_user.id,
                file_id=file_id,
                protect_content=True if pre == 'filep' else False,
            )
            filetype = msg.media
            file = getattr(msg, filetype)
            title = file.file_name
            size = get_size(file.file_size)
            f_caption = f"<code>{title}</code>"
            if CUSTOM_FILE_CAPTION:
                try:
                    f_caption = CUSTOM_FILE_CAPTION.format(
                        file_name='' if title is None else title,
                        file_size='' if size is None else size,
                        file_caption='')
                except:
                    return
            await msg.edit_caption(f_caption)
            return
        except:
            pass
        return await message.reply('No such file exist.')
    files = files_[0]
    title = files.file_name
    size = get_size(files.file_size)
    f_caption = files.caption
    if CUSTOM_FILE_CAPTION:
        try:
            f_caption = CUSTOM_FILE_CAPTION.format(
                file_name='' if title is None else title,
                file_size='' if size is None else size,
                file_caption='' if f_caption is None else f_caption)
        except Exception as e:
            logger.exception(e)
            f_caption = f_caption
    if f_caption is None:
        f_caption = f"{files.file_name}"
    await client.send_cached_media(
        chat_id=message.from_user.id,
        file_id=file_id,
        caption=f_caption,
        protect_content=True if pre == 'filep' else False,
    )