Exemplo n.º 1
0
    async def store(self,
                    message: Optional['_message.Message'],
                    caption: Optional[str] = '') -> int:
        """\nstore message to log channel.

        Parameters:
            message (`pyrogram.Message` | `None`):
                pass pyrogram.Message object which want to forward.

            caption (`str`, *optional*):
                Text or Cpation of the message to be sent.

        Returns:
            message_id on success or None
        """
        caption = caption or ''
        file_id = file_ref = None
        if message and message.caption:
            caption = caption + message.caption.html
        if message:
            file_id, file_ref = get_file_id_and_ref(message)
        if message and message.media and file_id and file_ref:
            if caption:
                caption = self._string.format(caption.strip())
            msg = await message.client.send_cached_media(chat_id=Config.LOG_CHANNEL_ID,
                                                         file_id=file_id,
                                                         file_ref=file_ref,
                                                         caption=caption)
            message_id = msg.message_id
        else:
            message_id = await self.log(caption)
        return message_id
Exemplo n.º 2
0
async def song_search(message: Message):
    """get songs from channel"""
    song = message.input_str
    if not song:
        await message.err("Provide a song name or artist name to search",
                          del_in=10)
        return
    search = await message.edit("ЁЯФН __Searching For__ **{}**".format(song))
    chat_id = message.chat.id
    f_id = ""
    f_ref = ""
    try:
        async for msg in userge.search_messages(-1001271479322,
                                                query=song,
                                                limit=1,
                                                filter="audio"):
            f_id, f_ref = get_file_id_and_ref(msg)
    except BadRequest:
        await search.edit(
            "Join [THIS](https://t.me/joinchat/DdR2SUvJPBouSW4QlbJU4g) channel first"
        )
        return
    if not (f_id or f_ref):
        await search.edit("тЪая╕П Song Not Found !", del_in=5)
        return
    await userge.send_audio(chat_id, f_id, f_ref)
    await search.delete()
Exemplo n.º 3
0
 async def chg_of_decision_(_, c_q: CallbackQuery):
     u_id = c_q.from_user.id
     if u_id != Config.OWNER_ID and u_id not in Config.SUDO_USERS:
         return await c_q.answer(
             "Given That It's A Stupid-Ass Decision, I've Elected To Ignore It.",
             show_alert=True,
         )
     await c_q.answer("Unsure", show_alert=False)
     msg = await userge.bot.get_messages("useless_x", 21)
     f_id, f_ref = get_file_id_and_ref(msg)
     img_text = "**ARE YOU OLD ENOUGH FOR THIS ?**"
     buttons = [[
         InlineKeyboardButton(text="Yes I'm 18+",
                              callback_data="age_verification_true"),
         InlineKeyboardButton(text="No I'm Not",
                              callback_data="age_verification_false"),
     ]]
     try:
         await c_q.edit_message_media(
             media=InputMediaPhoto(media=f_id,
                                   file_ref=f_ref,
                                   caption=img_text),
             reply_markup=InlineKeyboardMarkup(buttons),
         )
     except MessageNotModified:
         return
Exemplo n.º 4
0
 async def age_verification_true(_, c_q: CallbackQuery):
     u_id = c_q.from_user.id
     if u_id != Config.OWNER_ID and u_id not in Config.SUDO_USERS:
         return await c_q.answer(
             "Given That It's A Stupid-Ass Decision, I've Elected To Ignore It.",
             show_alert=True,
         )
     await c_q.answer("Yes I'm 18+", show_alert=False)
     msg = await userge.bot.get_messages("useless_x", 19)
     f_id, f_ref = get_file_id_and_ref(msg)
     buttons = [[
         InlineKeyboardButton(
             text="Unsure / Change of Decision ❔",
             callback_data="chg_of_decision_",
         )
     ]]
     try:
         await c_q.edit_message_media(
             media=InputMediaPhoto(
                 media=f_id,
                 file_ref=f_ref,
                 caption=
                 "Set <code>ALLOW_NSFW</code> = True in Heroku Vars to access this plugin",
             ),
             reply_markup=InlineKeyboardMarkup(buttons),
         )
     except MessageNotModified:
         return
Exemplo n.º 5
0
    async def age_verification_false(_, c_q: CallbackQuery):
        u_id = c_q.from_user.id
        if u_id not in Config.OWNER_ID and u_id not in Config.SUDO_USERS:
            return await c_q.answer(
                "Given That It's A Stupid-Ass Decision, I've Elected To Ignore It.",
                show_alert=True,
            )
        await c_q.answer("No I'm Not", show_alert=False)
        msg = await userge.bot.get_messages("useless_x", 20)
        f_id = get_file_id_and_ref(msg)[0]
        img_text = "GO AWAY KID !"

        buttons = [
            [
                InlineKeyboardButton(
                    text="Unsure / Change of Decision ❔",
                    callback_data="chg_of_decision_",
                )
            ]
        ]
        await xbot.edit_inline_media(
            c_q.inline_message_id,
            media=(await xmedia.InputMediaPhoto(file_id=f_id, caption=img_text)),
            reply_markup=InlineKeyboardMarkup(buttons),
        )
Exemplo n.º 6
0
 async def alive_callback(_, c_q: CallbackQuery):
     u_id = c_q.from_user.id
     if u_id != Config.OWNER_ID and u_id not in Config.SUDO_USERS:
         return await c_q.answer("Given That It\'s A Stupid-Ass Decision, I\'ve Elected To Ignore It.", show_alert=True)
     await c_q.answer("No I'm Not", show_alert=False)
     msg = await userge.bot.get_messages('useless_x' , 20)
     f_id, f_ref = get_file_id_and_ref(msg)
     img_text="GO AWAY KID !"
     buttons = [[
         InlineKeyboardButton(
         text="Unsure / Change of Decision ❔", 
         callback_data="chg_of_decision_"
         )
     ]]
     try:
         await c_q.edit_message_media(
             media=InputMediaPhoto(
                         media=f_id,
                         file_ref=f_ref,
                         caption=img_text
                     ),
             reply_markup=InlineKeyboardMarkup(buttons)
         )
     except MessageNotModified:
         return
Exemplo n.º 7
0
 async def _refresh_id(message: Message) -> None:
     global LOGO_ID, LOGO_REF  # pylint: disable=global-statement
     try:
         media = await ubot.get_messages(_CHAT, _MSG_ID)
     except ChannelInvalid:
         _set_data(True)
         return await _refresh_id(message)
     LOGO_ID, LOGO_REF = get_file_id_and_ref(media)
Exemplo n.º 8
0
async def _refresh_id(message: Message) -> None:
    global _LOGO_ID, _LOGO_REF, _IS_STICKER  # pylint: disable=global-statement
    try:
        media = await message.client.get_messages(_CHAT, _MSG_ID)
    except ChannelInvalid:
        _set_data(True)
        return await _refresh_id(message)
    else:
        if media.sticker:
            _IS_STICKER = True
        _LOGO_ID, _LOGO_REF = get_file_id_and_ref(media)
Exemplo n.º 9
0
 async def ytdl_callback(_, c_q: CallbackQuery):
     startTime = time()
     u_id = c_q.from_user.id
     if u_id != Config.OWNER_ID and u_id not in Config.SUDO_USERS:
         return await c_q.answer("𝘿𝙚𝙥𝙡𝙤𝙮 𝙮𝙤𝙪𝙧 𝙤𝙬𝙣 𝙐𝙎𝙀𝙍𝙂𝙀-𝙓", show_alert=True)
     choice_id = c_q.matches[0].group(2)
     callback_continue = "Downloading Video Please Wait..."
     callback_continue += f"\n\nFormat Code : {choice_id}"
     await c_q.answer(callback_continue, show_alert=True)
     upload_msg = await userge.send_message(Config.LOG_CHANNEL_ID, "Uploading...")
     yt_code = c_q.matches[0].group(1)
     yt_url = f"https://www.youtube.com/watch?v={yt_code}"
     await c_q.edit_message_caption(
         caption=f"Video is now Downloading, for progress see [LOG CHANNEL]({upload_msg.link})\n\n🔗  [<b>Link</b>]({yt_url})\n🆔  <b>Format Code</b> : {choice_id}",
         reply_markup=None,
     )
     retcode = await _tubeDl(yt_url, startTime, choice_id)
     if retcode == 0:
         _fpath = ""
         for _path in glob.glob(os.path.join(Config.DOWN_PATH, str(startTime), "*")):
             if not _path.lower().endswith((".jpg", ".png", ".webp")):
                 _fpath = _path
         if not _fpath:
             await upload_msg.err("nothing found !")
             return
         uploaded_vid = await upload(upload_msg, Path(_fpath))
     else:
         return await upload_msg.edit(str(retcode))
     refresh_vid = await userge.bot.get_messages(
         Config.LOG_CHANNEL_ID, uploaded_vid.message_id
     )
     f_id, f_ref = get_file_id_and_ref(refresh_vid)
     if hasattr(refresh_vid.video, "thumbs"):
         try:
             video_thumb = await userge.bot.download_media(
                 refresh_vid.video.thumbs[0].file_id
             )
         except TypeError:
             video_thumb = None
     else:
         video_thumb = None
     await c_q.edit_message_media(
         media=InputMediaVideo(
             media=f_id,
             file_ref=f_ref,
             thumb=video_thumb,
             caption=f"📹  <b>[{uploaded_vid.caption}]({yt_url})</b>",
             supports_streaming=True,
         ),
         reply_markup=None,
     )
     await uploaded_vid.delete()
Exemplo n.º 10
0
async def _custom_media_reply(message: Message):
    if CUSTOM_REPLIES_IDS:
        await asyncio.sleep(1)
        cus_msg = int(random.choice(CUSTOM_REPLIES_IDS))
        cus_msg = await message.client.get_messages(chat_id=CUSTOM_REPLY_CHANNEL,
                                                    message_ids=cus_msg)
        if cus_msg.service:
            await _custom_media_reply(message)
            return
        if cus_msg.media:
            file_id, file_ref = get_file_id_and_ref(cus_msg)
            try:
                if cus_msg.animation:
                    await message.client.send_animation(
                        chat_id=message.chat.id,
                        animation=file_id,
                        file_ref=file_ref,
                        unsave=True,
                        reply_to_message_id=message.message_id
                    )
                else:
                    action = None
                    if cus_msg.audio:
                        action = "upload_audio"
                    elif cus_msg.document:
                        action = "upload_document"
                    elif cus_msg.photo:
                        action = "upload_photo"
                    elif cus_msg.video:
                        action = "upload_audio"
                    elif cus_msg.voice:
                        action = "record_audio"
                    elif cus_msg.video_note:
                        action = "upload_video_note"
                    if action:
                        await message.reply_chat_action(action)
                    await asyncio.sleep(5)
                    await message.reply_cached_media(
                        file_id=file_id,
                        file_ref=file_ref
                    )
            except Exception as idk:  # pylint: disable=W0703
                LOGGER.log(f"#ERROR: `{idk}`")
                await _custom_media_reply(message)
                return
        if cus_msg.text:
            await _send_text_like_a_human(message, cus_msg.text)
Exemplo n.º 11
0
async def noformat_message(message: Message):
    reply = message.reply_to_message
    msg_text = None
    buttons = ""
    medias = get_file_id_and_ref(reply)
    if reply.text:
        msg_text = reply.text.html
    elif medias[0]:
        msg_text = reply.caption.html if reply.caption else None
    else:
        return await message.err(
            "Not Supported!, reply to a supported media type or text",
            del_in=5)

    if "-alt" in message.flags:
        lbr_ = "("
        rbr_ = ")"
    else:
        lbr_ = "["
        rbr_ = "]"

    if reply.reply_markup and not isinstance(reply.reply_markup,
                                             ReplyKeyboardRemove):
        for row in reply.reply_markup.inline_keyboard:
            firstbtn = True
            for btn in row:
                if btn.url:
                    if firstbtn:
                        buttons += f"[{btn.text}]{lbr_}buttonurl:{btn.url}{rbr_}"
                        firstbtn = False
                    else:
                        buttons += f"[{btn.text}]{lbr_}buttonurl:{btn.url}:same{rbr_}"

    if medias[0]:
        await message.delete()
        await message.client.send_cached_media(
            chat_id=message.chat.id,
            file_id=medias[0],
            file_ref=medias[1],
            caption=f"{msg_text}{buttons}",
            reply_to_message_id=reply.message_id,
            parse_mode=None,
        )
    else:
        await message.edit(f"{msg_text}{buttons}", parse_mode=None)
Exemplo n.º 12
0
async def create_button(msg: Message):
    """ Create Buttons Using Bot """
    if Config.BOT_TOKEN is None:
        await msg.err("First Create a Bot via @Botfather to Create Buttons...")
        return
    string = msg.input_raw
    replied = msg.reply_to_message
    file_id, file_ref = None, None
    if replied:
        if replied.caption:
            string = replied.caption.html
        elif replied.text:
            string = replied.text.html
        file_id, file_ref = get_file_id_and_ref(replied)
    if not string:
        await msg.err("`need an input!`")
        return
    text, markup = pb(string)
    if not text:
        await msg.err("`need text too!`")
        return
    message_id = replied.message_id if replied else None
    client = msg.client if msg.client.is_bot else msg.client.bot
    try:
        if replied and replied.media and file_id and file_ref:
            await client.send_cached_media(chat_id=msg.chat.id,
                                           file_id=file_id,
                                           file_ref=file_ref,
                                           caption=text,
                                           reply_to_message_id=message_id,
                                           reply_markup=markup)
        else:
            await client.send_message(chat_id=msg.chat.id,
                                      text=text,
                                      reply_to_message_id=message_id,
                                      reply_markup=markup)
    except UserIsBot:
        await msg.err("oops, your Bot is not here to send Msg!")
    except BadRequest:
        await msg.err("Check Syntax of Your Message for making buttons!")
    except Exception as error:
        await msg.edit(f"`Something went Wrong! 😁`\n\n**ERROR:** `{error}`")
    else:
        await msg.delete()
Exemplo n.º 13
0
 async def get_alive_():
     global MEDIA_TYPE, MEDIA_URL
     type_, media_ = await check_media_link(Config.ALIVE_MEDIA)
     if not media_:
         return
     MEDIA_TYPE = type_
     if type(media_) is str:
         limit = 1 if type_ == "url_gif" else 5
         media_info = MediaInfo.parse(media_)
         for track in media_info.tracks:
             if track.track_type == "General":
                 media_size = track.file_size / 1000000
         if media_size < limit:
             MEDIA_URL = media_
     else:
         try:
             msg = await userge.bot.get_messages(media_[0], media_[1])
             f_id, f_ref = get_file_id_and_ref(msg)
             if msg.photo:
                 MEDIA_TYPE = "tg_image"
         except BadRequest:
             return
         MEDIA_URL = [f_id, f_ref]
Exemplo n.º 14
0
async def inline_buttons(message: Message):
    await message.edit("<code>Creating an Inline Button...</code>")
    reply = message.reply_to_message
    msg_content = None
    media_valid = False
    media_id = 0
    if reply:
        media_valid = bool(get_file_id_and_ref(reply)[0])

    if message.input_str:
        msg_content = message.input_str
        if media_valid:
            media_id = (await reply.forward(Config.LOG_CHANNEL_ID)).message_id

    elif reply:
        if media_valid:
            media_id = (await reply.forward(Config.LOG_CHANNEL_ID)).message_id
            msg_content = reply.caption.html if reply.caption else None
        elif reply.text:
            msg_content = reply.text.html

    if not msg_content:
        return await message.err("Content not found", del_in=5)

    rnd_id = userge.rnd_id()
    msg_content = check_brackets(msg_content)
    InlineDB.save_msg(rnd_id, msg_content, media_valid, media_id)

    bot = await userge.bot.get_me()

    x = await userge.get_inline_bot_results(bot.username, f"btn_{rnd_id}")
    await userge.send_inline_bot_result(
        chat_id=message.chat.id,
        query_id=x.query_id,
        result_id=x.results[0].id,
    )
    await message.delete()
Exemplo n.º 15
0
    async def ytdl_download_callback(c_q: CallbackQuery):
        yt_code = c_q.matches[0].group(1)
        choice_id = c_q.matches[0].group(2)

        if str(choice_id).isdigit():
            choice_id = int(choice_id)
            if choice_id == 0:
                await xbot.edit_inline_reply_markup(
                    c_q.inline_message_id,
                    reply_markup=(await download_button(yt_code)))
                return

        else:
            choice_id = None

        startTime = time()

        downtype = c_q.matches[0].group(3)
        media_type = "Video" if downtype == "v" else "Audio"

        callback_continue = f"Downloading {media_type} Please Wait..."
        callback_continue += f"\n\nFormat Code : {choice_id or 'bestaudio/best'}"
        await c_q.answer(callback_continue, show_alert=True)
        upload_msg = await userge.send_message(Config.LOG_CHANNEL_ID,
                                               "Uploading...")

        yt_url = BASE_YT_URL + yt_code

        await xbot.edit_inline_caption(
            c_q.inline_message_id,
            caption=
            (f"{media_type} is now being ⬇️ Downloaded, for progress see:\nLog Channel:  [<b>click here</b>]({upload_msg.link})"
             f"\n\n🔗  [<b>Link</b>]({yt_url})\n🆔  <b>Format Code</b> : {choice_id or 'bestaudio/best'}"
             ),
        )
        if downtype == "v":
            retcode = await _tubeDl(url=yt_url,
                                    starttime=startTime,
                                    uid=choice_id)
        else:
            retcode = await _mp3Dl(url=yt_url,
                                   starttime=startTime,
                                   uid=choice_id)

        if retcode != 0:
            return await upload_msg.edit(str(retcode))
        _fpath = ""
        for _path in glob.glob(
                os.path.join(Config.DOWN_PATH, str(startTime), "*")):
            if not _path.lower().endswith((".jpg", ".png", ".webp")):
                _fpath = _path
        if not _fpath:
            await upload_msg.err("nothing found !")
            return
        uploaded_media = await upload(upload_msg, Path(_fpath), logvid=False)

        refresh_vid = await userge.bot.get_messages(Config.LOG_CHANNEL_ID,
                                                    uploaded_media.message_id)
        f_id = (get_file_id_and_ref(refresh_vid))[0]
        _thumb = None

        if downtype == "v":
            if refresh_vid.video.thumbs:
                _thumb = await userge.bot.download_media(
                    refresh_vid.video.thumbs[0].file_id)
            else:
                _thumb = download(get_ytthumb(yt_code))

            await xbot.edit_inline_media(
                c_q.inline_message_id,
                media=(await xmedia.InputMediaVideo(
                    file_id=f_id,
                    thumb=_thumb,
                    caption=f"📹  <b>[{uploaded_media.caption}]({yt_url})</b>",
                )),
            )

        else:  # Audio
            if refresh_vid.audio.thumbs:
                _thumb = await userge.bot.download_media(
                    refresh_vid.audio.thumbs[0].file_id)
            else:
                _thumb = download(get_ytthumb(yt_code, reverse=True))

            await xbot.edit_inline_media(
                c_q.inline_message_id,
                media=(await xmedia.InputMediaAudio(
                    file_id=f_id,
                    thumb=_thumb,
                    caption=f"🎵  <b>[{uploaded_media.caption}]({yt_url})</b>",
                )),
            )
Exemplo n.º 16
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

        if (
            inline_query.from_user.id in Config.OWNER_ID
            or inline_query.from_user.id in Config.SUDO_USERS
        ):

            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 str_y[0] == "ytdl":
                if len(str_y) == 2:
                    link = str_y[1]
                    x = ytdl.YoutubeDL({"no-playlist": True}).extract_info(
                        link, download=False
                    )
                    formats = x.get("formats", [x])
                    ytlink_code = x.get("id", None)
                    # uploader = x.get('uploader', None)
                    # channel_url = x.get('channel_url', None)
                    vid_title = x.get("title", None)
                    # upload_date = date_formatter(str(x.get('upload_date', None)))
                    vid_thumb = get_ytthumb(ytlink_code)
                    buttons = ytdl_btn_generator(formats, ytlink_code, inline_query.id)
                    caption_text = f"**{vid_title}**"
                    # caption_text += f"🔗 [Link]({link})  |  📅 : {upload_date}"
                    # caption_text += f"📹 : [{uploader}]({channel_url})"

                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=vid_thumb,
                            title=vid_title,
                            description="⬇️ Click to Download",
                            caption=caption_text,
                            reply_markup=InlineKeyboardMarkup(buttons),
                        )
                    )

            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://i.imgur.com/Zg58iXc.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"

                cn = requests.get(reddit_api)
                r = cn.json()
                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 == "rick":
                rick = [
                    [
                        InlineKeyboardButton(
                            text="🔍", url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"
                        )
                    ]
                ]
                results.append(
                    InlineQueryResultArticle(
                        title="Not a Rick Roll",
                        input_message_content=InputTextMessageContent("Search Results"),
                        description="Definately Not a Rick Roll",
                        thumb_url="https://i.imgur.com/hRCaKAy.png",
                        reply_markup=InlineKeyboardMarkup(rick),
                    )
                )

            if string == "alive":
                buttons = [
                    [
                        InlineKeyboardButton(
                            "🔧 SETTINGS", callback_data="settings_btn"
                        ),
                        InlineKeyboardButton(text="⚡️ REPO", url=Config.UPSTREAM_REPO),
                    ]
                ]

                alive_info = f"""
    **[USERGE-X](https://telegram.dog/x_xtests) is Up and Running**

 • 🐍 Python :  `v{versions.__python_version__}`
 • 🔥 Pyrogram :  `v{versions.__pyro_version__}`
 • 🧬 𝑿 :  `v{get_version()}`

{_get_mode()}  |  🕔: {userge.uptime}
"""

                if not MEDIA_URL and Config.ALIVE_MEDIA:
                    await get_alive_()

                if MEDIA_URL:
                    if MEDIA_TYPE == "url_gif":
                        results.append(
                            InlineQueryResultAnimation(
                                animation_url=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons),
                            )
                        )
                    elif MEDIA_TYPE == "url_image":
                        results.append(
                            InlineQueryResultPhoto(
                                photo_url=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons),
                            )
                        )
                    elif MEDIA_TYPE == "tg_image":
                        results.append(
                            InlineQueryResultCachedPhoto(
                                file_id=MEDIA_URL[0],
                                file_ref=MEDIA_URL[1],
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons),
                            )
                        )
                    else:
                        results.append(
                            InlineQueryResultCachedDocument(
                                title="USERGE-X",
                                file_id=MEDIA_URL[0],
                                file_ref=MEDIA_URL[1],
                                caption=alive_info,
                                description="ALIVE",
                                reply_markup=InlineKeyboardMarkup(buttons),
                            )
                        )
                else:  # default
                    random_alive = random.choice(ALIVE_IMGS)
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=random_alive,
                            caption=alive_info,
                            reply_markup=InlineKeyboardMarkup(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 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 len(string_split) == 2:  # workaround for list index out of range
                if 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:
                        cn = requests.get(f"{api_host}{codename}")
                        r = cn.json()
                    except ValueError:
                        return
                    s = requests.get(
                        f"{api_host}{codename}/releases/stable/last"
                    ).json()
                    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 str_y[0] == "spoiler":
                if not os.path.exists("./userge/xcache/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:
                        view_db = json.load(open("./userge/xcache/spoiler_db.json"))
                        if len(view_db) != 0:
                            numm = 0
                            for spoilerr in view_db:
                                numm += 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(PATH, "emoji_data.txt")
                try:
                    view_data = json.load(open(opinion))
                except:
                    view_data = False

                if view_data:
                    # Uniquely identifies an inline message
                    new_id = {int(inline_query.id): [{}]}
                    view_data.update(new_id)
                    json.dump(view_data, open(opinion, "w"))
                else:
                    d = {int(inline_query.id): [{}]}
                    json.dump(d, open(opinion, "w"))

                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 = "./userge/xcache/inline_db.json"
                if os.path.exists(inline_db_path):
                    with open(inline_db_path, "r") as data_file:
                        view_db = json.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 > 15:
                            view_db.pop(butt_ons, None)
                        data_count_n += 1

                    with open(inline_db_path, "w") as data_file:
                        json.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, None)
                        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_and_ref(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[0],
                                            file_ref=media_data[1],
                                            caption=textx,
                                            reply_markup=buttonsx,
                                        )
                                    )
                                else:
                                    results.append(
                                        InlineQueryResultCachedDocument(
                                            title=textx,
                                            file_id=media_data[0],
                                            file_ref=media_data[1],
                                            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":
                if len(str_y) == 2:
                    results = []
                    input_text = str_y[1]
                    font_names = [
                        "serif",
                        "sans",
                        "sans_i",
                        "serif_i",
                        "medi_b",
                        "medi",
                        "double",
                        "cursive_b",
                        "cursive",
                        "bigsmall",
                        "reverse",
                        "circle",
                        "circle_b",
                        "mono",
                        "square_b",
                        "square",
                        "smoth",
                        "goth",
                        "wide",
                        "web",
                        "weeb",
                        "weeeb",
                    ]
                    for f_name in font_names:
                        styled_str = await font_gen(f_name, input_text)
                        results.append(
                            InlineQueryResultArticle(
                                title=f_name.upper(),
                                input_message_content=InputTextMessageContent(
                                    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() == "secret":
                if len(str_x) == 3:
                    user_name = str_x[1]
                    msg = str_x[2]
                    try:
                        a = await userge.get_users(user_name)
                        user_id = a.id
                    except:
                        return
                    secret = os.path.join(PATH, "secret.txt")
                    try:
                        view_data = json.load(open(secret))
                    except:
                        view_data = False

                    if view_data:
                        # Uniquely identifies an inline message
                        new_id = {
                            str(inline_query.id): {"user_id": user_id, "msg": msg}
                        }
                        view_data.update(new_id)
                        json.dump(view_data, open(secret, "w"))
                    else:
                        d = {str(inline_query.id): {"user_id": user_id, "msg": msg}}
                        json.dump(d, open(secret, "w"))

                    buttons = [
                        [
                            InlineKeyboardButton(
                                "🔐  SHOW", callback_data=f"secret_{inline_query.id}"
                            )
                        ]
                    ]
                    results.append(
                        InlineQueryResultArticle(
                            title="Send A Secret Message",
                            input_message_content=InputTextMessageContent(
                                f"📩 <b>Secret Msg</b> for {user_name}. Only he/she can open it."
                            ),
                            description=f"Send Secret Message to: {user_name}",
                            thumb_url="https://i.imgur.com/c5pZebC.png",
                            reply_markup=InlineKeyboardMarkup(buttons),
                        )
                    )
            MAIN_MENU = InlineQueryResultArticle(
                title="Main Menu",
                input_message_content=InputTextMessageContent(" 𝐔𝐒𝐄𝐑𝐆𝐄-𝐗  𝗠𝗔𝗜𝗡 𝗠𝗘𝗡𝗨 "),
                url="https://github.com/code-rgb/USERGE-X",
                description="Userge-X Main Menu",
                thumb_url="https://i.imgur.com/1xsOo9o.png",
                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",
            )
Exemplo n.º 17
0
    async def ytdl_callback(_, c_q: CallbackQuery):
        startTime = time()
        inline_mode = True
        u_id = c_q.from_user.id
        if u_id not in Config.OWNER_ID and u_id not in Config.SUDO_USERS:
            return await c_q.answer("𝘿𝙚𝙥𝙡𝙤𝙮 𝙮𝙤𝙪𝙧 𝙤𝙬𝙣 𝙐𝙎𝙀𝙍𝙂𝙀-𝙓",
                                    show_alert=True)
        choice_id = c_q.matches[0].group(2)
        i_q_id = c_q.matches[0].group(3)
        callback_continue = "Downloading Video Please Wait..."
        callback_continue += f"\n\nFormat Code : {choice_id}"
        await c_q.answer(callback_continue, show_alert=True)
        upload_msg = await userge.send_message(Config.LOG_CHANNEL_ID,
                                               "Uploading...")
        yt_code = c_q.matches[0].group(1)
        yt_url = f"https://www.youtube.com/watch?v={yt_code}"
        try:
            await c_q.edit_message_caption(
                caption=
                (f"Video is now being ⬇️ Downloaded, for progress see:\nLog Channel:  [<b>click here</b>]({upload_msg.link})"
                 f"\n\n🔗  [<b>Link</b>]({yt_url})\n🆔  <b>Format Code</b> : {choice_id}"
                 ),
                reply_markup=None,
            )
        except MessageIdInvalid:
            inline_mode = False
            todelete = STORE_DATA.get(i_q_id)
            if todelete:
                bad_msg = await userge.get_messages(todelete["chat_id"],
                                                    todelete["msg_id"])
                await bad_msg.delete()
                upload_msg = await userge.send_message(todelete["chat_id"],
                                                       "Uploading ...")

        retcode = await _tubeDl(yt_url, startTime, choice_id)
        if retcode != 0:
            return await upload_msg.edit(str(retcode))
        _fpath = ""
        for _path in glob.glob(
                os.path.join(Config.DOWN_PATH, str(startTime), "*")):
            if not _path.lower().endswith((".jpg", ".png", ".webp")):
                _fpath = _path
        if not _fpath:
            await upload_msg.err("nothing found !")
            return
        uploaded_vid = await upload(upload_msg, Path(_fpath))
        if not inline_mode:
            return
        refresh_vid = await userge.bot.get_messages(Config.LOG_CHANNEL_ID,
                                                    uploaded_vid.message_id)
        f_id, f_ref = get_file_id_and_ref(refresh_vid)
        video_thumb = None
        if refresh_vid.video.thumbs:
            video_thumb = await userge.bot.download_media(
                refresh_vid.video.thumbs[0].file_id)
        else:
            video_thumb = download(get_ytthumb(yt_code))

        await c_q.edit_message_media(
            media=InputMediaVideo(
                media=f_id,
                file_ref=f_ref,
                thumb=video_thumb,
                caption=f"📹  <b>[{uploaded_vid.caption}]({yt_url})</b>",
                supports_streaming=True,
            ),
            reply_markup=None,
        )
        await uploaded_vid.delete()
Exemplo n.º 18
0
    async def forward_stored(self,
                             client: Union['_client.Userge', '_client._UsergeBot'],
                             message_id: int,
                             chat_id: int,
                             user_id: int,
                             reply_to_message_id: int,
                             del_in: int = 0) -> None:
        """\nforward stored message from log channel.

        Parameters:
            client (`Userge` | `usergeBot`):
                Pass Userge or UsergeBot.

            message_id (`int`):
                Message id of stored message.

            chat_id (`int`):
                ID of chat (dest) you want to farward.

            user_id (`int`):
                ID of user you want to reply.

            reply_to_message_id (`int`):
                If the message is a reply, ID of the original message.

            del_in (`int`):
                Time in Seconds for delete that message.

        Returns:
            None
        """
        if message_id and isinstance(message_id, int):
            message = await client.get_messages(chat_id=Config.LOG_CHANNEL_ID,
                                                message_ids=message_id)
            caption = ''
            file_id = file_ref = None
            if message.caption:
                caption = message.caption.html.split('\n\n', maxsplit=1)[-1]
            elif message.text:
                caption = message.text.html.split('\n\n', maxsplit=1)[-1]
            if caption:
                u_dict = await client.get_user_dict(user_id)
                chat = await client.get_chat(chat_id)
                u_dict.update({
                    'chat': chat.title if chat.title else "this group",
                    'count': chat.members_count})
                caption = caption.format_map(SafeDict(**u_dict))
            file_id, file_ref = get_file_id_and_ref(message)
            caption, buttons = parse_buttons(caption)
            if message.media and file_id and file_ref:
                msg = await client.send_cached_media(
                    chat_id=chat_id,
                    file_id=file_id,
                    file_ref=file_ref,
                    caption=caption,
                    reply_to_message_id=reply_to_message_id,
                    reply_markup=buttons if client.is_bot and buttons else None)
            else:
                msg = await client.send_message(
                    chat_id=chat_id,
                    text=caption,
                    reply_to_message_id=reply_to_message_id,
                    disable_web_page_preview=True,
                    reply_markup=buttons if client.is_bot and buttons else None)
            if del_in and msg:
                await asyncio.sleep(del_in)
                await msg.delete()