# Telegram - Twitter - Bot
# Github.com/New-dev0/TgTwitterBot
# CopyLeft AGPLv3 (C) 2020 The Authors
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from twitterbot import AUTH, api, HELP_MARKUP
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from twitterbot.funcs import simstuff

HELPBUT = [InlineKeyboardButton(text="Help Menu", callback_data="openmenu")]


@Client.on_callback_query(~filters.user(AUTH))
async def forunauth(client, query):
    text = "❌ You are Not Authorised to Use Me !"
    await query.answer(text, show_alert=True)


@Client.on_callback_query(filters.regex("^user(.*)"))
async def callie(client, query):
    match = query.matches[0].group(1)
    user = api.get_user(match)._json
    mt = "Follow"
    if user["following"]:
        mt = "UnFollow"
    un = user['screen_name']
    uli = f"https://twitter.com/{un}"
    text = simstuff(user, uli)
    await query.edit_message_text(text, disable_web_page_preview=True)
async def filter(client: Bot, message: Message):
    if re.findall("((^\/|^,|^!|^\.|^[\U0001F600-\U000E007F]).*)", message.text):
        return

    if 2 < len(message.text) < 50:    
        btn = []

        group_id = message.chat.id
        name = message.text

        filenames, links = await searchquery(group_id, name)
        if filenames and links:
            for filename, link in zip(filenames, links):
                btn.append(
                    [InlineKeyboardButton(text=f"🎬 {filename}",url=f"{link}")]
                )
        else:
            return

        if not btn:
            return

        if len(btn) > 10: 
            btns = list(split_list(btn, 10)) 
            keyword = f"{message.chat.id}-{message.message_id}"
            BUTTONS[keyword] = {
                "total" : len(btns),
                "buttons" : btns
            }
        else:
            buttons = btn
            buttons.append(
                [InlineKeyboardButton(text="⭕️ Pages 1/1 ⭕️",callback_data="pages")]
            )
            await message.reply_text(
                f""" <b>Powered By @T2Links</b>
                
<b>If U didn't get any Movie , Tag @admin with your Movie Name </b>                

<b>If Any Queries , Contact Us - @t2linkspromotion_bot</b>
                
<b>Here is the result for {message.text} 👇</b> """,
                reply_markup=InlineKeyboardMarkup(buttons)
            )
            return

        data = BUTTONS[keyword]
        buttons = data['buttons'][0].copy()

        buttons.append(
            [InlineKeyboardButton(text="NEXT ⏩",callback_data=f"next_0_{keyword}")]
        )    
        buttons.append(
            [InlineKeyboardButton(text=f"⭕️ Pages 1/{data['total']} ⭕️",callback_data="pages")]
        )

        await message.reply_text(
                f""" <b>Powered By @T2Links </b>
                
<b>If U did'nt get any Movie , Tag @admin with your Movie Name </b>           

<b>If Any Queries , Contact Us - @t2linkspromotion_bot </b>
                
<b>Here is the result for {message.text} 👇</b> """,
                reply_markup=InlineKeyboardMarkup(buttons)
            )    
async def cb_handler(client: Client, query: CallbackQuery):
    user_id = query.from_user.id
    if lel == user_id:
        if query.data == "removebg":
            await query.message.edit_text(
                "**Select required mode**ㅤㅤㅤㅤ",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(text="WITH WHITE BG",
                                             callback_data="rmbgwhite"),
                        InlineKeyboardButton(text="WITHOUT BG",
                                             callback_data="rmbgplain"),
                    ],
                    [
                        InlineKeyboardButton(text="STICKER",
                                             callback_data="rmbgsticker")
                    ],
                ]),
            )
        elif query.data == "stick":
            await query.message.edit(
                "**Select a Type**",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(text="Normal",
                                             callback_data="stkr"),
                        InlineKeyboardButton(text="Edge Curved",
                                             callback_data="cur_ved"),
                    ],
                    [
                        InlineKeyboardButton(text="Circle",
                                             callback_data="circle_sticker")
                    ],
                ]),
            )
        elif query.data == "rotate":
            await query.message.edit_text(
                "**Select the Degree**",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(text="180", callback_data="180"),
                        InlineKeyboardButton(text="90", callback_data="90"),
                    ],
                    [InlineKeyboardButton(text="270", callback_data="270")],
                ]),
            )

        elif query.data == "glitch":
            await query.message.edit_text(
                "**Select required mode**ㅤㅤㅤㅤ",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(text="NORMAL",
                                         callback_data="normalglitch"),
                    InlineKeyboardButton(text="SCAN LINES",
                                         callback_data="scanlineglitch"),
                ]]),
            )
        elif query.data == "normalglitch":
            await query.message.edit_text(
                "**Select Glitch power level**",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(text="1",
                                             callback_data="normalglitch1"),
                        InlineKeyboardButton(text="2",
                                             callback_data="normalglitch2"),
                        InlineKeyboardButton(text="3",
                                             callback_data="normalglitch3"),
                    ],
                    [
                        InlineKeyboardButton(text="4",
                                             callback_data="normalglitch4"),
                        InlineKeyboardButton(text="5",
                                             callback_data="normalglitch5"),
                    ],
                ]),
            )
        elif query.data == "scanlineglitch":
            await query.message.edit_text(
                "**Select Glitch power level**",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(text="1",
                                             callback_data="scanlineglitch1"),
                        InlineKeyboardButton(text="2",
                                             callback_data="scanlineglitch2"),
                        InlineKeyboardButton(text="3",
                                             callback_data="scanlineglitch3"),
                    ],
                    [
                        InlineKeyboardButton(text="4",
                                             callback_data="scanlineglitch4"),
                        InlineKeyboardButton(text="5",
                                             callback_data="scanlineglitch5"),
                    ],
                ]),
            )
        elif query.data == "blur":
            await query.message.edit(
                "**Select a Type**",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(text="box", callback_data="box"),
                        InlineKeyboardButton(text="normal",
                                             callback_data="normal"),
                    ],
                    [
                        InlineKeyboardButton(text="Gaussian",
                                             callback_data="gas")
                    ],
                ]),
            )
        elif query.data == "circle":
            await query.message.edit_text(
                "**Select required mode**",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(text="WITH BG",
                                         callback_data="circlewithbg"),
                    InlineKeyboardButton(text="WITHOUT BG",
                                         callback_data="circlewithoutbg"),
                ]]),
            )
        elif query.data == "border":
            await query.message.edit(
                "**Select Border**",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(text="🔴 RED 🔴",
                                             callback_data="red"),
                        InlineKeyboardButton(text="🟢 Green 🟢",
                                             callback_data="green"),
                    ],
                    [
                        InlineKeyboardButton(text="⚫ Black ⚫",
                                             callback_data="black"),
                        InlineKeyboardButton(text="🔵 Blue 🔵",
                                             callback_data="blue"),
                    ],
                ]),
            )

        elif query.data == "bright":
            await query.message.delete()
            await bright(client, query.message)

        elif query.data == "close_e":
            await query.message.delete()

        elif query.data == "mix":
            await query.message.delete()
            await mix(client, query.message)

        elif query.data == "b|w":
            await query.message.delete()
            await black_white(client, query.message)

        elif query.data == "circlewithbg":
            await query.message.delete()
            await circle_with_bg(client, query.message)

        elif query.data == "circlewithoutbg":
            await query.message.delete()
            await circle_without_bg(client, query.message)

        elif query.data == "green":
            await query.message.delete()
            await green_border(client, query.message)

        elif query.data == "blue":
            await query.message.delete()
            await blue_border(client, query.message)

        elif query.data == "red":
            await query.message.delete()
            await red_border(client, query.message)

        elif query.data == "black":
            await query.message.delete()
            await black_border(client, query.message)

        elif query.data == "circle_sticker":
            await query.message.delete()
            await round_sticker(client, query.message)

        elif query.data == "inverted":
            await query.message.delete()
            await inverted(client, query.message)

        elif query.data == "stkr":
            await query.message.delete()
            await sticker(client, query.message)

        elif query.data == "cur_ved":
            await query.message.delete()
            await edge_curved(client, query.message)

        elif query.data == "90":
            await query.message.delete()
            await rotate_90(client, query.message)

        elif query.data == "180":
            await query.message.delete()
            await rotate_180(client, query.message)

        elif query.data == "270":
            await query.message.delete()
            await rotate_270(client, query.message)

        elif query.data == "contrast":
            await query.message.delete()
            await contrast(client, query.message)

        elif query.data == "box":
            await query.message.delete()
            await box_blur(client, query.message)

        elif query.data == "gas":
            await query.message.delete()
            await g_blur(client, query.message)

        elif query.data == "normal":
            await query.message.delete()
            await normal_blur(client, query.message)

        elif query.data == "sepia":
            await query.message.delete()
            await sepia_mode(client, query.message)

        elif query.data == "pencil":
            await query.message.delete()
            await pencil(client, query.message)

        elif query.data == "cartoon":
            await query.message.delete()
            await cartoon(client, query.message)

        elif query.data == "normalglitch1":
            await query.message.delete()
            await normalglitch_1(client, query.message)

        elif query.data == "normalglitch2":
            await query.message.delete()
            await normalglitch_2(client, query.message)

        elif query.data == "normalglitch3":
            await normalglitch_3(client, query.message)

        elif query.data == "normalglitch4":
            await query.message.delete()
            await normalglitch_4(client, query.message)

        elif query.data == "normalglitch5":
            await query.message.delete()
            await normalglitch_5(client, query.message)

        elif query.data == "scanlineglitch1":
            await query.message.delete()
            await scanlineglitch_1(client, query.message)

        elif query.data == "scanlineglitch2":
            await query.message.delete()
            await scanlineglitch_2(client, query.message)

        elif query.data == "scanlineglitch3":
            await query.message.delete()
            await scanlineglitch_3(client, query.message)

        elif query.data == "scanlineglitch4":
            await query.message.delete()
            await scanlineglitch_4(client, query.message)

        elif query.data == "scanlineglitch5":
            await query.message.delete()
            await scanlineglitch_5(client, query.message)

        elif query.data == "rmbgwhite":
            await query.message.delete()
            await removebg_white(client, query.message)

        elif query.data == "rmbgplain":
            await query.message.delete()
            await removebg_plain(client, query.message)

        elif query.data == "rmbgsticker":
            await removebg_sticker(client, query.message)
Exemple #4
0
async def m_cb(b, cb):
    global que
    qeue = que.get(cb.message.chat.id)
    type_ = cb.matches[0].group(1)
    chat_id = cb.message.chat.id
    m_chat = cb.message.chat

    the_data = cb.message.reply_markup.inline_keyboard[1][0].callback_data
    if type_ == 'pause':
        if (chat_id not in callsmusic.pytgcalls.active_calls) or (
                callsmusic.pytgcalls.active_calls[chat_id] == 'paused'):
            await cb.answer('Chat is not connected!', show_alert=True)
        else:
            callsmusic.pytgcalls.pause_stream(chat_id)

            await cb.answer('Music Paused!')
            await cb.message.edit(updated_stats(m_chat, qeue),
                                  reply_markup=r_ply('play'))

    elif type_ == 'play':
        if (chat_id not in callsmusic.pytgcalls.active_calls) or (
                callsmusic.pytgcalls.active_calls[chat_id] == 'playing'):
            await cb.answer('Chat is not connected!', show_alert=True)
        else:
            callsmusic.pytgcalls.resume_stream(chat_id)
            await cb.answer('Music Resumed!')
            await cb.message.edit(updated_stats(m_chat, qeue),
                                  reply_markup=r_ply('pause'))

    elif type_ == 'playlist':
        queue = que.get(cb.message.chat.id)
        if not queue:
            await cb.message.edit('Player is idle')
        temp = []
        for t in queue:
            temp.append(t)
        now_playing = temp[0][0]
        by = temp[0][1].mention(style='md')
        msg = "**Now Playing** in {}".format(cb.message.chat.title)
        msg += "\n- " + now_playing
        msg += "\n- Req by " + by
        temp.pop(0)
        if temp:
            msg += '\n\n'
            msg += '**Queue**'
            for song in temp:
                name = song[0]
                usr = song[1].mention(style='md')
                msg += f'\n- {name}'
                msg += f'\n- Req by {usr}\n'
        await cb.message.edit(msg)

    elif type_ == 'resume':
        if (chat_id not in callsmusic.pytgcalls.active_calls) or (
                callsmusic.pytgcalls.active_calls[chat_id] == 'playing'):
            await cb.answer('Chat is not connected or already playng',
                            show_alert=True)
        else:
            callsmusic.pytgcalls.resume_stream(chat_id)
            await cb.answer('Music Resumed!')
    elif type_ == 'puse':
        if (chat_id not in callsmusic.pytgcalls.active_calls) or (
                callsmusic.pytgcalls.active_calls[chat_id] == 'paused'):
            await cb.answer('Chat is not connected or already paused',
                            show_alert=True)
        else:
            callsmusic.pytgcalls.pause_stream(chat_id)

            await cb.answer('Music Paused!')
    elif type_ == 'cls':
        await cb.answer('Closed menu')
        await cb.message.delete()

    elif type_ == 'menu':
        stats = updated_stats(cb.message.chat, qeue)
        await cb.answer('Menu opened')
        marr = InlineKeyboardMarkup([[
            InlineKeyboardButton('⏹', 'leave'),
            InlineKeyboardButton('⏸', 'puse'),
            InlineKeyboardButton('▶️', 'resume'),
            InlineKeyboardButton('⏭', 'skip')
        ], [
            InlineKeyboardButton('Playlist 📖', 'playlist'),
        ], [InlineKeyboardButton("❌ Close", 'cls')]])
        await cb.message.edit(stats, reply_markup=marr)
    elif type_ == 'skip':
        if qeue:
            skip = qeue.pop(0)
        if chat_id not in callsmusic.pytgcalls.active_calls:
            await cb.answer('Chat is not connected!', show_alert=True)
        else:
            callsmusic.queues.task_done(chat_id)

            if callsmusic.queues.is_empty(chat_id):
                callsmusic.pytgcalls.leave_group_call(chat_id)

                await cb.message.edit('- No More Playlist..\n- Leaving VC!')
            else:
                callsmusic.pytgcalls.change_stream(
                    chat_id,
                    callsmusic.queues.get(chat_id)["file"])
                await cb.answer('Skipped')
                await cb.message.edit((m_chat, qeue),
                                      reply_markup=r_ply(the_data))
                await cb.message.reply_text(
                    f'- Skipped track\n- Now Playing **{qeue[0][0]}**')

    else:
        if chat_id in callsmusic.pytgcalls.active_calls:
            try:
                callsmusic.queues.clear(chat_id)
            except QueueEmpty:
                pass

            callsmusic.pytgcalls.leave_group_call(chat_id)
            await cb.message.edit('Successfully Left the Chat!')
        else:
            await cb.answer('Chat is not connected!', show_alert=True)
Exemple #5
0
async def deezer(client: Client, message_: Message):
    global que
    lel = await message_.reply("🔄 **Processing**")
    administrators = await get_administrators(message_.chat)
    chid = message_.chat.id
    usar = await USER.get_me()
    wew = usar.id
    for administrator in administrators:
        if administrator == message_.from_user.id:
            try:
                invitelink = await client.export_chat_invite_link(chid)
            except:
                await lel.edit("<b>Add me as admin of yor group first</b>", )
                return

            try:
                await USER.join_chat(invitelink)
                await lel.edit("<b>helper userbot joined your chat</b>", )

            except UserAlreadyParticipant:
                pass
            except Exception as e:
                #print(e)
                #await lel.edit(
                #    f"<b>User {user.first_name} couldn't join your group! Make sure user is not banned in group."
                #    "\n\nOr manually add @Music_op_bot to your Group and try again</b>",
                #)
                pass
    try:
        chatdetails = await USER.get_chat(chid)
        #lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            "<i> @helper Userbot not in this chat, Ask admin to send /play command for first time or add assistant manually</i>"
        )
        return
    requested_by = message_.from_user.first_name
    try:
        #chatdetails = await USER.get_chat(chid)
        lmoa = await client.get_chat_member(chid, wew)
    except:
        await lel.reply(
            "<i>Looks like helper Userbot not in this chat, Ask admin to send /play command for first time or add assistant manually</i>"
        )
        pass

    text = message_.text.split(" ", 1)
    queryy = text[1]
    res = lel
    await res.edit(f"Searching 👀👀👀 for `{queryy}` on deezer")
    try:
        arq = ARQ("https://thearq.tech")
        r = await arq.deezer(query=queryy, limit=1)
        title = r[0]["title"]
        duration = int(r[0]["duration"])
        thumbnail = r[0]["thumbnail"]
        artist = r[0]["artist"]
        url = r[0]["url"]
    except:
        await res.edit(
            "Found Literally Nothing, You Should Work On Your English!")
        is_playing = False
        return
    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton('📖 Playlist', callback_data='playlist'),
        InlineKeyboardButton('Menu ⏯ ', callback_data='menu')
    ], [InlineKeyboardButton(text="Listen On Deezer 🎬", url=f"{url}")
        ], [InlineKeyboardButton(text="❌ Close", callback_data='cls')]])
    file_path = await converter.convert(wget.download(url))
    await res.edit("Generating Thumbnail")
    await generate_cover(requested_by, title, artist, duration, thumbnail)
    if message_.chat.id in callsmusic.pytgcalls.active_calls:
        await res.edit("adding in queue")
        position = await queues.put(message_.chat.id, file=file_path)
        qeue = que.get(message_.chat.id)
        s_name = title
        r_by = message_.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await res.edit_text(f"✯𝕺𝖝𝕪✯= #️⃣ Queued at position {position}")
    else:
        await res.edit_text("✯𝕺𝖝𝕪✯=▶️ Playing.....")
        chat_id = message_.chat.id
        que[chat_id] = []
        qeue = que.get(message_.chat.id)
        s_name = title
        r_by = message_.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message_.chat.id, file_path)

    await res.delete()

    m = await client.send_photo(chat_id=message_.chat.id,
                                reply_markup=keyboard,
                                photo="final.png",
                                caption=f"Playing [{title}]({url}) Via Deezer")
    os.remove("final.png")
async def zee5_capture(bot, update):

    if update.from_user.id in Config.BANNED_USERS:
        await bot.delete_messages(chat_id=update.chat.id,
                                  message_ids=update.message_id,
                                  revoke=True)
        return

    logger.info(update.from_user.id)

    if "zee5" in update.text:
        try:
            w = update.text
            req1 = requests.get("https://useraction.zee5.com/tokennd").json()
            rgx = re.findall("([0-9]?\w+)", w)[-3:]
            li = {
                "url": "zee5vodnd.akamaized.net",
                "token": "https://gwapi.zee5.com/content/details/"
            }
            req2 = requests.get(
                "https://useraction.zee5.com/token/platform_tokens.php?platform_name=web_app"
            ).json()["token"]
            headers["X-Access-Token"] = req2
            req3 = requests.get("https://useraction.zee5.com/token").json()
            if "movies" in w:
                r1 = requests.get(li["token"] + "-".join(rgx),
                                  headers=headers,
                                  params={
                                      "translation": "en",
                                      "country": "IN"
                                  }).json()
                g1 = (r1["hls"][0].replace("drm", "hls") + req1["video_token"])
                file_name = r1["title"]
                url = "https://" + li["url"] + g1
            elif "tvshows" or "originals" in w:
                r2 = requests.get(li["token"] + "-".join(rgx),
                                  headers=headers,
                                  params={
                                      "translation": "en",
                                      "country": "IN"
                                  }).json()
                g2 = (r2["hls"][0].replace("drm", "hls"))
                if "netst" in g2:
                    file_name = r2["title"]
                    url = g2 + req3["video_token"]
                else:
                    file_name = r2["title"]
                    url = "https://" + li["url"] + g2 + req1["video_token"]

            logger.info(url)
        except:
            await update.reply_text("There's some issue with your URL ",
                                    quote=True)
            return

    else:
        await update.reply_text(
            "I can download from Zee5 links only! Use any url uploader for other links 😇",
            quote=True)
        return

    try:
        zee5_capture.url = url

        command_to_exec = [
            "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest",
            "-j", url, "--geo-bypass-country", "IN"
        ]
        process = await asyncio.create_subprocess_exec(
            *command_to_exec,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, stderr = await process.communicate()
        e_response = stderr.decode().strip()
        t_response = stdout.decode().strip()

        if e_response:
            logger.info(e_response)

        if t_response:
            x_reponse = t_response
            if "\n" in x_reponse:
                x_reponse, _ = x_reponse.split("\n")
            response_json = json.loads(x_reponse)
            save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
                "/" + str(update.from_user.id) + ".json"
            with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
                json.dump(response_json, outfile, ensure_ascii=False)
            inline_keyboard = []
            duration = None
            if "duration" in response_json:
                duration = response_json["duration"]
            if "formats" in response_json:
                for formats in response_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"])
                    cb_string_video = "{}|{}|{}".format(
                        "video", format_id, format_ext)
                    cb_string_file = "{}|{}|{}".format("file", format_id,
                                                       format_ext)
                    if format_string is not None and not "audio only" in format_string:
                        ikeyboard = [
                            InlineKeyboardButton(
                                "🎞 (" + format_string + ") " +
                                approx_file_size + " ",
                                callback_data=(
                                    cb_string_video).encode("UTF-8")),
                            InlineKeyboardButton(
                                "📁 FILE " + format_ext + " " +
                                approx_file_size + " ",
                                callback_data=(cb_string_file).encode("UTF-8"))
                        ]
                        inline_keyboard.append(ikeyboard)

            inline_keyboard.append([
                InlineKeyboardButton(
                    "✖️ CLOSE ✖️",
                    callback_data=("closeformat").encode("UTF-8"))
            ])

            reply_markup = InlineKeyboardMarkup(inline_keyboard)
            thumbnail = Config.DEF_THUMB_NAIL_VID_S
            thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
            if "thumbnail" in response_json:
                if response_json["thumbnail"] is not None:
                    thumbnail = response_json["thumbnail"]
                    thumbnail_image = response_json["thumbnail"]
            thumb_image_path = DownLoadFile(
                thumbnail_image,
                Config.DOWNLOAD_LOCATION + "/" + str(update.from_user.id) +
                ".jpg",
                Config.CHUNK_SIZE,
                None,  # bot,
                Translation.DOWNLOAD_START,
                update.message_id,
                update.chat.id)

            await bot.send_message(
                chat_id=update.chat.id,
                text=Translation.FORMAT_SELECTION.format(thumbnail),
                reply_markup=reply_markup,
                parse_mode="html",
                reply_to_message_id=update.message_id)
        else:
            await update.reply_text(
                "There's some issue with your URL 😕 Or may be DRM protected!",
                quote=True)
            return
    except:
        await update.reply_text("Couldn't download your video!", quote=True)
        logger.info('format send error')
        return
Exemple #7
0
async def cb_handler(bot, query: CallbackQuery, group=1):
    cb_data = query.data

    if cb_data == "start":
        buttons = [[
            InlineKeyboardButton('My Dev 👨‍🔬', url='https://t.me/Deeks_04_8')
        ]]

        reply_markup = InlineKeyboardMarkup(buttons)

        await query.message.edit_text(Translation.START_TEXT.format(
            query.from_user.mention),
                                      reply_markup=reply_markup,
                                      parse_mode="html",
                                      disable_web_page_preview=True)

    elif cb_data == "help":
        buttons = [[
            InlineKeyboardButton('Home ⚡', callback_data='start'),
            InlineKeyboardButton('About 🚩', callback_data='about')
        ], [InlineKeyboardButton('Close 🔐', callback_data='close')]]

        reply_markup = InlineKeyboardMarkup(buttons)

        await query.message.edit_text(Translation.HELP_TEXT,
                                      reply_markup=reply_markup,
                                      parse_mode="html",
                                      disable_web_page_preview=True)

    elif cb_data == "about":
        buttons = [[
            InlineKeyboardButton('Home ⚡', callback_data='start'),
            InlineKeyboardButton('Close 🔐', callback_data='close')
        ]]

        reply_markup = InlineKeyboardMarkup(buttons)

        await query.message.edit_text(Translation.ABOUT_TEXT,
                                      reply_markup=reply_markup,
                                      parse_mode="html",
                                      disable_web_page_preview=True)

    elif cb_data == "close":
        await query.message.delete()

    elif "btn" in cb_data:
        cb_data = cb_data.split("|")

        index_val = cb_data[0]
        user_id = cb_data[1]
        data = cb_data[2].strip()

        if int(query.from_user.id) != int(user_id):
            await query.answer("You Arent Worth To Do That!!",
                               show_alert=True)  # Lol😆
            return
        else:
            pass

        if data == "next_btn":
            index_val = int(index_val) + 1
        elif data == "back_btn":
            index_val = int(index_val) - 1

        try:
            temp_results = result[index_val].copy()
        except IndexError:
            return  # Quick Fix🏃🏃
        except Exception as e:
            print(e)
            return

        if int(index_val) == (len(result) -
                              1) or int(index_val) == 10:  # Max 10 Page
            temp_results.append([
                InlineKeyboardButton(
                    "⏪ Back",
                    callback_data=
                    f"{index_val} | {query.from_user.id} | back_btn")
            ])

        elif int(index_val) == 0:
            pass

        else:
            temp_results.append([
                InlineKeyboardButton(
                    "⏪ Back",
                    callback_data=
                    f"{index_val} | {query.from_user.id} | back_btn"),
                InlineKeyboardButton(
                    "Next ⏩",
                    callback_data=
                    f"{index_val} | {query.from_user.id} | next_btn")
            ])

        reply_markup = InlineKeyboardMarkup(temp_results)

        if index_val == 0:
            text = f"Found {(len(result)*30 - (30 - len(result [-1])))} Results For Query"
        else:
            text = f"Page `{index_val}` For Your Query....."

        time.sleep(1)  # Just A Mesure To Prevent Flood Wait🙁
        try:
            await query.message.edit(text,
                                     reply_markup=reply_markup,
                                     parse_mode="md")
        except FloodWait as f:
            await asyncio.sleep(f.x)
            await query.message.edit(text,
                                     reply_markup=reply_markup,
                                     parse_mode="md")
    async def send_flood_alert(user_id: Union[int, User]) -> None:
        user_ = await userge.bot.get_user_dict(user_id, attr_dict=True)
        buttons = InlineKeyboardMarkup([[
            InlineKeyboardButton("🚫  BAN",
                                 callback_data=f"bot_pm_ban_{user_.id}"),
            InlineKeyboardButton(
                "➖ Bot Antiflood [OFF]",
                callback_data="toggle_bot-antiflood_off",
            ),
        ]])
        found = False
        if FloodConfig.ALERT and (user_.id in FloodConfig.ALERT.keys()):
            found = True
            FloodConfig.ALERT[user_.id]["count"] += 1
            flood_count = FloodConfig.ALERT[user_.id]["count"]
        else:
            flood_count = FloodConfig.ALERT[user_.id]["count"] = 1

        flood_msg = (
            r"⚠️ <b>\\#Flood_Warning//</b>"
            "\n\n"
            f"  ID: <code>{user_.id}</code>\n"
            f"  Name: {user_.flname}\n"
            f"  👤 User: {user_.mention}"
            f"\n\n**Is spamming your bot !** ->  [ Flood rate **({flood_count})** ]\n"
            "__Quick Action__: Ignored from bot for a while.")

        if found:
            if flood_count >= FloodConfig.AUTOBAN:
                if user_.id in Config.SUDO_USERS:
                    sudo_spam = (
                        f"**Sudo User** {user_.mention}:\n  ID: {user_.id}\n\n"
                        "Is Flooding your bot !, Check `.help delsudo` to remove the user from Sudo."
                    )
                    await userge.bot.send_message(Config.LOG_CHANNEL_ID,
                                                  sudo_spam)
                else:
                    await ban_from_bot_pm(
                        user_.id,
                        f"Automated Ban for Flooding bot [exceeded flood rate of **({FloodConfig.AUTOBAN})**]",
                        log=__name__,
                    )
                    FloodConfig.USERS[user_.id].clear()
                    FloodConfig.ALERT[user_.id].clear()
                    FloodConfig.BANNED_USERS.remove(user_.id)
                return
            fa_id = FloodConfig.ALERT[user_.id].get("fa_id")
            if not fa_id:
                return
            try:
                msg_ = await userge.bot.get_messages(Config.LOG_CHANNEL_ID,
                                                     fa_id)
                if msg_.text != flood_msg:
                    await msg_.edit(flood_msg, reply_markup=buttons)
            except Exception as fa_id_err:
                LOGGER.debug(fa_id_err)
                return
        else:
            fa_msg = await userge.bot.send_message(
                Config.LOG_CHANNEL_ID,
                flood_msg,
                reply_markup=buttons,
            )
            try:
                await userge.bot.send_message(
                    Config.OWNER_ID[0],
                    f"⚠️  **[Bot Flood Warning !]({fa_msg.link})**",
                )
            except UserIsBlocked:
                await CHANNEL.log("**Unblock your bot !**")
        if FloodConfig.ALERT[user_.id].get("fa_id") is None and fa_msg:
            FloodConfig.ALERT[user_.id]["fa_id"] = fa_msg.message_id
Exemple #9
0
async def auto_filter(bot, update):
    """
    A Funtion To Handle Incoming Text And Reply With Appropriate Results
    """
    group_id = update.chat.id

    if re.findall(r"((^\/|^,|^\.|^[\U0001F600-\U000E007F]).*)", update.text):
        return

    if ("https://" or "http://") in update.text:
        return

    query = re.sub(r"[1-2]\d{3}", "",
                   update.text)  # Targetting Only 1000 - 2999 😁

    if len(query) < 2:
        return

    results = []

    global ACTIVE_CHATS
    global FIND

    configs = await db.find_chat(group_id)
    achats = ACTIVE_CHATS[str(group_id)] if ACTIVE_CHATS.get(
        str(group_id)) else await db.find_active(group_id)
    ACTIVE_CHATS[str(group_id)] = achats

    if not configs:
        return

    allow_video = configs["types"]["video"]
    allow_audio = configs["types"]["audio"]
    allow_document = configs["types"]["document"]

    max_pages = configs["configs"][
        "max_pages"]  # maximum page result of a query
    pm_file_chat = configs["configs"][
        "pm_fchat"]  # should file to be send from bot pm to user
    max_results = configs["configs"][
        "max_results"]  # maximum total result of a query
    max_per_page = configs["configs"][
        "max_per_page"]  # maximum buttom per page
    show_invite = configs["configs"][
        "show_invite_link"]  # should or not show active chat invite link

    show_invite = (False if pm_file_chat == True else show_invite
                   )  # turn show_invite to False if pm_file_chat is True

    filters = await db.get_filters(group_id, query)

    if filters:
        for filter in filters:  # iterating through each files
            file_name = filter.get("file_name")
            file_type = filter.get("file_type")
            file_link = filter.get("file_link")
            file_size = int(filter.get("file_size", "0"))

            # from B to MiB

            if file_size < 1024:
                file_size = f"[{file_size} B]"
            elif file_size < (1024**2):
                file_size = f"[{str(round(file_size/1024, 2))} KiB] "
            elif file_size < (1024**3):
                file_size = f"[{str(round(file_size/(1024**2), 2))} MiB] "
            elif file_size < (1024**4):
                file_size = f"[{str(round(file_size/(1024**3), 2))} GiB] "

            file_size = "" if file_size == ("[0 B]") else file_size

            # add emoji down below inside " " if you want..
            button_text = f"{file_size}{file_name}"

            if file_type == "video":
                if allow_video:
                    pass
                else:
                    continue

            elif file_type == "audio":
                if allow_audio:
                    pass
                else:
                    continue

            elif file_type == "document":
                if allow_document:
                    pass
                else:
                    continue

            if len(results) >= max_results:
                break

            if pm_file_chat:
                unique_id = filter.get("unique_id")
                if not FIND.get("bot_details"):
                    try:
                        bot_ = await bot.get_me()
                        FIND["bot_details"] = bot_
                    except FloodWait as e:
                        asyncio.sleep(e.x)
                        bot_ = await bot.get_me()
                        FIND["bot_details"] = bot_

                bot_ = FIND.get("bot_details")
                file_link = f"https://t.me/{bot_.username}?start={unique_id}"

            results.append([InlineKeyboardButton(button_text, url=file_link)])

    else:
        return  # return if no files found for that query

    if len(results) == 0:  # double check
        return

    else:

        result = []
        # seperating total files into chunks to make as seperate pages
        result += [
            results[i * max_per_page:(i + 1) * max_per_page]
            for i in range((len(results) + max_per_page - 1) // max_per_page)
        ]
        len_result = len(result)
        len_results = len(results)
        results = None  # Free Up Memory

        FIND[query] = {
            "results": result,
            "total_len": len_results,
            "max_pages": max_pages
        }  # TrojanzHex's Idea Of Dicts😅

        # Add next buttin if page count is not equal to 1
        if len_result != 1:
            result[0].append([
                InlineKeyboardButton("Next ⏩",
                                     callback_data=f"navigate(0|next|{query})")
            ])

        # Just A Decaration
        result[0].append([
            InlineKeyboardButton(
                f"🔰 Page 1/{len_result if len_result < max_pages else max_pages} 🔰",
                callback_data="ignore")
        ])

        # if show_invite is True Append invite link buttons
        if show_invite:

            ibuttons = []
            achatId = []
            await gen_invite_links(configs, group_id, bot, update)

            for x in achats["chats"] if isinstance(achats, dict) else achats:
                achatId.append(int(x["chat_id"])) if isinstance(
                    x, dict) else achatId.append(x)

            ACTIVE_CHATS[str(group_id)] = achatId

            for y in INVITE_LINK.get(str(group_id)):

                chat_id = int(y["chat_id"])

                if chat_id not in achatId:
                    continue

                chat_name = y["chat_name"]
                invite_link = y["invite_link"]

                if ((len(ibuttons) % 2) == 0):
                    ibuttons.append([
                        InlineKeyboardButton(f"⚜ {chat_name} ⚜",
                                             url=invite_link)
                    ])

                else:
                    ibuttons[-1].append(
                        InlineKeyboardButton(f"⚜ {chat_name} ⚜",
                                             url=invite_link))

            for x in ibuttons:
                result[0].insert(
                    0, x)  #Insert invite link buttons at first of page

            ibuttons = None  # Free Up Memory...
            achatId = None

        reply_markup = InlineKeyboardMarkup(result[0])

        try:
            await bot.send_message(
                chat_id=update.chat.id,
                text=
                f"""<i>Found {(len_results)} Results For Your Query:</i> <b>{query}</b> \n\n <b>💥open below button and click on <u> START </u>💥</b>  \n\n 👇 SUBSCRIBE 👇 \n <a href="https://t.me/FCfilmcornerfc">♕ 𝓕𝓘𝓛𝓜 𝓒𝓞𝓡𝓝𝓔𝓡 ♛</a> """,
                reply_markup=reply_markup,
                parse_mode="html",
                disable_web_page_preview=True,
                reply_to_message_id=update.message_id)

        except ButtonDataInvalid:
            print(result[0])

        except Exception as e:
            print(e)
Exemple #10
0
 def keyboard(self, back=None) -> InlineKeyboardMarkup:
     return InlineKeyboardMarkup(
         [[InlineKeyboardButton('View online 🌐', url=self.url)],
          [keyboards.back(back)]])
Exemple #11
0
 def button(self) -> InlineKeyboardButton:
     return InlineKeyboardButton(self.provider.capitalize(), url=self.url)
Exemple #12
0
 def button(self) -> InlineKeyboardButton:
     return InlineKeyboardButton(self.full_title,
                                 callback_data=f'song_{self.id}')
Exemple #13
0
async def check_progress_for_dl(aria2, gid, event, previous_message):
    # g_id = event.reply_to_message.from_user.id
    try:
        file = aria2.get_download(gid)
        complete = file.is_complete
        is_file = file.seeder
        if not complete:
            if not file.error_message:
                msg = ""
                # sometimes, this weird https://t.me/c/1220993104/392975
                # error creeps up
                # TODO: temporary workaround
                downloading_dir_name = "N/A"
                try:
                    # another derp -_-
                    # https://t.me/c/1220993104/423318
                    downloading_dir_name = str(file.name)
                except:
                    pass
                #
                if is_file is None:
                    msgg = f"Conn: {file.connections} <b>|</b> GID: <code>{gid}</code>"
                else:
                    msgg = f"P: {file.connections} | S: {file.num_seeders} <b>|</b> GID: <code>{gid}</code>"
                msg = f"\n<b>╭────────「➭💻 File Name :</b> 〘 `{downloading_dir_name}`〙"
                msg += f"\n<b>├➭🔥 Speed</b>: 〘 {file.download_speed_string()} 〙"
                msg += f"\n<b>├➭⌛ Status</b>: 〘 {file.progress_string()} <b>of</b> {file.total_length_string()} <b>"
                msg += f"\n<b>├➭💾 Total Size</b>: 〘 {file.total_length_string()} 〙"
                msg += f"\n<b>├➭⌚ ETA〘</b> {file.eta_string()} <b>|</b> {msgg} 〙"
                msg += f"\n<b>╰──「</b>☕️ @MIRRORDEV ☕️ 」 "

                # if is_file is None :
                # msg += f"\n<b>Conn:</b> {file.connections}, GID: <code>{gid}</code>"
                # else :
                # msg += f"\n<b>Info:</b>[ P : {file.connections} | S : {file.num_seeders} ], GID: <code>{gid}</code>"

                # msg += f"\nStatus: {file.status}"
                # msg += f"\nETA: {file.eta_string()}"
                # msg += f"\nGID: <code>{gid}</code>"
                inline_keyboard = []
                ikeyboard = []
                ikeyboard.append(
                    InlineKeyboardButton(
                        "❌ Cancel ❌",
                        callback_data=(f"cancel {gid}").encode("UTF-8")))
                inline_keyboard.append(ikeyboard)
                reply_markup = InlineKeyboardMarkup(inline_keyboard)
                if msg != previous_message:
                    if not file.has_failed:
                        try:
                            await event.edit(msg, reply_markup=reply_markup)
                        except FloodWait as e_e:
                            LOGGER.warning(f"Trying to sleep for {e_e}")
                            time.sleep(e_e.x)
                        except MessageNotModified as e_p:
                            LOGGER.info(e_p)
                            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                        previous_message = msg
                    else:
                        LOGGER.info(
                            f"Cancelling downloading of {file.name} may be due to slow torrent"
                        )
                        await event.edit(
                            f"Download cancelled :\n<code>{file.name}</code>\n\n #MetaDataError"
                        )
                        file.remove(force=True, files=True)
                        return False
            else:
                msg = file.error_message
                LOGGER.info(msg)
                await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                await event.edit(f"`{msg}`")
                return False
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await check_progress_for_dl(aria2, gid, event, previous_message)
        else:
            LOGGER.info(
                f"Downloaded Successfully: `{file.name} ({file.total_length_string()})` 🤒"
            )
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await event.edit(
                f"Downloaded Successfully: `{file.name} ({file.total_length_string()})` 🤒"
            )
            return True
    except aria2p.client.ClientException:
        await event.edit(
            f"Download cancelled :\n<code>{file.name} ({file.total_length_string()})</code>"
        )
    except MessageNotModified as ep:
        LOGGER.info(ep)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await check_progress_for_dl(aria2, gid, event, previous_message)
    except FloodWait as e:
        LOGGER.info(e)
        time.sleep(e.x)
    except RecursionError:
        file.remove(force=True, files=True)
        await event.edit("Download Auto Canceled :\n\n"
                         "Your Torrent/Link is Dead.".format(file.name))
        return False
    except Exception as e:
        LOGGER.info(str(e))
        if "not found" in str(e) or "'file'" in str(e):
            await event.edit(
                f"Download cancelled :\n<code>{file.name} ({file.total_length_string()})</code>"
            )
            return False
        else:
            LOGGER.info(str(e))
            await event.edit(
                "<u>error</u> :\n<code>{}</code> \n\n#error".format(str(e)))
            return False
Exemple #14
0
async def on_language_command(_, message):
    user = message.db_user
    user.reset_action()

    back = InlineKeyboardButton(user.get_message('back_button'), callback_data='main_menu')
    await message.reply_text(user.get_message('language_selection'), reply_markup=languages.create_keyboard(back))
Exemple #15
0
async def genStr(_, msg: Message):
    chat = msg.chat
    api = await bot.ask(chat.id, API_TEXT.format(msg.from_user.mention))
    if await is_cancel(msg, api.text):
        return
    try:
        check_api = int(api.text)
    except Exception:
        await msg.reply("`API_ID` is Invalid.\nPress /start to Start again.")
        return
    api_id = api.text
    hash = await bot.ask(chat.id, HASH_TEXT)
    if await is_cancel(msg, hash.text):
        return
    if not len(hash.text) >= 30:
        await msg.reply("`API_HASH` is Invalid.\nPress /start to Start again.")
        return
    api_hash = hash.text
    while True:
        number = await bot.ask(chat.id, PHONE_NUMBER_TEXT)
        if not number.text:
            continue
        if await is_cancel(msg, number.text):
            return
        phone = number.text
        confirm = await bot.ask(
            chat.id,
            f'`Is "{phone}" correct? (y/n):` \n\nSend: `y` (If Yes)\nSend: `n` (If No)'
        )
        if await is_cancel(msg, confirm.text):
            return
        if "y" in confirm.text:
            break
    try:
        client = Client("my_account", api_id=api_id, api_hash=api_hash)
    except Exception as e:
        await bot.send_message(
            chat.id, f"**ERROR:** `{str(e)}`\nPress /start to Start again.")
        return
    try:
        await client.connect()
    except ConnectionError:
        await client.disconnect()
        await client.connect()
    try:
        code = await client.send_code(phone)
        await asyncio.sleep(1)
    except FloodWait as e:
        await msg.reply(f"You have Floodwait of {e.x} Seconds")
        return
    except ApiIdInvalid:
        await msg.reply(
            "API ID and API Hash are Invalid.\n\nPress /start to Start again.")
        return
    except PhoneNumberInvalid:
        await msg.reply(
            "Your Phone Number is Invalid.\n\nPress /start to Start again.")
        return
    try:
        otp = await bot.ask(chat.id, (
            "An OTP is sent to your phone number, "
            "Please enter OTP in `1 2 3 4 5` format. __(Space between each numbers!)__ \n\n"
            "If Bot not sending OTP then try /restart and Start Task again with /start command to Bot.\n"
            "Press /cancel to Cancel."),
                            timeout=300)

    except TimeoutError:
        await msg.reply(
            "Time limit reached of 5 min.\nPress /start to Start again.")
        return
    if await is_cancel(msg, otp.text):
        return
    otp_code = otp.text
    try:
        await client.sign_in(phone,
                             code.phone_code_hash,
                             phone_code=' '.join(str(otp_code)))
    except PhoneCodeInvalid:
        await msg.reply("Invalid Code.\n\nPress /start to Start again.")
        return
    except PhoneCodeExpired:
        await msg.reply("Code is Expired.\n\nPress /start to Start again.")
        return
    except SessionPasswordNeeded:
        try:
            two_step_code = await bot.ask(
                chat.id,
                "Your account have Two-Step Verification.\nPlease enter your Password.\n\nPress /cancel to Cancel.",
                timeout=300)
        except TimeoutError:
            await msg.reply(
                "`Time limit reached of 5 min.\n\nPress /start to Start again.`"
            )
            return
        if await is_cancel(msg, two_step_code.text):
            return
        new_code = two_step_code.text
        try:
            await client.check_password(new_code)
        except Exception as e:
            await msg.reply(f"**ERROR:** `{str(e)}`")
            return
    except Exception as e:
        await bot.send_message(chat.id, f"**ERROR:** `{str(e)}`")
        return
    try:
        session_string = await client.export_session_string()
        await client.send_message(
            "me",
            f"#PYROGRAM #STRING_SESSION\n\n```{session_string}``` \n\nBy [@StringSessionGen_Bot](tg://openmessage?user_id=1472531255) \nA Bot By @Discovery_Updates"
        )
        await client.disconnect()
        text = "String Session is Successfully Generated.\nClick on Below Button."
        reply_markup = InlineKeyboardMarkup([[
            InlineKeyboardButton(text="𝚂𝚎𝚎 𝚂𝚝𝚛𝚒𝚗𝚐 𝚂𝚎𝚜𝚜𝚒𝚘𝚗 👀",
                                 url=f"tg://openmessage?user_id={chat.id}")
        ]])
        await bot.send_message(chat.id, text, reply_markup=reply_markup)
    except Exception as e:
        await bot.send_message(chat.id, f"**ERROR:** `{str(e)}`")
        return
Exemple #16
0
async def genStr(bot: Bot, msg: Message):
    chat = msg.chat
    api = await bot.ask(chat.id, API_TEXT.format(msg.from_user.mention))
    if await is_cancel(msg, api.text):
        return
    try:
        int(api.text)
    except Exception:
        await api.delete()
        await msg.reply("`API ID Invalid.`\nPress /start to create again.")
        return
    api_id = api.text
    await api.delete()
    hash = await bot.ask(chat.id, HASH_TEXT)
    if await is_cancel(msg, hash.text):
        return
    api_hash = hash.text
    await hash.delete()
    try:
        client = Client("my_account", api_id=api_id, api_hash=api_hash)
    except Exception as e:
        await bot.send_message(
            chat.id, f"**ERROR:** `{str(e)}`\nPress /start to create again.")
        return
    try:
        await client.connect()
    except ConnectionError:
        await client.disconnect()
        await client.connect()
    await msg.reply("`Successfully Connected to you Client.`")
    while True:
        number = await bot.ask(chat.id, PHONE_NUMBER_TEXT)
        if not number.text:
            continue
        if await is_cancel(msg, number.text):
            await client.disconnect()
            return
        phone = number.text
        await number.delete()
        confirm = await bot.ask(
            chat.id,
            f'`Is "{phone}" correct? (y/n):` \n\ntype: `y` (If Yes)\ntype: `n` (If No)'
        )
        if await is_cancel(msg, confirm.text):
            await client.disconnect()
            return
        if "y" in confirm.text.lower():
            await confirm.delete()
            break
    try:
        code = await client.send_code(phone)
        await asyncio.sleep(1)
    except FloodWait as e:
        await msg.reply(f"`you have floodwait of {e.x} Seconds`")
        return await bot.sleep(msg)
    except ApiIdInvalid:
        await msg.reply(
            "`Api Id and Api Hash are Invalid.`\n\nPress /start to create again."
        )
        return await bot.sleep(msg)
    except PhoneNumberInvalid:
        await msg.reply(
            "`your Phone Number is Invalid.`\n\nPress /start to create again.")
        return await bot.sleep(msg)
    try:
        otp = await bot.ask(chat.id, (
            "`An otp is sent to your phone number, "
            "Please enter otp in\n`1 2 3 4 5` format.`\n\n"
            "`If Bot not sending OTP then try` /restart `cmd and again` /start `the Bot.`\n"
            "Press /cancel to Cancel."),
                            timeout=300)
    except TimeoutError:
        await msg.reply(
            "`Time limit reached of 5 min.\nPress /start to create again.`")
        return await bot.sleep(msg)
    if await is_cancel(msg, otp.text):
        return await client.disconnect()
    otp_code = otp.text
    await otp.delete()
    try:
        await client.sign_in(phone,
                             code.phone_code_hash,
                             phone_code=' '.join(str(otp_code)))
    except PhoneCodeInvalid:
        await msg.reply("`Invalid Code.`\n\nPress /start to create again.")
        return await bot.sleep(msg)
    except PhoneCodeExpired:
        await msg.reply("`Code is Expired.`\n\nPress /start to create again.")
        return await bot.sleep(msg)
    except SessionPasswordNeeded:
        try:
            two_step_code = await bot.ask(
                chat.id,
                "`This account have two-step verification code.\nPlease enter your second factor authentication code.`\nPress /cancel to Cancel.",
                timeout=300)
        except TimeoutError:
            await msg.reply(
                "`Time limit reached of 5 min.\n\nPress /start to create again.`"
            )
            return await bot.sleep(msg)
        if await is_cancel(msg, two_step_code.text):
            return await client.disconnect()
        new_code = two_step_code.text
        await two_step_code.delete()
        try:
            await client.check_password(new_code)
        except Exception as e:
            await msg.reply(f"**ERROR:** `{str(e)}`")
            return await bot.sleep(msg)
    except Exception as e:
        await bot.send_message(chat.id, f"**ERROR:** `{str(e)}`")
        return await bot.sleep(msg)
    session_string = await client.export_session_string()
    await client.send_message(
        "me", f"#PYROGRAM #HU_STRING_SESSION\n\n```{session_string}```")

    text = "`String Session is Successfully Generated.\nClick on Button Below.`"
    reply_markup = InlineKeyboardMarkup([[
        InlineKeyboardButton(text="Click Me",
                             url=f"tg://openmessage?user_id={chat.id}")
    ]])
    await bot.send_message(chat.id, text, reply_markup=reply_markup)
    return await bot.sleep(msg)
async def zee5_execute(bot, update):

    try:
        cb_data = update.data
        tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|")

        thumb_image_path = Config.DOWNLOAD_LOCATION + \
            "/" + str(update.from_user.id) + ".jpg"

        save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
            "/" + str(update.from_user.id) + ".json"
        try:
            with open(save_ytdl_json_path, "r", encoding="utf8") as f:
                response_json = json.load(f)
        except (FileNotFoundError) as e:
            await bot.delete_messages(chat_id=update.message.chat.id,
                                      message_ids=update.message.message_id,
                                      revoke=True)
            return False

        youtube_dl_url = zee5_capture.url

        linksplit = update.message.reply_to_message.text.split("/")
        videoname = linksplit[+5]
        logger.info(videoname)

        custom_file_name = videoname + ".mp4"

        await bot.edit_message_text(text=Translation.DOWNLOAD_START,
                                    chat_id=update.message.chat.id,
                                    message_id=update.message.message_id)
        description = Translation.CUSTOM_CAPTION_UL_FILE.format(
            newname=custom_file_name)

        tmp_directory_for_each_user = Config.DOWNLOAD_LOCATION + "/" + str(
            update.from_user.id)
        if not os.path.isdir(tmp_directory_for_each_user):
            os.makedirs(tmp_directory_for_each_user)
        download_directory = tmp_directory_for_each_user + "/" + custom_file_name
        command_to_exec = []

        minus_f_format = youtube_dl_format + "+bestaudio"
        command_to_exec = [
            "youtube-dl", "-c", "--max-filesize",
            str(Config.TG_MAX_FILE_SIZE), "-f", minus_f_format,
            "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory
        ]
        command_to_exec.append("--no-warnings")
        command_to_exec.append("--geo-bypass-country")
        command_to_exec.append("IN")

        start = datetime.now()
        process = await asyncio.create_subprocess_exec(
            *command_to_exec,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, stderr = await process.communicate()
        e_response = stderr.decode().strip()
        t_response = stdout.decode().strip()

        if os.path.isfile(download_directory):
            logger.info("no issues")
        else:
            logger.info("issues found, passing to sub process")
            command_to_exec.clear()
            minus_f_format = youtube_dl_format
            command_to_exec = [
                "youtube-dl", "-c", "--max-filesize",
                str(Config.TG_MAX_FILE_SIZE), "-f", minus_f_format,
                "--hls-prefer-ffmpeg", youtube_dl_url, "-o", download_directory
            ]
            command_to_exec.append("--no-warnings")
            command_to_exec.append("--geo-bypass-country")
            command_to_exec.append("IN")

            start = datetime.now()
            process = await asyncio.create_subprocess_exec(
                *command_to_exec,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            stdout, stderr = await process.communicate()
            e_response = stderr.decode().strip()
            t_response = stdout.decode().strip()

        ad_string_to_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."
        if e_response and ad_string_to_replace in e_response:
            error_message = e_response.replace(ad_string_to_replace, "")
            await bot.edit_message_text(chat_id=update.message.chat.id,
                                        message_id=update.message.message_id,
                                        text=error_message)
            return False
        if t_response:
            os.remove(save_ytdl_json_path)
            end_one = datetime.now()
            time_taken_for_download = (end_one - start).seconds
            file_size = Config.TG_MAX_FILE_SIZE + 1
            try:
                file_size = os.stat(download_directory).st_size
            except FileNotFoundError as exc:
                download_directory = os.path.splitext(
                    download_directory)[0] + "." + "mp4"
                file_size = os.stat(download_directory).st_size
            if file_size > Config.TG_MAX_FILE_SIZE:
                await bot.edit_message_text(
                    chat_id=update.message.chat.id,
                    text=Translation.RCHD_TG_API_LIMIT.format(
                        time_taken_for_download, humanbytes(file_size)),
                    message_id=update.message.message_id)
            else:
                await bot.edit_message_text(
                    text=Translation.UPLOAD_START,
                    chat_id=update.message.chat.id,
                    message_id=update.message.message_id)

                # get the correct width, height, and duration for videos greater than 10MB
                width = 0
                height = 0
                duration = 0
                if tg_send_type != "file":
                    metadata = extractMetadata(
                        createParser(download_directory))
                    if metadata is not None:
                        if metadata.has("duration"):
                            duration = metadata.get('duration').seconds
                # get the correct width, height, and duration for videos greater than 10MB

                if not os.path.exists(thumb_image_path):
                    mes = await thumb(update.from_user.id)
                    if mes != None:
                        m = await bot.get_messages(update.chat.id, mes.msg_id)
                        await m.download(file_name=thumb_image_path)
                        thumb_image_path = thumb_image_path
                    else:
                        try:
                            thumb_image_path = await take_screen_shot(
                                download_directory,
                                os.path.dirname(download_directory),
                                random.randint(0, duration - 1))
                        except:
                            thumb_image_path = None
                            pass
                else:
                    width = 0
                    height = 0
                    metadata = extractMetadata(createParser(thumb_image_path))
                    if metadata.has("width"):
                        width = metadata.get("width")
                    if metadata.has("height"):
                        height = metadata.get("height")
                    if tg_send_type == "vm":
                        height = width
                    Image.open(thumb_image_path).convert("RGB").save(
                        thumb_image_path)
                    img = Image.open(thumb_image_path)
                    img.thumbnail((90, 90))
                    if tg_send_type == "file":
                        img.resize((320, height))
                    else:
                        img.resize((90, height))
                    img.save(thumb_image_path, "JPEG")

                start_time = time.time()

                if tg_send_type == "file":
                    await bot.send_document(
                        chat_id=update.message.chat.id,
                        document=download_directory,
                        thumb=thumb_image_path,
                        caption=description,
                        parse_mode="HTML",
                        # reply_markup=reply_markup,
                        reply_to_message_id=update.message.reply_to_message.
                        message_id,
                        progress=progress_for_pyrogram,
                        progress_args=(Translation.UPLOAD_START,
                                       update.message, start_time))
                elif tg_send_type == "video":
                    await bot.send_video(
                        chat_id=update.message.chat.id,
                        video=download_directory,
                        caption=description,
                        parse_mode="HTML",
                        duration=duration,
                        width=width,
                        height=height,
                        supports_streaming=True,
                        # reply_markup=reply_markup,
                        thumb=thumb_image_path,
                        reply_to_message_id=update.message.reply_to_message.
                        message_id,
                        progress=progress_for_pyrogram,
                        progress_args=(Translation.UPLOAD_START,
                                       update.message, start_time))
                else:
                    logger.info("Did this happen? :\\")

                try:
                    shutil.rmtree(tmp_directory_for_each_user)
                except:
                    pass
                try:
                    os.remove(thumb_image_path)
                except:
                    pass

                await bot.edit_message_text(
                    text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG_WITH_TS,
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(text="Support Channel",
                                             url="https://t.me/Mai_bOTs")
                    ]]),
                    chat_id=update.message.chat.id,
                    message_id=update.message.message_id,
                    disable_web_page_preview=True)
    except:
        await update.reply_text("Couldn't download your video!", quote=True)
        logger.info('error in process')
async def echo(bot, update):
    if update.from_user.id in Config.BANNED_USERS:
        await update.reply_text("Siz B A N olgansiz 🤣🤣🤣🤣")
        return
    TRChatBase(update.from_user.id, update.text, "/echo")
    update_channel = Config.UPDATE_CHANNEL
    if update_channel:
        try:
            user = await bot.get_chat_member(update_channel, update.chat.id)
            if user.status == "kicked":
                await update.reply_text(
                    "🤭 Kechirasiz siz Ban oldingiz. **B A N N E D 🤣🤣🤣**\nIltimos Kanallarimizga obuna bo'ling: @InfoTeleUz @Bot_Owners"
                )
                return
        except UserNotParticipant:
            #await update.reply_text(f"Join @{update_channel} To Use Me")
            await update.reply_text(
                text=
                "**Iltimos Kanalimizga Obuna Bo'ling. 😎 🤭**\n**Join My Updates Channel to use ME 😎 🤭**",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(text="Join My Updates Channel",
                                         url=f"https://t.me/{update_channel}")
                ]]))
            return
        except Exception:
            await update.reply_text("Something Wrong. Contact my Support Group"
                                    )
            return
    logger.info(update.from_user)
    url = update.text
    youtube_dl_username = None
    youtube_dl_password = None
    file_name = None
    if "|" in url:
        url_parts = url.split("|")
        if len(url_parts) == 2:
            url = url_parts[0]
            file_name = url_parts[1]
        elif len(url_parts) == 4:
            url = url_parts[0]
            file_name = url_parts[1]
            youtube_dl_username = url_parts[2]
            youtube_dl_password = url_parts[3]
        else:
            for entity in update.entities:
                if entity.type == "text_link":
                    url = entity.url
                elif entity.type == "url":
                    o = entity.offset
                    l = entity.length
                    url = url[o:o + l]
        if url is not None:
            url = url.strip()
        if file_name is not None:
            file_name = file_name.strip()
        # https://stackoverflow.com/a/761825/4723940
        if youtube_dl_username is not None:
            youtube_dl_username = youtube_dl_username.strip()
        if youtube_dl_password is not None:
            youtube_dl_password = youtube_dl_password.strip()
        logger.info(url)
        logger.info(file_name)
    else:
        for entity in update.entities:
            if entity.type == "text_link":
                url = entity.url
            elif entity.type == "url":
                o = entity.offset
                l = entity.length
                url = url[o:o + l]
    if Config.HTTP_PROXY != "":
        command_to_exec = [
            "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest",
            "-j", url, "--proxy", Config.HTTP_PROXY
        ]
    else:
        command_to_exec = [
            "youtube-dl", "--no-warnings", "--youtube-skip-dash-manifest",
            "-j", url
        ]
    if youtube_dl_username is not None:
        command_to_exec.append("--username")
        command_to_exec.append(youtube_dl_username)
    if youtube_dl_password is not None:
        command_to_exec.append("--password")
        command_to_exec.append(youtube_dl_password)
    # 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 and "nonnumeric port" not in 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.",
            "")
        if "This video is only available for registered users." in error_message:
            error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.NO_VOID_FORMAT_FOUND.format(
                                   str(error_message)),
                               reply_to_message_id=update.message_id,
                               parse_mode="html",
                               disable_web_page_preview=True)
        return False
    if t_response:
        # logger.info(t_response)
        x_reponse = t_response
        if "\n" in x_reponse:
            x_reponse, _ = x_reponse.split("\n")
        response_json = json.loads(x_reponse)
        save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
            "/" + str(update.from_user.id) + ".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 = []
        duration = None
        if "duration" in response_json:
            duration = response_json["duration"]
        if "formats" in response_json:
            for formats in response_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"])
                cb_string_video = "{}|{}|{}".format("video", format_id,
                                                    format_ext)
                cb_string_file = "{}|{}|{}".format("file", format_id,
                                                   format_ext)
                if format_string is not None and not "audio only" in format_string:
                    ikeyboard = [
                        InlineKeyboardButton(
                            "S " + format_string + " video " +
                            approx_file_size + " ",
                            callback_data=(cb_string_video).encode("UTF-8")),
                        InlineKeyboardButton(
                            "D " + format_ext + " " + approx_file_size + " ",
                            callback_data=(cb_string_file).encode("UTF-8"))
                    ]
                    """if duration is not None:
                        cb_string_video_message = "{}|{}|{}".format(
                            "vm", format_id, format_ext)
                        ikeyboard.append(
                            InlineKeyboardButton(
                                "VM",
                                callback_data=(
                                    cb_string_video_message).encode("UTF-8")
                            )
                        )"""
                else:
                    # special weird case :\
                    ikeyboard = [
                        InlineKeyboardButton(
                            "SVideo [" + "] ( " + approx_file_size + " )",
                            callback_data=(cb_string_video).encode("UTF-8")),
                        InlineKeyboardButton(
                            "DFile [" + "] ( " + approx_file_size + " )",
                            callback_data=(cb_string_file).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([
                    InlineKeyboardButton(
                        "MP3 " + "(" + "64 kbps" + ")",
                        callback_data=cb_string_64.encode("UTF-8")),
                    InlineKeyboardButton(
                        "MP3 " + "(" + "128 kbps" + ")",
                        callback_data=cb_string_128.encode("UTF-8"))
                ])
                inline_keyboard.append([
                    InlineKeyboardButton(
                        "MP3 " + "(" + "320 kbps" + ")",
                        callback_data=cb_string.encode("UTF-8"))
                ])
        else:
            format_id = response_json["format_id"]
            format_ext = response_json["ext"]
            cb_string_file = "{}|{}|{}".format("file", format_id, format_ext)
            cb_string_video = "{}|{}|{}".format("video", format_id, format_ext)
            inline_keyboard.append([
                InlineKeyboardButton(
                    "SVideo", callback_data=(cb_string_video).encode("UTF-8")),
                InlineKeyboardButton(
                    "DFile", callback_data=(cb_string_file).encode("UTF-8"))
            ])
            cb_string_file = "{}={}={}".format("file", format_id, format_ext)
            cb_string_video = "{}={}={}".format("video", format_id, format_ext)
            inline_keyboard.append([
                InlineKeyboardButton(
                    "video", callback_data=(cb_string_video).encode("UTF-8")),
                InlineKeyboardButton(
                    "file", callback_data=(cb_string_file).encode("UTF-8"))
            ])
        reply_markup = InlineKeyboardMarkup(inline_keyboard)
        # logger.info(reply_markup)
        thumbnail = Config.DEF_THUMB_NAIL_VID_S
        thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
        if "thumbnail" in response_json:
            if response_json["thumbnail"] is not None:
                thumbnail = response_json["thumbnail"]
                thumbnail_image = response_json["thumbnail"]
        thumb_image_path = DownLoadFile(
            thumbnail_image,
            Config.DOWNLOAD_LOCATION + "/" + str(update.from_user.id) +
            ".webp",
            Config.CHUNK_SIZE,
            None,  # bot,
            Translation.DOWNLOAD_START,
            update.message_id,
            update.chat.id)
        if os.path.exists(thumb_image_path):
            im = Image.open(thumb_image_path).convert("RGB")
            im.save(thumb_image_path.replace(".webp", ".jpg"), "jpeg")
        else:
            thumb_image_path = None
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.FORMAT_SELECTION.format(thumbnail) + "\n" +
            Translation.SET_CUSTOM_USERNAME_PASSWORD,
            reply_markup=reply_markup,
            parse_mode="html",
            reply_to_message_id=update.message_id)
    else:
        # fallback for nonnumeric port a.k.a seedbox.io
        inline_keyboard = []
        cb_string_file = "{}={}={}".format("file", "LFO", "NONE")
        cb_string_video = "{}={}={}".format("video", "OFL", "ENON")
        inline_keyboard.append([
            InlineKeyboardButton(
                "SVideo", callback_data=(cb_string_video).encode("UTF-8")),
            InlineKeyboardButton(
                "DFile", callback_data=(cb_string_file).encode("UTF-8"))
        ])
        reply_markup = InlineKeyboardMarkup(inline_keyboard)
        await bot.send_message(chat_id=update.chat.id,
                               text=Translation.FORMAT_SELECTION.format(""),
                               reply_markup=reply_markup,
                               parse_mode="html",
                               reply_to_message_id=update.message_id)
Exemple #19
0
async def auto_filter(bot, update):

    group_id = update.chat.id

    if re.findall("((^\/|^,|^\.|^[\U0001F600-\U000E007F]).*)", update.text):
        return

    query = update.text

    if len(query) < 3:
        return

    results = []

    conn_hist = await db.find_connections(group_id)

    if conn_hist:  # TODO: Better Way!? 😕
        channel1 = int(conn_hist["channel_ids"]["channel1"]
                       ) if conn_hist["channel_ids"]["channel1"] else None
        channel2 = int(conn_hist["channel_ids"]["channel2"]
                       ) if conn_hist["channel_ids"]["channel2"] else None
        channel3 = int(conn_hist["channel_ids"]["channel3"]
                       ) if conn_hist["channel_ids"]["channel3"] else None
        channels = [channel1, channel2, channel3]
    else:
        return

    for channel in channels:
        if channel == None:
            continue

        async for msgs in bot.USER.search_messages(chat_id=channel,
                                                   query=query,
                                                   filter="document",
                                                   limit=150):

            if msgs.video:
                name = msgs.video.file_name
            elif msgs.document:
                name = msgs.document.file_name
            elif msgs.audio:
                name = msgs.audio.file_name
            else:
                name = None

            link = msgs.link

            if name is not None:
                results.append([InlineKeyboardButton(name, url=link)])

        async for msgs in bot.USER.search_messages(chat_id=channel,
                                                   query=query,
                                                   filter="video",
                                                   limit=150):

            if msgs.video:
                name = msgs.video.file_name
            elif msgs.document:
                name = msgs.document.file_name
            elif msgs.audio:
                name = msgs.audio.file_name
            else:
                name = None

            link = msgs.link

            if name is not None:
                results.append([InlineKeyboardButton(name, url=link)])

    if len(results) == 0:
        # await bot.send_message(
        #     chat_id = update.chat.id,
        #     text=f"Couldn't Find A Matching Result",
        #     reply_to_message_id=update.message_id
        # )
        return

    else:
        global result
        result = []
        result += [
            results[i * 30:(i + 1) * 30]
            for i in range((len(results) + 30 - 1) // 30)
        ]

        if len(results) > 30:
            result[0].append([
                InlineKeyboardButton(
                    "Next ⏩",
                    callback_data=f"0 | {update.from_user.id} | next_btn")
            ])

        reply_markup = InlineKeyboardMarkup(result[0])

        await bot.send_message(
            chat_id=update.chat.id,
            text=
            f"Found {(len(results))} Results For Query: <code>{query}</code>",
            reply_markup=reply_markup,
            parse_mode="html",
            reply_to_message_id=update.message_id)
async def executor(client, message):
    try:
        cmd = message.text.split(" ", maxsplit=1)[1]
    except IndexError:
        return await message.delete()
    t1 = time()
    old_stderr = sys.stderr
    old_stdout = sys.stdout
    redirected_output = sys.stdout = StringIO()
    redirected_error = sys.stderr = StringIO()
    stdout, stderr, exc = None, None, None
    try:
        await aexec(cmd, client, message)
    except Exception:
        exc = traceback.format_exc()
    stdout = redirected_output.getvalue()
    stderr = redirected_error.getvalue()
    sys.stdout = old_stdout
    sys.stderr = old_stderr
    evaluation = ""
    if exc:
        evaluation = exc
    elif stderr:
        evaluation = stderr
    elif stdout:
        evaluation = stdout
    else:
        evaluation = "Success"
    final_output = f"**OUTPUT**:\n```{evaluation.strip()}```"
    if len(final_output) > 4096:
        filename = "output.txt"
        with open(filename, "w+", encoding="utf8") as out_file:
            out_file.write(str(evaluation.strip()))
        t2 = time()
        keyboard = InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        text="⏳",
                        callback_data=f"runtime {t2-t1} Seconds",
                    )
                ]
            ]
        )
        await message.reply_document(
            document=filename,
            caption=f"**INPUT:**\n`{cmd[0:980]}`\n\n**OUTPUT:**\n`Attached Document`",
            quote=False,
            reply_markup=keyboard,
        )
        await message.delete()
        os.remove(filename)
    else:
        t2 = time()
        keyboard = InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        text="⏳",
                        callback_data=f"runtime {round(t2-t1, 3)} Seconds",
                    )
                ]
            ]
        )
        await eor(message, text=final_output, reply_markup=keyboard)
Exemple #21
0
async def start(bot, update):
    
    try:
        file_uid = update.command[1]
    except IndexError:
        file_uid = False
    
    if file_uid:
        file_id, file_type = await db.get_file(file_uid)
        
        if (file_id or file_type) == None:
            return
        
        if file_type == "document":
        
            await bot.send_document(
                chat_id=update.chat.id,
                document = file_id,
                caption = '',
                reply_to_message_id=update.message_id,
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton
                                (
                                    'Developers', url="https://t.me/CrazyBotsz"
                                )
                        ]
                    ]
                )
            )

        elif file_type == "video":
        
            await update.reply_video(
                file_id,
                quote=True,
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton
                                (
                                    'My Dev 👨‍🔬', url="https://t.me/CrazyBotsz"
                                )
                        ]
                    ]
                )
            )
            
        elif file_type == "audio":
        
            await update.reply_audio(
                file_id,
                quote=True,
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton
                                (
                                    'My Dev 👨‍🔬', url="https://t.me/CrazyBotsz"
                                )
                        ]
                    ]
                )
            )

        else:
            print(file_type)
        
        return

    buttons = [[
        InlineKeyboardButton('Developers', url='https://t.me/CrazyBotsz'),
        InlineKeyboardButton('Source Code 🧾', url ='https://github.com/AlbertEinsteinTG/Adv-Auto-Filter-Bot-V2')
    ],[
        InlineKeyboardButton('Support 🛠', url='https://t.me/CrazyBotszGrp')
    ],[
        InlineKeyboardButton('Help ⚙', callback_data="help")
    ]]
    
    reply_markup = InlineKeyboardMarkup(buttons)
    
    await bot.send_message(
        chat_id=update.chat.id,
        text=script.START_MSG.format(message.from_user.mention),
        reply_markup=reply_markup,
        parse_mode="html",
        reply_to_message_id=update.message_id
    )
Exemple #22
0
async def rename_doc(bot, update):
    update_channel = Config.UPDATE_CHANNEL
    if update_channel:
        try:
            user = await bot.get_chat_member(update_channel, update.chat.id)
            if user.status == "kicked":
               await update.reply_text(" Sorry, You are **B A N N E D**")
               return
        except UserNotParticipant:
            #await update.reply_text(f"Join @{update_channel} To Use Me")
            await update.reply_text(
                text="**Please Join My Update Channel Before Using Me..**",
                reply_markup=InlineKeyboardMarkup([
                    [ InlineKeyboardButton(text="Join My Updates Channel", url=f"https://t.me/{update_channel}")]
              ])
            )
            return
    #TRChatBase(update.from_user.id, update.text, "rename")
    if (" " in update.text) and (update.reply_to_message is not None):
        cmd, file_name = update.text.split(" ", 1)
        if len(file_name) > 64:
            await update.reply_text(
                Translation.IFLONG_FILE_NAME.format(
                    alimit="64",
                    num=len(file_name)
                )
            )
            return
        description = Translation.CUSTOM_CAPTION_UL_FILE
        download_location = Config.DOWNLOAD_LOCATION + "/"
        a = await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.DOWNLOAD_START,
            reply_to_message_id=update.message_id
        )
        c_time = time.time()
        the_real_download_location = await bot.download_media(
            message=update.reply_to_message,
            file_name=download_location,
            progress=progress_for_pyrogram,
            progress_args=(
                Translation.DOWNLOAD_START,
                a,
                c_time
            )
        )
        if the_real_download_location is not None:
            try:
                await bot.edit_message_text(
                    text=Translation.SAVED_RECVD_DOC_FILE,
                    chat_id=update.chat.id,
                    message_id=a.message_id
                )
            except:
                pass
            new_file_name = download_location + file_name
            os.rename(the_real_download_location, new_file_name)
            await bot.edit_message_text(
                text=Translation.UPLOAD_START,
                chat_id=update.chat.id,
                message_id=a.message_id
                )
            logger.info(the_real_download_location)
            thumb_image_path = Config.DOWNLOAD_LOCATION + "/" + str(update.from_user.id) + ".jpg"
            if not os.path.exists(thumb_image_path):
                mes = await thumb(update.from_user.id)
                if mes != None:
                    m = await bot.get_messages(update.chat.id, mes.msg_id)
                    await m.download(file_name=thumb_image_path)
                    thumb_image_path = thumb_image_path
                else:
                    thumb_image_path = None
            else:
                width = 0
                height = 0
                metadata = extractMetadata(createParser(thumb_image_path))
                if metadata.has("width"):
                    width = metadata.get("width")
                if metadata.has("height"):
                    height = metadata.get("height")
                # resize image
                # ref: https://t.me/PyrogramChat/44663
                # https://stackoverflow.com/a/21669827/4723940
                Image.open(thumb_image_path).convert("RGB").save(thumb_image_path)
                img = Image.open(thumb_image_path)
                # https://stackoverflow.com/a/37631799/4723940
                # img.thumbnail((90, 90))
                img.resize((320, height))
                img.save(thumb_image_path, "JPEG")
                # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
            c_time = time.time()
            await bot.send_document(
                chat_id=update.chat.id,
                document=new_file_name,
                thumb=thumb_image_path,
                caption=f"<b>{file_name}</b>",
                # reply_markup=reply_markup,
                reply_to_message_id=update.reply_to_message.message_id,
                progress=progress_for_pyrogram,
                progress_args=(
                    Translation.UPLOAD_START,
                    a, 
                    c_time
                )
            )
            try:
                os.remove(new_file_name)
                os.remove(thumb_image_path)
            except:
                pass
            await bot.edit_message_text(
                text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG,
                chat_id=update.chat.id,
                message_id=a.message_id,
                disable_web_page_preview=True
           )
    else:
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.REPLY_TO_DOC_FOR_RENAME_FILE,
            reply_to_message_id=update.message_id
        )
Exemple #23
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **Processing**")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id
    usar = await USER.get_me()
    wew = usar.id
    for administrator in administrators:
        if administrator == message.from_user.id:
            try:
                invitelink = await _.export_chat_invite_link(chid)
            except:
                await lel.edit("<b>Add me as admin of yor group first</b>", )
                return

            try:
                await USER.join_chat(invitelink)
                await lel.edit("<b> userbot joined your chat</b>", )

            except UserAlreadyParticipant:
                pass
            except Exception as e:
                #print(e)
                #await lel.edit(
                #    f"<b>User {user.first_name} couldn't join your group! Make sure user is not banned in group."
                #    "\n\nOr manually add @Music_op_bot to your Group and try again</b>",
                #)
                pass
    try:
        chatdetails = await USER.get_chat(chid)
        #lmoa = await _.get_chat_member(chid,wew)
    except:
        await lel.edit(
            "<i>helper Userbot not in this chat, Ask admin to send /play command for first time or add assistant manually</i>"
        )
        return
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name
    await lel.edit("🔎 **Finding**")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    await lel.edit("🎵 **Processing**")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)
        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        await lel.edit(
            "Song not found.Try another song or maybe spell it properly.")
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton('📖 Playlist', callback_data='playlist'),
        InlineKeyboardButton('Menu ⏯ ', callback_data='menu')
    ], [InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")
        ], [InlineKeyboardButton(text="❌ Close", callback_data='cls')]])
    requested_by = message.from_user.first_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file_path = await converter.convert(youtube.download(url))

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Your requested song **queued** at position {position}!",
            reply_markup=keyboard)
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = message.chat.id
        que[chat_id] = []
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption=
            "▶️ **Playing** here the song requested by {} via OxyXmusic 😜".
            format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
    InlineKeyboardMarkup
)
from vars import var


START_MSG = """
Hi, I am **KS ANONYMOUS SENDER BOT.**\n
Just Forward me Some messages or
media and I will **Anonymize** that !!
Credits: Sahan Sachintha
"""

if var.START_MESSAGE is not None:
    START = var.START_MESSAGE
else:
    START = START_MSG


REPLY_MARKUP = InlineKeyboardMarkup([
    [InlineKeyboardButton("❤️ Support Group ❤️",
                          url="t.me/KingSahan380Group")],
    [InlineKeyboardButton("🧑‍💻 Dev 🧑‍💻",
                          url="t.me/King_Sahan")]])
    [InlineKeyboardButton("🧑‍💻 KS bot 🧑‍💻",
                          url="t.me/KingSahanBot")]])


@Client.on_message(filters.command('start') & filters.private)
async def start(client, message):
    await message.reply_text(START,
                             reply_markup=REPLY_MARKUP)
Exemple #25
0
async def jiosaavn(client: Client, message_: Message):
    global que
    lel = await message_.reply("🔄 **Processing**")
    administrators = await get_administrators(message_.chat)
    chid = message_.chat.id
    usar = await USER.get_me()
    wew = usar.id

    for administrator in administrators:
        if administrator == message_.from_user.id:
            try:
                invitelink = await client.export_chat_invite_link(chid)
            except:
                await lel.edit("<b>Add me as admin of yor group first</b>", )
                return

            try:
                await USER.join_chat(invitelink)
                await lel.edit("<b>helper userbot joined your chat</b>", )

            except UserAlreadyParticipant:
                pass
            except Exception as e:
                #print(e)
                #await lel.edit(
                #    f"<b>User {user.first_name} couldn't join your group! Make sure user is not banned in group."
                #    "\n\nOr manually add @Music_op_bot to your Group and try again</b>",
                #)
                pass
    try:
        chatdetails = await USER.get_chat(chid)
        #lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            "<i> helper Userbot not in this chat, Ask admin to send /play command for first time or add assistant manually</i>"
        )
        return
    requested_by = message_.from_user.first_name
    chat_id = message_.chat.id
    text = message_.text.split(" ", 1)
    query = text[1]
    res = lel
    await res.edit(f"Searching 👀👀👀 for `{query}` on jio saavn")
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(
                    f"https://jiosaavnapi.bhadoo.uk/result/?query={query}"
            ) as resp:
                r = json.loads(await resp.text())
        sname = r[0]["song"]
        slink = r[0]["media_url"]
        ssingers = r[0]["singers"]
        sthumb = r[0]["image"]
        sduration = int(r[0]["duration"])
    except Exception as e:
        await res.edit(
            "Found Literally Nothing!, You Should Work On Your English.")
        print(str(e))
        is_playing = False
        return
    keyboard = InlineKeyboardMarkup(
        [[
            InlineKeyboardButton('📖 Playlist', callback_data='playlist'),
            InlineKeyboardButton('Menu ⏯ ', callback_data='menu')
        ],
         [
             InlineKeyboardButton(text="Join Official Group",
                                  url='https://t.me/X_F0RCE_TEAM')
         ], [InlineKeyboardButton(text="❌ Close", callback_data='cls')]])
    file_path = await converter.convert(wget.download(slink))
    if message_.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message_.chat.id, file=file_path)
        qeue = que.get(message_.chat.id)
        s_name = sname
        r_by = message_.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await res.delete()
        m = await client.send_photo(
            chat_id=message_.chat.id,
            reply_markup=keyboard,
            photo="final.png",
            caption=f"✯𝕺𝖝𝕪✯=#️⃣ Queued at position {position}",
        )

    else:
        await res.edit_text("✯𝕺𝖝𝕪✯=▶️ Playing.....")
        chat_id = message_.chat.id
        que[chat_id] = []
        qeue = que.get(message_.chat.id)
        s_name = sname
        r_by = message_.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message_.chat.id, file_path)
    await res.edit("Generating Thumbnail.")
    await generate_cover(requested_by, sname, ssingers, sduration, sthumb)
    await res.delete()
    m = await client.send_photo(
        chat_id=message_.chat.id,
        reply_markup=keyboard,
        photo="final.png",
        caption=f"Playing {sname} Via Jiosaavn",
    )
    os.remove("final.png")
Exemple #26
0
    "custom": "🔧",
    "jutsu": "👁‍🗨",
    "ara ara": "⚠️",
}
# Database
SAVED_SETTINGS = get_collection("CONFIGS")
REPO_X = InlineQueryResultArticle(
    title="Repo",
    input_message_content=InputTextMessageContent(
        "**Here's how to setup USERGE-X** "),
    url="https://ask@eightbituwu",
    description="Setup Your Own",
    thumb_url="https://telegra.ph/file/8fa91f9c7f6f4f6b8fa6c.jpg",
    reply_markup=InlineKeyboardMarkup([[
        InlineKeyboardButton(
            "Paimon Repo",
            url="https://ask@eightbituwu",
        ),
        InlineKeyboardButton(
            "Deploy USERGE-X",
            url=("https://heroku.com/deploy?template="
                 "https://github.com/ash/MyGpack"),
        ),
    ]]),
)

media_, alive_media, media_type = None, None, None


async def _init() -> None:
    global media_, alive_media, media_type
    data = await SAVED_SETTINGS.find_one({"_id": "CURRENT_CLIENT"})
async def cb_handler(client: Bot, query: CallbackQuery):
    clicked = query.from_user.id
    typed = query.message.reply_to_message.from_user.id

    if (clicked == typed) or (clicked in AUTH_USERS):

        if query.data.startswith("next"):
            await query.answer()
            ident, index, keyword = query.data.split("_")
            data = BUTTONS[keyword]

            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"):
            await query.answer()
            ident, index, keyword = query.data.split("_")
            data = BUTTONS[keyword] 

            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 == "pages":
            await query.answer()


        elif query.data == "start_data":
            await query.answer()
            keyboard = InlineKeyboardMarkup([
                [InlineKeyboardButton("HELP", callback_data="help_data"),
                    InlineKeyboardButton("ABOUT", callback_data="about_data")],
                [InlineKeyboardButton("🔰 JOIN OUR CHANNEL 🔰", url="https://t.me/T2links")]
            ])

            await query.message.edit_text(
                script.START_MSG.format(query.from_user.mention),
                reply_markup=keyboard,
                disable_web_page_preview=True
            )


        elif query.data == "help_data":
            await query.answer()
            keyboard = InlineKeyboardMarkup([
                [InlineKeyboardButton("BACK", callback_data="start_data"),
                    InlineKeyboardButton("ABOUT", callback_data="about_data")],
                [InlineKeyboardButton("🔰 SUPPORT 🔰", url="https://t.me/Tamil_latest_films")]
            ])

            await query.message.edit_text(
                script.HELP_MSG,
                reply_markup=keyboard,
                disable_web_page_preview=True
            )


        elif query.data == "about_data":
            await query.answer()
            keyboard = InlineKeyboardMarkup([
                [InlineKeyboardButton("BACK", callback_data="help_data"),
                    InlineKeyboardButton("START", callback_data="start_data")],
                [InlineKeyboardButton("SOURCE CODE", url="https://github.com/TroJanzHEX/Auto-Filter-Bot-V2")]
            ])

            await query.message.edit_text(
                script.ABOUT_MSG,
                reply_markup=keyboard,
                disable_web_page_preview=True
            )


        elif query.data == "delallconfirm":
            await query.message.delete()
            await deleteallfilters(client, query.message)
        
        elif query.data == "delallcancel":
            await query.message.reply_to_message.delete()
            await query.message.delete()

    else:
        await query.answer("Thats not for you!!",show_alert=True)
Exemple #28
0
    async def inline_answer(_, inline_query: InlineQuery):
        results = []
        i_q = inline_query.query
        string = i_q.lower()  # All lower
        str_x = i_q.split(" ", 2)  # trigger @username Text
        str_y = i_q.split(" ", 1)  # trigger and Text
        string_split = string.split()  # All lower and Split each word
        iq_user_id = inline_query.from_user.id
        if ((iq_user_id in Config.OWNER_ID)
                or (iq_user_id in Config.SUDO_USERS or iq_user_id
                    in Config.TRUSTED_SUDO_USERS) and Config.SUDO_ENABLED):

            if string == "syntax":
                owner = [[
                    InlineKeyboardButton(text="Contact",
                                         url="https://t.me/deleteduser420")
                ]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=
                        "https://coverfiles.alphacoders.com/123/123388.png",
                        caption="Hey I solved **𝚂𝚢𝚗𝚝𝚊𝚡's ░ Σrr♢r**",
                        reply_markup=InlineKeyboardMarkup(owner),
                    ))

            if string == "age_verification_alert":
                buttons = [[
                    InlineKeyboardButton(
                        text="Yes I'm 18+",
                        callback_data="age_verification_true"),
                    InlineKeyboardButton(
                        text="No I'm Not",
                        callback_data="age_verification_false"),
                ]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=
                        "https://telegra.ph/file/87653d81b25e2960cf251.jpg",
                        caption="**ARE YOU OLD ENOUGH FOR THIS ?**",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if str_y[0] == "reddit":
                reddit_api = "https://meme-api.herokuapp.com/gimme/"
                if len(str_y) == 2:
                    subreddit_regex = r"^([a-zA-Z]+)\.$"
                    match = re.search(subreddit_regex, str_y[1])
                    if match:
                        subreddit_name = match.group(1)
                        reddit_api += f"{subreddit_name}/30"
                    else:
                        return
                else:
                    reddit_api += "30"
                try:
                    r = await get_response.json(reddit_api)
                except ValueError:
                    results.append(
                        InlineQueryResultArticle(
                            title="Reddit Api is Down !",
                            input_message_content=InputTextMessageContent(
                                "**Error Code: Status != 200**"),
                            thumb_url="https://i.imgur.com/7a7aPVa.png",
                        ))
                else:
                    if "code" in r:
                        bool_is_gallery = False
                        code = r["code"]
                        code_message = r["message"]
                        results.append(
                            InlineQueryResultArticle(
                                title=str(code),
                                input_message_content=InputTextMessageContent(
                                    f"**Error Code: {code}**\n`{code_message}`"
                                ),
                                description="Enter A Valid Subreddit Name !",
                                thumb_url="https://i.imgur.com/7a7aPVa.png",
                            ))
                    else:
                        bool_is_gallery = True
                        for post in r["memes"]:
                            if "url" in post:
                                postlink = post["postLink"]
                                subreddit = post["subreddit"]
                                title = post["title"]
                                media_url = post["url"]
                                author = post["author"]
                                upvote = post["ups"]
                                captionx = f"<b>{title}</b>\n"
                                captionx += f"`Posted by u/{author}`\n"
                                captionx += f"↕️ <code>{upvote}</code>\n"
                                thumbnail = reddit_thumb_link(post["preview"])
                                if post["spoiler"]:
                                    captionx += "Post marked as SPOILER\n"
                                if post["nsfw"]:
                                    captionx += "Post marked Adult \n"
                                buttons = [[
                                    InlineKeyboardButton(
                                        f"Source: r/{subreddit}", url=postlink)
                                ]]
                                if media_url.endswith(".gif"):
                                    results.append(
                                        InlineQueryResultAnimation(
                                            animation_url=media_url,
                                            thumb_url=thumbnail,
                                            caption=captionx,
                                            reply_markup=InlineKeyboardMarkup(
                                                buttons),
                                        ))
                                else:
                                    results.append(
                                        InlineQueryResultPhoto(
                                            photo_url=media_url,
                                            thumb_url=thumbnail,
                                            caption=captionx,
                                            reply_markup=InlineKeyboardMarkup(
                                                buttons),
                                        ))
                    await inline_query.answer(
                        results=results,
                        cache_time=1,
                        is_gallery=bool_is_gallery,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline",
                    )
                    return

            if string == "alive":
                me = await userge.get_me()
                alive_info = Bot_Alive.alive_info(me)
                buttons = Bot_Alive.alive_buttons()
                if Config.ALIVE_MEDIA_TYPE == "photo":
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=Config.NEW_ALIVE_MEDIA,
                            caption=alive_info,
                            reply_markup=buttons,
                        ))
                elif Config.ALIVE_MEDIA_TYPE == "gif":
                    results.append(
                        InlineQueryResultAnimation(
                            animation_url=Config.NEW_ALIVE_MEDIA,
                            caption=alive_info,
                            reply_markup=buttons,
                        ))

            if string == "geass":
                results.append(
                    InlineQueryResultAnimation(
                        animation_url="https://i.imgur.com/DeZHcRK.gif",
                        caption="To defeat evil, I must become a greater evil",
                    ))

            if str_y[0] == "inotes" and len(str_y) == 2:
                note_data = str_y[1].split("_", 2)
                note_data = [int(x) for x in note_data]
                if len(note_data) == 3:
                    cnote = await get_inote(note_id=note_data[0],
                                            chat_id=note_data[1],
                                            user_id=note_data[2])
                    type_ = cnote.get("type")
                    if type_ == "image":
                        results.append(
                            InlineQueryResultCachedPhoto(
                                file_id=cnote.get("file_id"),
                                caption=cnote.get("caption"),
                                reply_markup=cnote.get("buttons"),
                            ))
                    elif type_ == "media":
                        results.append(
                            InlineQueryResultCachedDocument(
                                title="Inline Note",
                                file_id=cnote.get("file_id"),
                                caption=cnote.get("caption"),
                                description=f"#{note_data[0]}",
                                reply_markup=cnote.get("buttons"),
                            ))
                    else:
                        results.append(
                            InlineQueryResultArticle(
                                title="Inline Note",
                                input_message_content=InputTextMessageContent(
                                    cnote.get("caption"),
                                    disable_web_page_preview=True),
                                description=f"#{note_data[0]}",
                                reply_markup=cnote.get("buttons"),
                            ))

            if string == "gapps":
                buttons = [
                    [
                        InlineKeyboardButton("Open GApps",
                                             callback_data="open_gapps"),
                        InlineKeyboardButton("Flame GApps",
                                             callback_data="flame_gapps"),
                    ],
                    [
                        InlineKeyboardButton("Nik GApps",
                                             callback_data="nik_gapps")
                    ],
                ]
                results.append(
                    InlineQueryResultArticle(
                        title="GApps",
                        input_message_content=InputTextMessageContent(
                            "[\u200c](https://i.imgur.com/BZBMrfn.jpg) **LATEST Android 10 arm64 GApps**"
                        ),
                        description=
                        "Get Latest GApps Download Links Directly from SF",
                        thumb_url="https://i.imgur.com/Npzw8Ph.png",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if string == "voting":
                up = "0 likes"
                down = "0 dislikes"
                anon = False
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=
                        "https://telegra.ph/file/fffb70c7b824b8c4e020b.jpg",
                        caption="Vote your opinion.",
                        reply_markup=vote_buttons(up, down, anon),
                    ))
            if string == "anon_voting":
                up = "0 likes"
                down = "0 dislikes"
                anon = True
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=
                        "https://telegra.ph/file/b23ac25afde3d6b99a591.jpg",
                        caption="Vote your opinion anonymously.",
                        reply_markup=vote_buttons(up, down, anon),
                    ))

            if len(string_split) == 2 and (string_split[0] == "ofox"):
                codename = string_split[1]
                t = TelegraphPoster(use_api=True)
                t.create_api_token("Userge-X")
                photo = "https://i.imgur.com/582uaSk.png"
                api_host = "https://api.orangefox.download/v2/device/"
                try:
                    async with get_response.get_session() as session:
                        r = await get_response.json(f"{api_host}{codename}",
                                                    session=session)
                        s = await get_response.json(
                            f"{api_host}{codename}/releases/stable/last",
                            session=session,
                        )
                except ValueError:
                    return
                info = f"📱 **Device**: {r['fullname']}\n"
                info += f"👤 **Maintainer**: {r['maintainer']['name']}\n\n"
                recovery = f"🦊 <code>{s['file_name']}</code>\n"
                recovery += f"📅 {s['date']}\n"
                recovery += f"ℹ️ **Version:** {s['version']}\n"
                recovery += f"📌 **Build Type:** {s['build_type']}\n"
                recovery += f"🔰 **Size:** {s['size_human']}\n\n"
                recovery += "📍 **Changelog:**\n"
                recovery += f"<code>{s['changelog']}</code>\n\n"
                msg = info
                msg += recovery
                notes_ = s.get("notes")
                if notes_:
                    notes = t.post(title="READ Notes", author="", text=notes_)
                    buttons = [[
                        InlineKeyboardButton("NOTES", url=notes["url"]),
                        InlineKeyboardButton("⬇️ DOWNLOAD", url=s["url"]),
                    ]]
                else:
                    buttons = [[
                        InlineKeyboardButton(text="⬇️ DOWNLOAD", url=s["url"])
                    ]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=photo,
                        thumb_url="https://i.imgur.com/o0onLYB.jpg",
                        title="Latest OFOX RECOVERY",
                        description=f"For device : {codename}",
                        caption=msg,
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if string == "repo":
                results.append(REPO_X)

            if len(str_y) == 2 and str_y[0] == "anime":
                for i in await Anime.search(str_y[1]):
                    results.append(
                        InlineQueryResultArticle(
                            title=i.get("title"),
                            input_message_content=InputTextMessageContent(
                                f'[\u200c]({i.get("image")})**{i.get("title")}**\n{i.get("release")}'
                            ),
                            description=i.get("release"),
                            thumb_url=i.get("image"),
                            reply_markup=InlineKeyboardMarkup([[
                                InlineKeyboardButton(
                                    text="⬇️  Download",
                                    callback_data=f'get_eps{i.get("key")}',
                                )
                            ]]),
                        ))
                if len(results) != 0:
                    await inline_query.answer(
                        results=results[:50],
                        cache_time=1,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline",
                    )
                    return

            if str_y[0] == "spoiler":
                if not os.path.exists(f"{Config.CACHE_PATH}/spoiler_db.json"):
                    results.append(
                        InlineQueryResultArticle(
                            title="No Spoiler Found",
                            input_message_content=InputTextMessageContent(
                                "No Spoiler Found !\nLet's Add Some 😈"),
                            description="See .help spoiler for more info",
                        ))
                else:
                    bot_name = (await userge.bot.get_me()).username
                    if len(str_y) == 2:
                        link = f"https://t.me/{bot_name}?start=spoiler_{str_y[1]}"
                        buttons = [[
                            InlineKeyboardButton(text="View Spoiler", url=link)
                        ]]
                        results.append(
                            InlineQueryResultArticle(
                                title="Spoiler",
                                input_message_content=InputTextMessageContent(
                                    "<b>Click To View The Spoiler !</b>"),
                                description="Click To Send",
                                thumb_url=
                                "https://telegra.ph/file/ee3a6439494463acd1a3a.jpg",
                                reply_markup=InlineKeyboardMarkup(buttons),
                            ))
                    else:
                        fo = open(f"{Config.CACHE_PATH}/spoiler_db.json")
                        view_db = ujson.load(fo)
                        fo.close()
                        if len(view_db) != 0:
                            for numm, spoilerr in enumerate(view_db, start=1):
                                buttons = [[
                                    InlineKeyboardButton(
                                        text="View Spoiler",
                                        url=
                                        f"https://t.me/{bot_name}?start=spoiler_{spoilerr}",
                                    )
                                ]]
                                saved_at = view_db.get(spoilerr, None)
                                savetime = (saved_at.get("savetime", None)
                                            if saved_at else None)
                                results.append(
                                    InlineQueryResultArticle(
                                        title=f"#{numm}  Spoiler",
                                        input_message_content=
                                        InputTextMessageContent(
                                            "<b>Click To View The Spoiler !</b>"
                                        ),
                                        description=f"Created At: {savetime}",
                                        thumb_url=
                                        "https://telegra.ph/file/ee3a6439494463acd1a3a.jpg",
                                        reply_markup=InlineKeyboardMarkup(
                                            buttons),
                                    ))

            if str_x[0].lower() == "op" and len(str_x) > 1:
                txt = i_q[3:]
                opinion = os.path.join(Config.CACHE_PATH, "emoji_data.txt")
                if os.path.exists(opinion):
                    with open(opinion) as fo:
                        view_data = ujson.load(fo)
                    # Uniquely identifies an inline message
                    new_id = {int(inline_query.id): [{}]}
                    view_data.update(new_id)
                else:
                    view_data = {int(inline_query.id): [{}]}
                with open(opinion, "w") as outfile:
                    ujson.dump(view_data, outfile)
                buttons = [[
                    InlineKeyboardButton(
                        "👍", callback_data=f"op_y_{inline_query.id}"),
                    InlineKeyboardButton(
                        "👎", callback_data=f"op_n_{inline_query.id}"),
                ]]
                results.append(
                    InlineQueryResultArticle(
                        title="Ask For Opinion",
                        input_message_content=InputTextMessageContent(txt),
                        description=f"Q. {txt}",
                        thumb_url="https://i.imgur.com/Zlc98qS.jpg",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if "btn_" in str_y[0] or str_y[0] == "btn":
                inline_db_path = f"{Config.CACHE_PATH}/inline_db.json"
                if os.path.exists(inline_db_path):
                    with open(inline_db_path, "r") as data_file:
                        view_db = ujson.load(data_file)
                    data_count_n = 1
                    reverse_list = list(view_db)
                    reverse_list.reverse()
                    for butt_ons in reverse_list:
                        if data_count_n > 30:
                            view_db.pop(butt_ons, None)
                        data_count_n += 1
                    with open(inline_db_path, "w") as data_file:
                        ujson.dump(view_db, data_file)
                    if str_y[0] == "btn":
                        inline_storage = list(view_db)
                    else:
                        rnd_id = (str_y[0].split("_", 1))[1]
                        inline_storage = [rnd_id]
                    if len(inline_storage) == 0:
                        return
                    for inline_content in inline_storage:
                        inline_db = view_db.get(inline_content)
                        if inline_db:
                            if (inline_db["media_valid"]
                                    and int(inline_db["media_id"]) != 0):
                                saved_msg = await userge.bot.get_messages(
                                    Config.LOG_CHANNEL_ID,
                                    int(inline_db["media_id"]))
                                media_data = get_file_id(saved_msg)
                            textx, buttonsx = pb(inline_db["msg_content"])
                            if inline_db["media_valid"]:
                                if saved_msg.photo:
                                    results.append(
                                        InlineQueryResultCachedPhoto(
                                            file_id=media_data,
                                            caption=textx,
                                            reply_markup=buttonsx,
                                        ))
                                else:
                                    results.append(
                                        InlineQueryResultCachedDocument(
                                            title=textx,
                                            file_id=media_data,
                                            caption=textx,
                                            description="Inline Button",
                                            reply_markup=buttonsx,
                                        ))
                            else:
                                results.append(
                                    InlineQueryResultArticle(
                                        title=textx,
                                        input_message_content=
                                        InputTextMessageContent(textx),
                                        reply_markup=buttonsx,
                                    ))

            if str_y[0].lower() == "stylish" and len(str_y) == 2:
                results = []
                for f_name in Styled.font_choice:
                    styled_str = font_gen(f_name, str_y[1])
                    results.append(
                        InlineQueryResultArticle(
                            title=f_name.upper(),
                            input_message_content=InputTextMessageContent(
                                f"`{styled_str}`"),
                            description=styled_str,
                        ))
                await inline_query.answer(
                    results=results,
                    cache_time=1,
                    switch_pm_text="Available Commands",
                    switch_pm_parameter="inline",
                )
                return

            if str_x[0].lower() in ["secret", "troll"] and len(str_x) == 3:
                user_name = str_x[1]
                msg = str_x[2]
                try:
                    receiver = await userge.get_users(user_name)
                except (BadRequest, IndexError):
                    return
                secret = os.path.join(Config.CACHE_PATH, "secret.json")
                key_ = rand_key()
                r_name = (("@" + receiver.username) if receiver.username else
                          f"{receiver.first_name} {receiver.last_name or ''}")
                secret_data = {
                    key_: {
                        "sender": iq_user_id,
                        "receiver": {
                            "id": receiver.id,
                            "name": r_name
                        },
                        "msg": msg,
                        "views": [],
                    }
                }
                if os.path.exists(secret):
                    with open(secret) as outfile:
                        view_data = ujson.load(outfile)
                    view_data.update(secret_data)
                else:
                    view_data = secret_data
                # Save
                with open(secret, "w") as r:
                    ujson.dump(view_data, r, indent=4)
                if str_x[0].lower() == "secret":
                    c_data = f"secret_{key_}"
                    i_m_content = f"<b>Secret Msg</b> for <b>{r_name}</b>. Only he/she can open it."
                    i_l_des = f"Send Secret Message to: {r_name}"
                    title = "Send A Secret Message"
                    thumb_img = "https://i.imgur.com/c5pZebC.png"
                else:
                    c_data = f"troll_{key_}"
                    i_m_content = f"Only <b>{r_name}</b> can't view this message. UwU"
                    i_l_des = f"Message Hidden from {r_name}"
                    title = "Troll"
                    thumb_img = "https://i.imgur.com/0vg5B0A.png"
                buttons = [[
                    InlineKeyboardButton("SHOW", callback_data=c_data)
                ]]
                results.append(
                    InlineQueryResultArticle(
                        title=title,
                        input_message_content=InputTextMessageContent(
                            i_m_content),
                        description=i_l_des,
                        thumb_url=thumb_img,
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if str_y[0].lower() == "ytdl" and len(str_y) == 2:
                link = get_yt_video_id(str_y[1].strip())
                found_ = True
                if link is None:
                    search = VideosSearch(str_y[1].strip(), limit=15)
                    resp = (search.result()).get("result")
                    if len(resp) == 0:
                        found_ = False
                    else:
                        outdata = await result_formatter(resp)
                        key_ = rand_key()
                        ytsearch_data.store_(key_, outdata)
                        buttons = InlineKeyboardMarkup([
                            [
                                InlineKeyboardButton(
                                    text=f"1 / {len(outdata)}",
                                    callback_data=f"ytdl_next_{key_}_1",
                                )
                            ],
                            [
                                InlineKeyboardButton(
                                    text="List all",
                                    callback_data=f"ytdl_listall_{key_}_1",
                                ),
                                InlineKeyboardButton(
                                    text="⬇️  Download",
                                    callback_data=
                                    f'ytdl_download_{outdata[1]["video_id"]}_0',
                                ),
                            ],
                        ])
                        caption = outdata[1]["message"]
                        photo = outdata[1]["thumb"]
                else:
                    caption, buttons = await download_button(link, body=True)
                    photo = await get_ytthumb(link)

                if found_:
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=photo,
                            title=link,
                            description="⬇️ Click to Download",
                            caption=caption,
                            reply_markup=buttons,
                        ))
                else:
                    results.append(
                        InlineQueryResultArticle(
                            title="not Found",
                            input_message_content=InputTextMessageContent(
                                f"No Results found for `{str_y[1]}`"),
                            description="INVALID",
                        ))

            MAIN_MENU = InlineQueryResultArticle(
                title="Main Menu",
                input_message_content=InputTextMessageContent(" Paimon Menu "),
                url="https://ask@eightbituwu",
                description="paimon menu",
                thumb_url="https://telegra.ph/file/8fa91f9c7f6f4f6b8fa6c.jpg",
                reply_markup=InlineKeyboardMarkup(main_menu_buttons()),
            )
            results.append(MAIN_MENU)
            if len(results) != 0:
                await inline_query.answer(
                    results=results,
                    cache_time=1,
                    switch_pm_text="Available Commands",
                    switch_pm_parameter="inline",
                )
        else:
            results.append(REPO_X)
            owner_name = (await userge.get_me()).first_name
            await inline_query.answer(
                results=results,
                cache_time=1,
                switch_pm_text=f"This bot is only for {owner_name}",
                switch_pm_parameter="start",
            )
async def photo(client: Client, message: Message):
    if not message.reply_to_message.photo:
        client.send_message(message.chat.id, "Reply to an image man!ㅤㅤ")
        return
    global lel
    lel = message.from_user.id
    try:
        await client.send_message(
            chat_id=message.chat.id,
            text="Select your required mode from below!ㅤㅤ",
            reply_markup=InlineKeyboardMarkup([
                [
                    InlineKeyboardButton(text="💡 BRIGHT",
                                         callback_data="bright"),
                    InlineKeyboardButton(text="🖼 MIXED", callback_data="mix"),
                    InlineKeyboardButton(text="🔳 B&W", callback_data="b|w"),
                ],
                [
                    InlineKeyboardButton(text="🟡 CIRCLE",
                                         callback_data="circle"),
                    InlineKeyboardButton(text="🩸 BLUR", callback_data="blur"),
                    InlineKeyboardButton(text="🌌 BORDER",
                                         callback_data="border"),
                ],
                [
                    InlineKeyboardButton(text="🎉 STICKER",
                                         callback_data="stick"),
                    InlineKeyboardButton(text="↩️ ROTATE",
                                         callback_data="rotate"),
                    InlineKeyboardButton(text="🔦 CONTRAST",
                                         callback_data="contrast"),
                ],
                [
                    InlineKeyboardButton(text="🌇 SEPIA",
                                         callback_data="sepia"),
                    InlineKeyboardButton(text="✏️ PENCIL",
                                         callback_data="pencil"),
                    InlineKeyboardButton(text="🐶 CARTOON",
                                         callback_data="cartoon"),
                ],
                [
                    InlineKeyboardButton(text="🔄 INVERT",
                                         callback_data="inverted"),
                    InlineKeyboardButton(text="🔮 GLITCH",
                                         callback_data="glitch"),
                    InlineKeyboardButton(text="✂️ REMOVE BG",
                                         callback_data="removebg"),
                ],
                [
                    InlineKeyboardButton(text="❌ CLOSE",
                                         callback_data="close_e"),
                ],
            ]),
            reply_to_message_id=message.reply_to_message.message_id,
        )
    except Exception as e:
        print("photomarkup error - " + str(e))
        if "USER_IS_BLOCKED" in str(e):
            return
        else:
            try:
                await message.reply_text("Something went wrong!", quote=True)
            except Exception:
                return
Exemple #30
0
)

updatesc = os.environ["UPDATES_CHANNEL"],
supportc = os.environ["SUPPORT_CHAT"]

BOT_TEXT = """
Hai {} , This Bot Is Under Maintenance.

You Can't Use This Bot Right Now.You Will Get a Message On This Bot's Channel If This Bot Is Ready To Work.To Know More Contact Support Group:)

ℹ️ Maintenance Bot.
"""

BOT_BUTTONS = InlineKeyboardMarkup(
        [[
        InlineKeyboardButton(text="Channel", url=f"https://telegram.me/{updatesc}"),
        InlineKeyboardButton(text="Support", url=f"https://telegram.me/{supportc}")
        ]]
    )
                
@Bot.on_message(filters.private & filters.text)
async def start(bot, update):
    text = BOT_TEXT.format(update.from_user.mention)
    reply_markup = BOT_BUTTONS
    await update.reply_text(
        text=text,
        disable_web_page_preview=True,
        reply_markup=reply_markup
    )