示例#1
0
async def flac_quality(message: Message):
    """set quality of flacbot"""
    bot_ = "FlacStoreBot" if "-r" not in message.flags else "rFlacStoreBot"
    if "-c" in message.flags:
        async with userge.conversation(bot_) as conv:
            await conv.send_message("/settings")
            check = await conv.get_response(mark_read=True)
        quality_ = check.reply_markup.inline_keyboard[0][0].text
        qual = quality_.split()[1]
        await message.edit(f"`Current quality set in the bot is: {qual}`",
                           del_in=5)
        return
    input_ = message.filtered_input_str
    if not input_:
        return await message.edit("`Provide quality to set...`", del_in=5)
    if (input_ not in ["flac", "320", "256", "128"] and "-r"
            not in message.flags) or (input_ not in ["flac", "320", "128"]
                                      and "-r" in message.flags):
        return await message.edit(
            f"`Input not found in available options, see '{Config.CMD_TRIGGER}help flac_q'...`",
            del_in=5,
        )
    if input_ == "flac":
        if "-r" in message.flags:
            q_ = 1
        else:
            q_ = 0
        quality = "FLAC"
    elif input_ == "320":
        if "-r" in message.flags:
            q_ = 0
        else:
            q_ = 1
        quality = "MP3_320"
    elif input_ == "256" and "-r" not in message.flags:
        q_ = 2
        quality = "MP3_256"
    elif input_ == "128":
        if "-r" in message.flags:
            q_ = 2
        else:
            q_ = 3
        quality = "MP3_128"
    await message.edit("`Changing quality...`")
    async with userge.conversation(bot_) as conv:
        try:
            await conv.send_message("/settings")
        except BaseException:
            return await message.edit("`Unblock` @FlacStoreBot `first.`",
                                      del_in=5)
        resp_one = await conv.get_response(mark_read=True)
        await resp_one.click(x=0)
        resp_two = await conv.get_response(mark_read=True)
        await resp_two.click(x=q_)
    await message.edit(f"Changed music quality to <b>{quality}</b>.", del_in=5)
示例#2
0
async def convert_botmode(msg: Message):
    """ convert to bot mode """
    if userge.has_bot:
        return await msg.err("using have bot mode")
    if not msg.input_str and '|' not in msg.input_str:
        return await msg.err("read .help convert_botmode")

    _, __ = msg.input_str.split('|', maxsplit=1)
    name = _.strip()
    username = __.strip()
    await msg.edit("`Converting to use bot mode`")
    try:
        async with userge.conversation('botfather') as conv:
            try:
                await conv.send_message('/start')
            except YouBlockedUser:
                await userge.unblock_user('botfather')
                await conv.send_message('/start')
            await conv.get_response()
            await conv.send_message('/newbot')
            await conv.get_response()
            await conv.send_message(name)
            await conv.get_response()
            await conv.send_message(username)
            response = await conv.get_response(mark_read=True)
            if 'Sorry' in response.text:
                await msg.err(response.text)
            else:
                await userge.promote_chat_member(config.LOG_CHANNEL_ID,
                                                 username)
                token = extract_entities(response, ["code"])[0]
                await msg.edit("DONE! Bot Mode will be enabled after restart.")
                await system.set_env("BOT_TOKEN", token)
    except StopConversation:
        await msg.err("@botfather didn't respond in time.")
示例#3
0
async def carbon_(message: Message):
    replied = message.reply_to_message
    if replied:
        text = replied.text
    else:
        text = message.input_str
    if not text:
        await message.err("input not found!")
        return
    await message.edit("`creating a carbon...`")
    async with userge.conversation("CarbonNowShBot", timeout=30) as conv:
        try:
            await conv.send_message(text)
        except YouBlockedUser:
            await message.edit('first **unblock** @CarbonNowShBot')
            return
        response = await conv.get_response(mark_read=True)
        while not response.reply_markup:
            response = await conv.get_response(mark_read=True)
        await response.click(x=random.randint(0, 2), y=random.randint(0, 8))
        response = await conv.get_response(mark_read=True)
        while not response.media:
            response = await conv.get_response(mark_read=True)
        caption = "\n".join(response.caption.split("\n")[0:2])
        file_id = response.document.file_id
        await message.delete()
        await userge.send_document(
            chat_id=message.chat.id,
            document=file_id,
            caption='`' + caption + '`',
            reply_to_message_id=replied.message_id if replied else None)
示例#4
0
async def quotecmd(message: Message):
    """quotecmd"""
    asyncio.get_event_loop().create_task(message.delete())
    args = message.input_str
    replied = message.reply_to_message
    async with userge.conversation('QuotLyBot') as conv:
        try:
            if replied and not args:
                await conv.forward_message(replied)
            else:
                if not args:
                    await message.err('input not found!')
                    return
                await conv.send_message(args)
        except YouBlockedUser:
            await message.edit('first **unblock** @QuotLyBot')
            return
        quote = await conv.get_response(mark_read=True)
        if not quote.sticker:
            await message.err('something went wrong!')
        else:
            message_id = replied.message_id if replied else None
            await userge.send_sticker(chat_id=message.chat.id,
                                      sticker=quote.sticker.file_id,
                                      file_ref=quote.sticker.file_ref,
                                      reply_to_message_id=message_id)
示例#5
0
async def quotecmd(message: Message):
    """quotecmd"""
    chat = '@es3n1n_bot'
    args = message.input_str
    replied = message.reply_to_message
    async with userge.conversation(chat) as conv:
        try:
            if replied and not args:
                text = await conv.forward_message(replied)
            else:
                if not args:
                    await message.err("```input not found!```", del_in=5)
                    return
                text = await conv.send_message(args)
        except YouBlockedUser:
            await message.edit('first **unblock** @es3n1n_bot')
            return
        await message.edit("```Wait Plox ...```")
        await userge.send_message(chat,
                                  "/quote",
                                  reply_to_message_id=text.message_id)
        await conv.get_response(mark_read=True)
        await conv.get_response(mark_read=True)
        await conv.get_response(mark_read=True)
        await conv.get_response(mark_read=True)
        await conv.get_response(mark_read=True)
        await conv.get_response(mark_read=True)
        quote = await conv.get_response(mark_read=True)
        message_id = replied.message_id if replied else None
        sticker = await userge.get_messages(chat, quote.message_id)
        await userge.send_sticker(message.chat.id,
                                  sticker.sticker.file_id,
                                  file_ref=sticker.sticker.file_ref,
                                  reply_to_message_id=message_id)
        await message.delete()
async def create_token_file(message):
    # Run through the OAuth flow and retrieve credentials
    flow = client.OAuth2WebServerFlow(G_PHOTOS_CLIENT_ID,
                                      G_PHOTOS_CLIENT_SECRET,
                                      OAUTH_SCOPE,
                                      redirect_uri=REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    async with userge.conversation(message.chat.id, timeout=60) as conv:
        await conv.send_message(
            "Go to the following link in "
            f"your browser: {authorize_url} and reply the code")
        response = await conv.get_response(mark_read=True)
        # LOG.info(response.stringify())
        code = response.text.strip()
        credentials = flow.step2_exchange(code)
        storage = file.Storage(TOKEN_FILE_NAME)
        storage.put(credentials)
        imp_gsem = await conv.send_document(document=TOKEN_FILE_NAME)
        await imp_gsem.reply_text(
            "please set <code>G_PHOTOS_AUTH_TOKEN_ID</code> = "
            f"<u>{imp_gsem.message_id}</u> ..!"
            "\n\n<i>This is only required, "
            "if you are running in an ephimeral file-system</i>.",
            parse_mode="html")
        return storage
示例#7
0
async def prof_ile(message: Message):
    """Get known/unknown profile links"""
    id_ = message.input_str
    if not id_:
        await message.err("Please provide user id...", del_in=5)
        return
    async with userge.conversation("missrose_bot") as conv:
        try:
            await conv.send_message(f"!info {id_}")
        except YouBlockedUser:
            await message.err("Unblock @missrose_bot first...", del_in=5)
            return
        info_ = await conv.get_response(mark_read=True)
    u_info = info_.text
    pass_ = "User info:"
    if pass_ in u_info:
        name_l = u_info.split("\n")[2]
    else:
        await message.err(
            f"Sorry, ID <code>{id_}</code> was not found in database...", del_in=5
        )
        return
    name_s = name_l.split(":")
    name = name_s[1] if (len(name_s) == 2) else "<b>Deleted account</b> (or blank name)"
    out = (
        f"<b>👤 User:</b> [{name}](tg://user?id={(id_)})\n"
        f"<b>#⃣ ID:</b> <code>{id_}</code>"
    )
    await message.edit(out)
示例#8
0
    async def vol_callback(cq: CallbackQuery):

        arg = cq.matches[0].group(1)
        volume = 0

        if arg.isnumeric():
            volume = int(arg)

        elif arg == "custom":

            try:
                async with userge.conversation(cq.message.chat.id, user_id=cq.from_user.id) as conv:
                    await cq.edit_message_text("`Now Input Volume`")

                    def _filter(_, __, m: RawMessage) -> bool:
                        r = m.reply_to_message
                        return r and r.message_id == cq.message.message_id

                    response = await conv.get_response(mark_read=True,
                                                       filters=filters.create(_filter))
            except StopConversation:
                await cq.edit_message_text("No arguments passed!")
                return

            if response.text.isnumeric():
                volume = int(response.text)
            else:
                await cq.edit_message_text("`Invalid Arguments!`")
                return

        if 200 >= volume > 0:
            await call.set_my_volume(volume)
            await cq.edit_message_text(f"Successfully set volume to {volume}")
        else:
            await cq.edit_message_text("`Invalid Range!`")
示例#9
0
async def unfban_(message: Message):
    """Unbans a user from connected Feds."""
    user = (message.extract_user_and_text)[0]
    fban_arg = ["❯", "❯❯", "❯❯❯", "❯❯❯ <b>Un-FBanned {}</b>"]
    await message.edit(fban_arg[0])
    input = message.input_str
    if message.reply_to_message:
        reason = input
    else:
        reason = input.split(" ", 1)[1]
    PROOF_CHANNEL = FBAN_LOG_CHANNEL if FBAN_LOG_CHANNEL else Config.LOG_CHANNEL_ID
    error_msg = "Provide a User ID or reply to a User"
    if user is None:
        return await message.err(error_msg, del_in=7)
    try:
        user_ = await message.client.get_users(user)
    except (PeerIdInvalid, IndexError):
        return await message.err(error_msg, del_in=7)
    user = user_.id
    reason = reason or "Not specified"
    failed = []
    total = 0
    await message.edit(fban_arg[1])
    async for data in FED_LIST.find():
        total += 1
        chat_id = int(data["chat_id"])
        try:
            async with userge.conversation(chat_id, timeout=8) as conv:
                await conv.send_message(f"/unfban {user} {reason}")
                response = await conv.get_response(
                    mark_read=True,
                    filters=(filters.user([609517172]) & ~filters.service),
                )
                resp = response.text
                if (("New un-FedBan" not in resp) and ("I'll give" not in resp)
                        and ("Un-FedBan" not in resp)):
                    failed.append(
                        f"{data['fed_name']}  \n__ID__: `{data['chat_id']}`")

        except BaseException:
            failed.append(data["fed_name"])
    if total == 0:
        return await message.err(
            "You Don't have any feds connected!\nsee .help addf, for more info."
        )
    await message.edit(fban_arg[2])

    if len(failed) != 0:
        status = f"Failed to un-fban in `{len(failed)}/{total}` feds.\n"
        for i in failed:
            status += "• " + i + "\n"
    else:
        status = f"Success! Un-Fbanned in `{total}` feds."
    msg_ = (
        fban_arg[3].format(user_.mention) +
        f"\n<b>ID:</b> <code>{user}</code>\n<b>Reason:</b> {reason}\n**Status:** {status}"
    )
    await message.edit(msg_)
    await userge.send_message(int(PROOF_CHANNEL), msg_)
示例#10
0
文件: fban.py 项目: 0anurag0/VoldyBot
async def fban_(message: Message):
    """Bans a user from connected Feds."""
    user, reason = message.extract_user_and_text
    fban_arg = ["❯", "❯❯", "❯❯❯", "❯❯❯ <b>FBanned {}</b>"]
    await message.edit(fban_arg[0])
    error_msg = "Provide a User ID or reply to a User"
    if user is None:
        return await message.err(error_msg, del_in=7)
    try:
        user_ = await message.client.get_users(user)
    except (PeerIdInvalid, IndexError):
        return await message.err(error_msg, del_in=7)
    user = user_.id
    if (user in Config.SUDO_USERS or user in Config.OWNER_ID
            or user == (await message.client.get_me()).id):
        return await message.err(
            "Can't F-Ban users that exists in Sudo or Owners", del_in=7)
    failed = []
    total = 0
    reason = reason or "Not specified."
    await message.edit(fban_arg[1])
    async for data in FED_LIST.find():
        total += 1
        chat_id = int(data["chat_id"])
        try:
            async with userge.conversation(chat_id, timeout=8) as conv:
                await conv.send_message(f"/fban {user} {reason}")
                response = await conv.get_response(
                    mark_read=True,
                    filters=(filters.user([609517172]) & ~filters.service),
                )
                resp = response.text
                if (("New FedBan" not in resp)
                        and ("Starting a federation ban" not in resp)
                        and ("Start a federation ban" not in resp)
                        and ("FedBan reason updated" not in resp)):
                    failed.append(
                        f"{data['fed_name']}  \n__ID__: `{data['chat_id']}`")

        except BaseException:
            failed.append(data["fed_name"])
    if total == 0:
        return await message.err(
            "You Don't have any feds connected!\nsee .help addf, for more info."
        )
    await message.edit(fban_arg[2])

    if len(failed) != 0:
        status = f"Failed to fban in {len(failed)}/{total} feds.\n"
        for i in failed:
            status += "• " + i + "\n"
    else:
        status = f"Success! Fbanned in `{total}` feds."
    msg_ = (fban_arg[3].format(user_.mention) +
            f"\n**Reason:** {reason}\n**Status:** {status}")
    await message.edit(msg_)
    await CHANNEL.log(msg_)
示例#11
0
async def quotecmd(message: Message):
    """quotecmd"""
    quote_list = []
    replied = message.reply_to_message
    if replied and "l" in message.flags and not message.filtered_input_str:
        args = ""
        limit = message.flags.get("l", 1)
        if limit.isdigit():
            limit = int(limit)
        else:
            return await message.err("give valid no. of message to quote", del_in=3)
        num = min(limit, 24)
        async for msg in userge.iter_history(
            message.chat.id, limit=num, offset_id=replied.message_id, reverse=True
        ):
            if msg.message_id != message.message_id:
                quote_list.append(msg.message_id)
    else:
        args = message.input_str
        quote_list.append(replied.message_id)
    asyncio.get_event_loop().create_task(message.delete())

    async with userge.conversation("QuotLyBot") as conv:
        try:
            if quote_list and not args:
                await userge.forward_messages("QuotLyBot", message.chat.id, quote_list)
            else:
                if not args:
                    await message.err("input not found!")
                    return
                await conv.send_message(args)
        except YouBlockedUser:
            await message.edit("first **unblock** @QuotLyBot")
            return
        quote = await conv.get_response(mark_read=True)
        if not (quote.sticker or quote.document):
            await message.err("something went wrong!")
        else:
            message_id = replied.message_id if replied else None
            if quote.sticker:
                await userge.send_sticker(
                    chat_id=message.chat.id,
                    sticker=quote.sticker.file_id,
                    file_ref=quote.sticker.file_ref,
                    reply_to_message_id=message_id,
                )
            else:
                await userge.send_document(
                    chat_id=message.chat.id,
                    document=quote.document.file_id,
                    file_ref=quote.document.file_ref,
                    reply_to_message_id=message_id,
                )
示例#12
0
async def unfban_(message: Message):
    """Unbans a user from connected Feds."""
    user = (message.extract_user_and_text)[0]
    fban_arg = ["❯", "❯❯", "❯❯❯", "❯❯❯ <b>Un-FBanned {} Successfully</b>"]
    await message.edit(fban_arg[0])
    error_msg = "Provide a User ID or reply to a User"
    if user is None:
        return await message.err(error_msg, del_in=7)
    try:
        user_ = await message.client.get_users(user)
    except PeerIdInvalid:
        return await message.err(error_msg, del_in=7)
    user = user_.id
    failed = []
    total = 0
    await message.edit(fban_arg[1])
    async for data in FED_LIST.find():
        total += 1
        chat_id = int(data["chat_id"])
        try:
            async with userge.conversation(chat_id, timeout=8) as conv:
                await conv.send_message(f"/unfban {user}")
                response = await conv.get_response(
                    mark_read=True,
                    filters=(filters.user([609517172]) & ~filters.service),
                )
                resp = response.text
                if (
                    ("New un-FedBan" not in resp)
                    and ("I'll give" not in resp)
                    and ("Un-FedBan" not in resp)
                ):
                    failed.append(f"{data['fed_name']}  \n__ID__: `{data['chat_id']}`")

        except BaseException:
            failed.append(data["fed_name"])
    if total == 0:
        return await message.err(
            "You Don't have any feds connected!\nsee .help addf, for more info."
        )
    await message.edit(fban_arg[2])

    if len(failed) != 0:
        status = f"Failed to un-fban in `{len(failed)}/{total}` feds.\n"
        for i in failed:
            status += "• " + i + "\n"
    else:
        status = f"Success! Un-Fbanned in `{total}` feds."
    msg_ = fban_arg[3].format(user_.mention) + f"\n**Status:** {status}"
    await message.edit(msg_)
    await CHANNEL.log(msg_)
示例#13
0
async def get_auth_():
    _authurl = (
        "https://accounts.spotify.com/authorize?client_id={}&response_type=code&redirect_uri="
        "https%3A%2F%2Fexample.com%2Fcallback&scope=user-read-playback-state%20user-read-currently"
        "-playing+user-follow-read+user-read-recently-played+user-top-read+playlist-read-private+playlist"
        "-modify-private+user-follow-modify+user-read-private")
    async with userge.conversation(Config.LOG_CHANNEL_ID, timeout=150) as conv:
        msg_ = await conv.send_message(
            "Go to the following link in "
            f"your browser: {_authurl.format(Config.SPOTIFY_CLIENT_ID)} and reply the code or url"
        )
        response = await conv.get_response(mark_read=True)
        await msg_.edit("`Processing ...`")
        return response.text.strip(), msg_
示例#14
0
async def del_post(message: Message):
    """delete chat from list for posting"""
    if "-all" in message.flags:
        msg_ = (
            "### <b>DELETING ALL CHATS FROM POST LIST</b> ###\n\n"
            "For confirmation of deleting all chats from POST LIST,\n"
            "please reply with '`Yes, delete all chats in list for posting.`' <b>within 10 seconds</b>."
        )
        await message.edit(msg_)
        me_ = await userge.get_me()
        try:
            async with userge.conversation(message.chat.id) as conv:
                response = await conv.get_response(mark_read=True,
                                                   filters=(filters.user(
                                                       me_.id)))
        except BaseException:
            msg_ += "\n\n### Process cancelled as no response given. ###"
            await message.edit(msg_)
            return
        resp = response.text
        if resp == "Yes, delete all chats in list for posting.":
            await POST_LIST.drop()
            await resp.delete()
            del_ = "Deleted whole <b>POST LIST</b> successfully."
            await message.edit(del_)
            await CHANNEL.log(del_)
            return

    chat_ = message.input_str
    if not chat_:
        chat_ = message.chat.id
    try:
        chat_ = await userge.get_chat(chat_)
    except BaseException:
        await message.edit(f"`Provided input ({chat_}) is not a chat...`",
                           del_in=5)
        return
    chat_id = chat_.id
    found = await POST_LIST.find_one({"chat_id": chat_id})
    if found:
        msg_ = f"Successfully removed <b>{found['chat_name']}</b> from POST LIST."
        await POST_LIST.delete_one(found)
        await message.edit(msg_)
        await CHANNEL.log(msg_)
        return
    else:
        await message.edit(
            f"The chat <b>{chat_id}</b> doesn't exist in POST LIST.")
示例#15
0
async def add_sticker(message: Message, short_name: str, sticker: str, emoji: str) -> bool:
    if userge.has_bot:
        media = (await userge.bot.send(UploadMedia(
            peer=await userge.bot.resolve_peer('stickers'),
            media=InputMediaUploadedDocument(
                mime_type=userge.guess_mime_type(sticker) or "application/zip",
                file=(
                    await userge.bot.save_file(sticker)
                ),
                force_file=True,
                thumb=None,
                attributes=[
                    DocumentAttributeFilename(file_name=os.path.basename(sticker))
                ]
            )
        )
        )).document
        await userge.bot.send(
            AddStickerToSet(
                stickerset=InputStickerSetShortName(
                    short_name=short_name),
                sticker=InputStickerSetItem(
                    document=InputDocument(
                        id=media.id,
                        access_hash=media.access_hash,
                        file_reference=media.file_reference),
                    emoji=emoji)))
    else:
        async with userge.conversation('Stickers', limit=30) as conv:
            try:
                await conv.send_message('/addsticker')
            except YouBlockedUser:
                await message.edit('first **unblock** @Stickers')
                return False
            await conv.get_response(mark_read=True)
            await conv.send_message(short_name)
            await conv.get_response(mark_read=True)
            await conv.send_document(sticker)
            rsp = await conv.get_response(mark_read=True)
            if "Sorry, the file type is invalid." in rsp.text:
                await message.edit("`Failed to add sticker, use` @Stickers "
                                   "`bot to add the sticker manually.`")
                return False
            await conv.send_message(emoji)
            await conv.get_response(mark_read=True)
            await conv.send_message('/done')
            await conv.get_response(mark_read=True)
    return True
示例#16
0
async def bitly(msg: Message):
    url = msg.input_or_reply_str
    if not url:
        await msg.err("need url to shorten")
        return
    try:
        async with userge.conversation("Sl_BitlyBot") as conv:
            await conv.send_message("/start")
            await conv.get_response(mark_read=True)
            await conv.send_message(url)
            shorten_url = (await conv.get_response(mark_read=True)).text.split(
                "\n", maxsplit=1
            )[-1]
            await msg.edit(f"`{shorten_url}`", disable_web_page_preview=True)
    except YouBlockedUser:
        await msg.edit("unblock **@Sl_BitlyBot** to shorten URLs.")
    except StopConversation:
        await msg.err("bot is down")
示例#17
0
async def flac_bot(message: Message):
    """download music with FlacBot"""
    query_ = message.input_str
    if not query_:
        return await message.edit("`Provide input to search...`", del_in=5)
    query_ = capitaled(query_)
    await message.edit(f"Searching <b>{query_}</b> on deezer...")
    bot_ = "rFlacStoreBot" if "-r" in message.flags else "FlacStoreBot"
    results = await userge.get_inline_bot_results(bot_, query_)
    if not results:
        return await message.edit("`Results not found...`", del_in=5)
    try:
        log_send = await userge.send_inline_bot_result(
            chat_id=Config.LOG_CHANNEL_ID,
            query_id=results.query_id,
            result_id=results.results[0].id,
        )
    except IndexError:
        return await message.edit("`Couldn't find the song...`", del_in=5)
    reply_ = message.reply_to_message
    if reply_:
        reply_to = reply_.message_id
    else:
        reply_to = None
    try:
        await userge.copy_message(
            chat_id=bot_,
            from_chat_id=Config.LOG_CHANNEL_ID,
            message_id=log_send.updates[0].id,
        ),
        async with userge.conversation(bot_) as conv:
            await conv.get_response(mark_read=True)
            music_ = await conv.get_response(mark_read=True)
        await userge.copy_message(message.chat.id,
                                  bot_,
                                  music_.message_id,
                                  reply_to_message_id=reply_to)
        await message.delete()
    except BaseException as e:
        await message.edit(
            f"`Something unexpected happened.`\n<b>Error:</b> `{e}`", del_in=5)
async def true_c_(message: Message):
    num = message.input_str
    reply = message.reply_to_message
    if not num:
        if reply:
            num = reply.text
            reply_to = reply.message_id
        else:
            await message.edit("Provide number to search...", del_in=5)
            return
    else:
        reply_to = message.message_id
    if not num.startswith("+"):
        await message.edit(
            "Provide number in <b><u>international</u></b> format...",
            del_in=5)
        return
    num_check = num.replace("+", "")
    if not num_check.isdigit():
        await message.edit("Provide a proper number...", del_in=5)
        return
    await message.edit("Searching the database...")
    bot = "@RespawnRobot"
    async with userge.conversation(bot) as conv:
        try:
            await conv.send_message("/start")
            await conv.get_response()
            await conv.send_message(num)
            await asyncio.sleep(5)
            check = await conv.get_response()
            info = check.text
            await userge.send_read_acknowledge(conv.chat_id)
        except BaseException:
            await message.edit(
                "Please unblock <code>@RespawnRobot</code> and try again...",
                del_in=5)
            return
        await userge.send_message(message.chat.id,
                                  info,
                                  reply_to_message_id=reply_to)
    await message.delete()
示例#19
0
async def buttery2_(message: Message):
    """ Get User's Phone Status"""
    replied = message.reply_to_message
    if not replied:
        await message.err("```Reply to get Second Phone Battery Status...```",
                          del_in=5)
        return
    user = replied.from_user.id
    chat = "@ravanaphonebot"
    await message.edit("```Getting Battery information of Second Phone```")
    msgs = []
    ERROR_MSG = "For your kind information, you blocked @ravanaphonebot, Unblock it"
    try:
        async with userge.conversation(chat) as conv:
            try:
                await conv.send_message("/battery".format(user))
            except YouBlockedUser:
                await message.err(f"**{ERROR_MSG}**", del_in=5)
                return
            msgs.append(await conv.get_response(mark_read=True))
            msgs.append(await conv.get_response(mark_read=True))
            msgs.append(await conv.get_response(timeout=3, mark_read=True))
    except StopConversation:
        pass
    battery2 = "Battery"
    username = "******"
    for msg in msgs:
        if "-u" in message.flags:
            if msg.text.startswith("No records found"):
                await message.edit("```User never changed his Username...```",
                                   del_in=5)
                return
            if msg.text.startswith(username):
                await message.edit(f"`{msg.text}`")
        else:
            if msg.text.startswith("No records found"):
                await message.edit("```User never changed his Name...```",
                                   del_in=5)
                return
            if msg.text.startswith(battery2):
                await message.edit(f"`{msg.text}`")
示例#20
0
async def sangmata_(message: Message):
    """Get User's Updated previous Names and Usernames"""
    replied = message.reply_to_message
    if not replied:
        await message.err("```Reply to get Name and Username History...```",
                          del_in=5)
        return
    user = replied.from_user.id
    chat = "@Sangmatainfo_bot"
    await message.edit("```Getting info, Wait plox ...```")
    msgs = []
    ERROR_MSG = "For your kind information, you blocked @Sangmatainfo_bot, Unblock it"
    try:
        async with userge.conversation(chat) as conv:
            try:
                await conv.send_message("/search_id {}".format(user))
            except YouBlockedUser:
                await message.err(f"**{ERROR_MSG}**", del_in=5)
                return
            msgs.append(await conv.get_response(mark_read=True))
            msgs.append(await conv.get_response(mark_read=True))
            msgs.append(await conv.get_response(timeout=3, mark_read=True))
    except StopConversation:
        pass
    name = "Name History"
    username = "******"
    for msg in msgs:
        if "-u" in message.flags:
            if msg.text.startswith("No records found"):
                await message.edit("```User never changed his Username...```",
                                   del_in=5)
                return
            if msg.text.startswith(username):
                await message.edit(f"`{msg.text}`")
        else:
            if msg.text.startswith("No records found"):
                await message.edit("```User never changed his Name...```",
                                   del_in=5)
                return
            if msg.text.startswith(name):
                await message.edit(f"`{msg.text}`")
示例#21
0
文件: quote.py 项目: xten81/Userge
async def quotecmd(message: Message):
    """quotecmd"""
    asyncio.create_task(message.delete())
    args = message.input_str
    replied = message.reply_to_message
    async with userge.conversation('QuotLyBot') as conv:
        try:
            if replied:
                await conv.forward_message(replied)
            else:
                if not args:
                    await message.err('input not found!')
                    return
                await conv.send_message(args)
        except YouBlockedUser:
            await message.edit('first **unblock** @QuotLyBot')
            return
        quote = await conv.get_response(mark_read=True)
        await userge.forward_messages(chat_id=message.chat.id,
                                      from_chat_id=conv.chat_id,
                                      message_ids=quote.message_id,
                                      as_copy=True)
示例#22
0
async def f_stat(message: Message):
    """Fstat of user"""
    reply = message.reply_to_message
    user_ = message.input_str if not reply else reply.from_user.id
    if not user_:
        user_ = message.from_user.id
    try:
        get_u = await userge.get_users(user_)
        user_name = full_name(get_u)
        user_id = get_u.id
        await message.edit(
            f"Fetching fstat of user <a href='tg://user?id={user_id}'><b>{user_name}</b></a>..."
        )
    except BaseException:
        await message.edit(
            f"Fetching fstat of user <b>{user_}</b>...\nWARNING: User not found in your database, checking Rose's database."
        )
        user_name = user_
        user_id = user_
    bot_ = "MissRose_bot"
    try:
        async with userge.conversation(bot_) as conv:
            await conv.send_message(f"!fstat {user_id}")
            response = await conv.get_response(mark_read=True,
                                               filters=filters.edited)
    except YouBlockedUser:
        await message.err("Unblock @missrose_bot first...", del_in=5)
        return
    except Exception as e:
        return await message.edit(f"<b>ERROR:</b> `{e}`")
    fail = "Could not find a user"
    resp = response.text.html
    resp = resp.replace("/fbanstat", f"`{Config.CMD_TRIGGER}fbanstat`")
    if fail in resp:
        await message.edit(
            f"User <b>{user_name}</b> (<code>{user_id}</code>) could not be found in @MissRose_bot's database."
        )
    else:
        await message.edit(resp, parse_mode="html")
示例#23
0
async def carbon_(message: Message):
    if Config.GOOGLE_CHROME_BIN is None:
        replied = message.reply_to_message
        if replied:
            text = replied.text
        else:
            text = message.text
        if not text:
            await message.err("need input text!")
            return
        await message.edit("`Sedang Mengcarbon Sayang...`")
        async with userge.conversation("CarbonNowShBot", timeout=30) as conv:
            try:
                await conv.send_message(text)
            except YouBlockedUser:
                await message.edit('first **unblock** @CarbonNowShBot')
                return
            response = await conv.get_response(mark_read=True)
            while not response.reply_markup:
                response = await conv.get_response(mark_read=True)
            await response.click(x=random.randint(0, 2),
                                 y=random.randint(0, 8))
            response = await conv.get_response(mark_read=True)
            while not response.media:
                response = await conv.get_response(mark_read=True)
            caption = "\n".join(response.caption.split("\n")[0:2])
            file_id = response.document.file_id
            await asyncio.gather(
                message.delete(),
                userge.send_document(chat_id=message.chat.id,
                                     document=file_id,
                                     caption='`' + caption + '`',
                                     reply_to_message_id=replied.message_id
                                     if replied else None))
    else:
        input_str = message.filtered_input_str
        replied = message.reply_to_message
        theme = 'seti'
        lang = 'auto'
        red = message.flags.get('r', random.randint(0, 255))
        green = message.flags.get('g', random.randint(0, 255))
        blue = message.flags.get('b', random.randint(0, 255))
        alpha = message.flags.get('a', random.randint(0, 100))
        bg_ = f"rgba({red}, {green}, {blue}, {alpha})"
        if replied and (replied.text or
                        (replied.document
                         and 'text' in replied.document.mime_type)):
            message_id = replied.message_id
            if replied.document:
                await message.edit("`Downloading File...`")
                path_ = await message.client.download_media(
                    replied, file_name=Config.DOWN_PATH)
                async with aiofiles.open(path_) as file_:
                    code = await file_.read()
                os.remove(path_)
            else:
                code = replied.text
            if input_str:
                if '|' in input_str:
                    args = input_str.split('|')
                    if len(args) == 2:
                        theme = args[0].strip()
                        lang = args[1].strip()
                else:
                    theme = input_str
        elif input_str:
            message_id = message.message_id
            if '|' in input_str:
                args = input_str.split('|')
                if len(args) == 3:
                    theme = args[0].strip()
                    lang = args[1].strip()
                    code = args[2].strip()
                elif len(args) == 2:
                    theme = args[0].strip()
                    code = args[1].strip()
            else:
                code = input_str
        else:
            await message.err("Masukan Text Dulu Dong Sayang !")
            return
        await message.edit(
            "`Oke Perintah Di Terima Sayang , Aku akan Ngeproses Carbon Mu Sayang...`"
        )
        code = quote_plus(code)
        await message.edit("`Proses Sudah 20% Sayang`")
        carbon_path = os.path.join(Config.DOWN_PATH, "carbon.png")
        if os.path.isfile(carbon_path):
            os.remove(carbon_path)
        url = CARBON.format(theme=theme, lang=lang, code=code, bg=bg_)
        if len(url) > 2590:
            await message.err("input too large!")
            return
        chrome_options = webdriver.ChromeOptions()
        chrome_options.binary_location = Config.GOOGLE_CHROME_BIN
        chrome_options.add_argument("--headless")
        chrome_options.add_argument("--window-size=1920x1080")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-gpu")
        prefs = {'download.default_directory': Config.DOWN_PATH}
        chrome_options.add_experimental_option('prefs', prefs)
        driver = webdriver.Chrome(chrome_options=chrome_options)
        driver.get(url)
        await message.edit("`Proses Sudah 40% Sayang`")
        driver.command_executor._commands["send_command"] = (  # pylint: disable=protected-access
            "POST", '/session/$sessionId/chromium/send_command')
        params = {
            'cmd': 'Page.setDownloadBehavior',
            'params': {
                'behavior': 'allow',
                'downloadPath': Config.DOWN_PATH
            }
        }
        driver.execute("send_command", params)
        # driver.find_element_by_xpath("//button[contains(text(),'Export')]").click()
        driver.find_element_by_id("export-menu").click()
        await asyncio.sleep(1)
        await message.edit("`Proses Sudah 60% Sayang`")
        driver.find_element_by_xpath("//button[contains(text(),'4x')]").click()
        await asyncio.sleep(1)
        driver.find_element_by_xpath(
            "//button[contains(text(),'PNG')]").click()
        await message.edit("`Proses Sudah 80% Sayang`")
        while not os.path.isfile(carbon_path):
            await asyncio.sleep(0.5)
        await message.edit("`Proses Sudah 100% Sayang`")
        await message.edit("`Mengupload Hasil Carbon Mu Sayang!...`")
        await asyncio.gather(
            message.delete(),
            message.client.send_photo(chat_id=message.chat.id,
                                      photo=carbon_path,
                                      reply_to_message_id=message_id))
        os.remove(carbon_path)
        driver.quit()
示例#24
0
async def meme_(message: Message):
    """ meme for media """
    replied = message.reply_to_message
    if not (replied and message.input_str):
        await message.err("Nibba, reply to Media and give some input...")
        return
    if not (replied.photo or replied.sticker or replied.video
            or replied.animation):
        await message.err("reply to only media...")
        return
    if not os.path.isdir(Config.DOWN_PATH):
        os.makedirs(Config.DOWN_PATH)
    await message.edit("`Memifying...`")

    meme_file = None
    should_forward = False
    dls_loc = None

    if (replied.photo or
        (replied.sticker and replied.sticker.file_name.endswith(".webp"))):
        should_forward = True
    else:
        dls = await message.client.download_media(message=replied,
                                                  file_name=Config.DOWN_PATH)
        dls_loc = os.path.join(Config.DOWN_PATH, os.path.basename(dls))
        if replied.sticker and replied.sticker.file_name.endswith(".tgs"):
            file_1 = os.path.join(Config.DOWN_PATH, "meme.png")
            cmd = f"lottie_convert.py --frame 0 -if lottie -of png {dls_loc} {file_1}"
            stdout, stderr = (await runcmd(cmd))[:2]
            if not os.path.lexists(file_1):
                await message.err("Sticker not found, cuz its gay...")
                raise Exception(stdout + stderr)
            meme_file = file_1
        elif replied.animation or replied.video:
            file_2 = os.path.join(Config.DOWN_PATH, "meme.png")
            await take_screen_shot(dls_loc, 0, file_2)
            if not os.path.lexists(file_2):
                await message.err("Media not found...")
                return
            meme_file = file_2

    chat = "@MemeAuto_bot"
    async with userge.conversation(chat) as conv:
        try:
            await conv.send_message("/start")
            await conv.get_response(mark_read=True)
        except YouBlockedUser:
            await message.err(
                "this cmd not for you, If you want to use, Unblock **@MemeAutobot**",
                del_in=5)
            return
        await conv.send_message(message.input_str)
        response = await conv.get_response(mark_read=True)
        if "Okay..." not in response.text:
            await message.err("Bot is Down, try to restart Bot !...")
            return
        if should_forward:
            await conv.forward_message(replied)
        else:
            await userge.send_photo(chat, meme_file)
        response = await conv.get_response(mark_read=True)
        if response.sticker:
            await response.copy(message.chat.id,
                                reply_to_message_id=replied.message_id)
    await message.delete()
    for file in (meme_file, dls_loc):
        if file and os.path.exists(file):
            os.remove(file)
示例#25
0
async def _insta_post_downloader(message: Message):
    """ download instagram post """
    await message.edit('`Setting up Configs. Please don\'t flood.`')
    dirname = 'instadl_{target}'
    filename = '{target}\'s_post'
    insta = Instaloader(dirname_pattern=dirname,
                        filename_pattern=filename,
                        download_video_thumbnails=False,
                        download_geotags=False,
                        download_comments=False,
                        save_metadata=False,
                        compress_json=False)
    if Config.INSTA_ID and Config.INSTA_PASS:
        # try login
        try:
            insta.load_session_from_file(Config.INSTA_ID)
            await message.edit('`Logged in with current Session`')
        except FileNotFoundError:
            await message.edit('`Login required. Trying to login`')
            try:
                insta.login(Config.INSTA_ID, Config.INSTA_PASS)
            except InvalidArgumentException:
                await message.err('Provided `INSTA_ID` is incorrect')
                return
            except BadCredentialsException:
                await message.err('Provided `INSTA_PASS` is incorrect')
                return
            except ConnectionException:
                await message.err(
                    'Instagram refused to connect. Try again later or never'
                    ' (your choice)😒')
                return
            # This is a nightmare.
            except TwoFactorAuthRequiredException:
                # Send a promt for 2FA code in saved messages
                chat_type = 'Saved Messages' if message.from_user.is_self else 'Private Message'
                text = ('[<b>2 Factor Authentication Detected</b>]\n'
                        f'I have sent a message to {chat_type}. '
                        'Please continue there and send your 2FA code.')
                await message.edit(text)
                for _ in range(4):
                    # initial convo with the user who sent message in pm.
                    # if user is_self convo in saved messages
                    # else in pm of sudo user
                    async with userge.conversation(
                            message.from_user.id) as asker:
                        asked = await asker.send_message(
                            'Please reply me with your 2FA code `int`')
                        response = await asker.get_response(mark_read=True)
                        if not (response.reply_to_message
                                and response.reply_to_message.is_self):
                            # I said reply me.
                            continue
                        code = response.text
                        if not (code.isdigit() and len(code) == 6):
                            # the six digit code
                            # What else it has always been a six digit code.
                            continue
                        try:
                            insta.two_factor_login(code)
                            break
                        except BadCredentialsException as b_c_e:
                            await asked.err(b_c_e)
                        except InvalidArgumentException:
                            await asked.edit('`No pending Login Found`')
                            return
            else:
                try:
                    insta.save_session_to_file()
                except LoginRequiredException:
                    await message.err(
                        'Failed to save session file, probably due to invalid login.'
                    )
                    await asyncio.sleep(5)
    else:
        await message.edit(
            'Login Credentials not found.\n`[NOTE]`: '
            '**You may not be able to download private contents or so**')
        await asyncio.sleep(2)

    p = r'^https:\/\/www\.instagram\.com\/(p|tv|reel)\/([A-Za-z0-9\-]*)\/(\?igshid=[a-zA-Z0-9]*)?$'
    match = re.search(p, message.input_str)

    if '-u' in message.flags:
        username = message.filtered_input_str
        sent = await message.edit(f'`Fetching all posts of {username}`')
        profile = await get_profile(insta, username)
        for post in await get_profile_posts(profile):
            try:
                await download_post(insta, post)
                await upload_to_tg(message,
                                   dirname.format(target=post.owner_username),
                                   post)
            except FloodWait as f_w:
                await asyncio.sleep(f_w.x + 10)
                await upload_to_tg(message,
                                   dirname.format(target=post.owner_username),
                                   post)
            except (KeyError, LoginRequiredException):
                await message.err('Private Content Login Required')
                return
            finally:
                shutil.rmtree(dirname.format(target=post.owner_username),
                              ignore_errors=True)
        await sent.delete()
    elif match:
        dtypes = {'p': 'POST', 'tv': 'IGTV', 'reel': 'REELS'}
        d_t = dtypes.get(match.group(1))
        if not d_t:
            await message.err('Unsupported Format')
            return
        sent = await message.edit(f'`Fetching {d_t} Content.`')
        shortcode = match.group(2)
        post = await get_post(insta, shortcode)
        try:
            await download_post(insta, post)
            await upload_to_tg(message,
                               dirname.format(target=post.owner_username),
                               post)
        except (KeyError, LoginRequiredException):
            await message.err("Post is private. Login and try again")
            return
        except FloodWait as f_w:
            await asyncio.sleep(f_w.x + 5)
            await upload_to_tg(message,
                               dirname.format(target=post.owner_username),
                               post)
        finally:
            shutil.rmtree(dirname.format(target=post.owner_username),
                          ignore_errors=True)
        await sent.delete()
    else:
        await message.err('`Invalid Input`')
示例#26
0
async def fry_(message: Message):
    """ fryer for any media """
    frying_file = None
    replied = message.reply_to_message
    if not (replied and message.input_str):
        await message.err("Reply to Media and gib fry count to deepfry !...")
        return
    if not (replied.photo or replied.sticker or replied.video or replied.animation):
        await message.err("Reply to Media only !...")
        return
    args = message.input_str
    if not args.isdigit():
        await message.err("Need fry count from 1 - 8 only !...")
        return
    args = int(args)
    if not 0 < args < 9:
        await message.err("Invalid range !...")
        return
    if not os.path.isdir(Config.DOWN_PATH):
        os.makedirs(Config.DOWN_PATH)
    await message.edit("`Frying, Wait plox ...`")
    dls = await message.client.download_media(
        message=replied,
        file_name=Config.DOWN_PATH,
        progress=progress,
        progress_args=(message, "Downloading to my local")
    )
    dls_loc = os.path.join(Config.DOWN_PATH, os.path.basename(dls))
    if replied.sticker and replied.sticker.file_name.endswith(".tgs"):
        await message.edit("```Ohh nice sticker, Lemme deepfry this Animated sticker ...```")
        webp_file = os.path.join(Config.DOWN_PATH, "fry.png")
        cmd = f"lottie_convert.py --frame 0 -if lottie -of png {dls_loc} {webp_file}"
        stdout, stderr = (await runcmd(cmd))[:2]
        if not os.path.lexists(webp_file):
            await message.err("```Media not found ...```", del_in=5)
            raise Exception(stdout + stderr)
        frying_file = webp_file
    elif replied.animation or replied.video:
        if replied.video:
            await message.edit("```Wait bruh, lemme deepfry this video ...```")
        else:
            await message.edit("```What a Gif, Lemme deepfry this ...```")
        jpg_file = os.path.join(Config.DOWN_PATH, "fry.jpg")
        await take_screen_shot(dls_loc, 0, jpg_file)
        if not os.path.lexists(jpg_file):
            await message.err("```Media not found ...```", del_in=5)
            return
        frying_file = jpg_file
    elif replied.sticker and replied.sticker.file_name.endswith(".webp"):
        await message.edit("```Lemme deepfry this Sticker, wait plox ...```")
        png_file = os.path.join(Config.DOWN_PATH, "fry.jpg")
        os.rename(dls_loc, png_file)
        if not os.path.lexists(png_file):
            await message.err("```Media not found ...```", del_in=5)
            return
        frying_file = png_file
    if frying_file is None:
        frying_file = dls_loc
    chat = "@image_deepfrybot"
    async with userge.conversation(chat) as conv:
        try:
            await conv.send_message("/start")
        except YouBlockedUser:
            await message.edit(
                "**For your kind information, you blocked @Image_DeepfryBot, Unblock it**",
                del_in=5)
            return
        await conv.get_response(mark_read=True)
        media = await userge.send_photo(chat, frying_file)
        await conv.get_response(mark_read=True)
        await userge.send_message(
            chat,
            "/deepfry {}".format(args),
            reply_to_message_id=media.message_id,
        )
        response = await conv.get_response(mark_read=True)
        if not response.photo:
            await message.err("Bot is Down, try to restart Bot !...", del_in=5)
            return
        message_id = replied.message_id
        deep_fry = None
        if response.photo:
            directory = Config.DOWN_PATH
            files_name = "fry.webp"
            deep_fry = os.path.join(directory, files_name)
            await message.client.download_media(
                message=response,
                file_name=deep_fry)
            await message.client.send_sticker(
                message.chat.id,
                sticker=deep_fry,
                reply_to_message_id=message_id,
            )
    await message.delete()
    for garb in (dls_loc, frying_file, deep_fry):
        if garb and os.path.exists(garb):
            os.remove(garb)
示例#27
0
async def kang_(message: Message):
    """ kang a sticker """
    user = await userge.get_me()
    if not user.username:
        user.username = user.first_name or user.id
    replied = message.reply_to_message
    photo = None
    emoji = None
    is_anim = False
    resize = False
    if replied and replied.media:
        if replied.photo:
            resize = True
        elif replied.document and "image" in replied.document.mime_type:
            resize = True
        elif replied.document and "tgsticker" in replied.document.mime_type:
            is_anim = True
        elif replied.sticker:
            emoji = replied.sticker.emoji
            is_anim = replied.sticker.is_animated
            if not replied.sticker.file_name.endswith('.tgs'):
                resize = True
        else:
            await message.edit("`Unsupported File!`")
            return
        await message.edit(f"`{random.choice(KANGING_STR)}`")
        photo = await userge.download_media(message=replied,
                                            file_name=Config.DOWN_PATH)
    else:
        await message.edit("`I can't kang that...`")
        return
    if photo:
        args = message.input_str.split()
        if not emoji:
            emoji = "🤔"
        pack = 1
        if len(args) == 2:
            emoji, pack = args
        elif len(args) == 1:
            if args[0].isnumeric():
                pack = int(args[0])
            else:
                emoji = args[0]
        packname = f"a{user.id}_by_{user.username}_{pack}"
        packnick = f"@{user.username}'s kang pack Vol.{pack}"
        cmd = '/newpack'
        if resize:
            photo = resize_photo(photo)
        if is_anim:
            packname += "_anim"
            packnick += " (Animated)"
            cmd = '/newanimated'

        @pool.run_in_thread
        def get_response():
            response = urllib.request.urlopen(  # nosec
                urllib.request.Request(f'http://t.me/addstickers/{packname}'))
            return response.read().decode("utf8").split('\n')
        htmlstr = await get_response()
        if ("  A <strong>Telegram</strong> user has created "
                "the <strong>Sticker&nbsp;Set</strong>.") not in htmlstr:
            async with userge.conversation('Stickers', limit=30) as conv:
                try:
                    await conv.send_message('/addsticker')
                except YouBlockedUser:
                    await message.edit('first **unblock** @Stickers')
                    return
                await conv.get_response(mark_read=True)
                await conv.send_message(packname)
                msg = await conv.get_response(mark_read=True)
                limit = "50" if is_anim else "120"
                while limit in msg.text:
                    pack += 1
                    packname = f"a{user.id}_by_{user.username}_{pack}"
                    packnick = f"@{user.username}'s kang pack Vol.{pack}"
                    await message.edit("`Switching to Pack " + str(pack) +
                                       " due to insufficient space`")
                    await conv.send_message(packname)
                    msg = await conv.get_response(mark_read=True)
                    if msg.text == "Invalid pack selected.":
                        await conv.send_message(cmd)
                        await conv.get_response(mark_read=True)
                        await conv.send_message(packnick)
                        await conv.get_response(mark_read=True)
                        await conv.send_document(photo)
                        await conv.get_response(mark_read=True)
                        await conv.send_message(emoji)
                        await conv.get_response(mark_read=True)
                        await conv.send_message("/publish")
                        if is_anim:
                            await conv.get_response(mark_read=True)
                            await conv.send_message(f"<{packnick}>")
                        await conv.get_response(mark_read=True)
                        await conv.send_message("/skip")
                        await conv.get_response(mark_read=True)
                        await conv.send_message(packname)
                        await conv.get_response(mark_read=True)
                        await message.edit(
                            f"`Sticker added in a Different Pack !\n"
                            "This Pack is Newly created!\n"
                            f"Your pack can be found [here](t.me/addstickers/{packname})")
                        return
                await conv.send_document(photo)
                rsp = await conv.get_response(mark_read=True)
                if "Sorry, the file type is invalid." in rsp.text:
                    await message.edit("`Failed to add sticker, use` @Stickers "
                                       "`bot to add the sticker manually.`")
                    return
                await conv.send_message(emoji)
                await conv.get_response(mark_read=True)
                await conv.send_message('/done')
                await conv.get_response(mark_read=True)
        else:
            await message.edit("`Brewing a new Pack...`")
            async with userge.conversation('Stickers') as conv:
                try:
                    await conv.send_message(cmd)
                except YouBlockedUser:
                    await message.edit('first **unblock** @Stickers')
                    return
                await conv.get_response(mark_read=True)
                await conv.send_message(packnick)
                await conv.get_response(mark_read=True)
                await conv.send_document(photo)
                rsp = await conv.get_response(mark_read=True)
                if "Sorry, the file type is invalid." in rsp.text:
                    await args.edit("`Failed to add sticker, use` @Stickers "
                                    "`bot to add the sticker manually.`")
                    return
                await conv.send_message(emoji)
                await conv.get_response(mark_read=True)
                await conv.send_message("/publish")
                if is_anim:
                    await conv.get_response(mark_read=True)
                    await conv.send_message(f"<{packnick}>")
                await conv.get_response(mark_read=True)
                await conv.send_message("/skip")
                await conv.get_response(mark_read=True)
                await conv.send_message(packname)
                await conv.get_response(mark_read=True)
        await message.edit(f"`Sticker kanged successfully!`\n"
                           f"Pack can be found [here](t.me/addstickers/{packname})")
        if os.path.exists(str(photo)):
            os.remove(photo)
示例#28
0
async def _insta_post_downloader(message: Message):
    """ download instagram post """
    await message.edit("`Setting up Configs. Please don't flood.`")
    dirname = "instadl_{target}"
    filename = "{target}'s_post"
    insta = Instaloader(
        dirname_pattern=dirname,
        filename_pattern=filename,
        download_video_thumbnails=False,
        download_geotags=False,
        download_comments=False,
        save_metadata=False,
        compress_json=False,
    )
    if Config.INSTA_ID and Config.INSTA_PASS:
        # try login
        try:
            insta.load_session_from_file(Config.INSTA_ID)
            await message.edit("`Logged in with current Session`")
        except FileNotFoundError:
            await message.edit("`Login required. Trying to login`")
            try:
                insta.login(Config.INSTA_ID, Config.INSTA_PASS)
            except InvalidArgumentException:
                await message.err("Provided `INSTA_ID` is incorrect")
                return
            except BadCredentialsException:
                await message.err("Provided `INSTA_PASS` is incorrect")
                return
            except ConnectionException:
                await message.err(
                    "Instagram refused to connect. Try again later or never"
                    " (your choice)😒")
                return
            # This is a nightmare.
            except TwoFactorAuthRequiredException:
                # Send a promt for 2FA code in saved messages
                chat_type = ("Saved Messages" if message.from_user.is_self else
                             "Private Message")
                text = ("[<b>2 Factor Authentication Detected</b>]\n"
                        f"I have sent a message to {chat_type}. "
                        "Please continue there and send your 2FA code.")
                await message.edit(text)
                for _ in range(4):
                    # initial convo with the user who sent message in pm.
                    # if user is_self convo in saved messages
                    # else in pm of sudo user
                    async with userge.conversation(
                            message.from_user.id) as asker:
                        asked = await asker.send_message(
                            "Please reply me with your 2FA code `int`")
                        response = await asker.get_response(mark_read=True)
                        if not (response.reply_to_message
                                and response.reply_to_message.is_self):
                            # I said reply me.
                            continue
                        code = response.text
                        if not (code.isdigit() and len(code) == 6):
                            # the six digit code
                            # What else it has always been a six digit code.
                            continue
                        try:
                            insta.two_factor_login(code)
                            break
                        except BadCredentialsException as b_c_e:
                            await asked.err(b_c_e)
                        except InvalidArgumentException:
                            await asked.edit("`No pending Login Found`")
                            return
            else:
                try:
                    insta.save_session_to_file()
                except LoginRequiredException:
                    await message.err(
                        "Failed to save session file, probably due to invalid login."
                    )
                    await asyncio.sleep(5)
    else:
        await message.edit(
            "Login Credentials not found.\n`[NOTE]`: "
            "**You may not be able to download private contents or so**")
        await asyncio.sleep(2)

    p = r"^https:\/\/www\.instagram\.com\/(p|tv|reel)\/([A-Za-z0-9\-_]*)\/(\?igshid=[a-zA-Z0-9]*)?$"
    match = re.search(p, message.input_str)

    if "-u" in message.flags:
        username = message.filtered_input_str
        sent = await message.edit(f"`Fetching all posts of {username}`")
        profile = await get_profile(insta, username)
        limit = int(message.flags.get("-l", 0))
        count = 0
        for post in await get_profile_posts(profile):
            count += 1
            if message.process_is_canceled:
                await sent.edit("Post Download Interrupted...")
                await asyncio.sleep(5)
                break
            try:
                await download_post(insta, post)
                await upload_to_tg(message,
                                   dirname.format(target=post.owner_username),
                                   post)
            except FloodWait as f_w:
                await asyncio.sleep(f_w.x + 10)
                await upload_to_tg(message,
                                   dirname.format(target=post.owner_username),
                                   post)
            except (KeyError, LoginRequiredException):
                await message.err("Private Content Login Required")
                return
            finally:
                shutil.rmtree(dirname.format(target=post.owner_username),
                              ignore_errors=True)
            if limit > 0 and count == limit:
                break
        await sent.delete()
    elif match:
        dtypes = {"p": "POST", "tv": "IGTV", "reel": "REELS"}
        d_t = dtypes.get(match.group(1))
        if not d_t:
            await message.err("Unsupported Format")
            return
        sent = await message.edit(f"`Fetching {d_t} Content.`")
        shortcode = match.group(2)
        post = await get_post(insta, shortcode)
        try:
            await download_post(insta, post)
            await upload_to_tg(message,
                               dirname.format(target=post.owner_username),
                               post)
        except (KeyError, LoginRequiredException):
            await message.err("Post is private. Login and try again")
            return
        except FloodWait as f_w:
            await asyncio.sleep(f_w.x + 5)
            await upload_to_tg(message,
                               dirname.format(target=post.owner_username),
                               post)
        finally:
            shutil.rmtree(dirname.format(target=post.owner_username),
                          ignore_errors=True)
        await sent.delete()
    else:
        await message.err("`Invalid Input`")
示例#29
0
async def kang_(message: Message):
    """ kang a sticker """
    user = await userge.get_me()
    replied = message.reply_to_message
    photo = None
    emoji_ = None
    is_anim = False
    resize = False
    if replied and replied.media:
        if replied.photo:
            resize = True
        elif replied.document and "image" in replied.document.mime_type:
            resize = True
        elif replied.document and "tgsticker" in replied.document.mime_type:
            is_anim = True
        elif replied.sticker:
            if not replied.sticker.file_name:
                await message.edit("`Sticker has no Name!`")
                return
            emoji_ = replied.sticker.emoji
            is_anim = replied.sticker.is_animated
            if not replied.sticker.file_name.endswith(".tgs"):
                resize = True
        else:
            await message.edit("`Unsupported File!`")
            return
        await message.edit(f"`{random.choice(KANGING_STR)}`")
        photo = await userge.download_media(message=replied,
                                            file_name=Config.DOWN_PATH)
    else:
        await message.edit("`I can't kang that...`")
        return
    if photo:
        args = message.filtered_input_str.split()
        pack = 1
        if len(args) == 2:
            emoji_, pack = args
        elif len(args) == 1:
            if args[0].isnumeric():
                pack = int(args[0])
            else:
                emoji_ = args[0]

        if emoji_ and emoji_ not in emoji.UNICODE_EMOJI:
            emoji_ = None
        if not emoji_:
            emoji_ = "🤔"

        u_name = user.username
        u_name = "@" + u_name if u_name else user.first_name or user.id
        packname = f"a{user.id}_by_userge_{pack}"
        custom_packnick = Config.CUSTOM_PACK_NAME or f"{u_name}'s kang pack"
        packnick = f"{custom_packnick} Vol.{pack}"
        cmd = "/newpack"
        if resize:
            photo = resize_photo(photo)
        if is_anim:
            packname += "_anim"
            packnick += " (Animated)"
            cmd = "/newanimated"
        async with aiohttp.ClientSession() as ses:
            async with ses.get(f"http://t.me/addstickers/{packname}") as res:
                htmlstr = (await res.text()).split("\n")
        if ("  A <strong>Telegram</strong> user has created "
                "the <strong>Sticker&nbsp;Set</strong>.") not in htmlstr:
            async with userge.conversation("Stickers", limit=30) as conv:
                try:
                    await conv.send_message("/addsticker")
                except YouBlockedUser:
                    await message.edit("first **unblock** @Stickers")
                    return
                await conv.get_response(mark_read=True)
                await conv.send_message(packname)
                msg = await conv.get_response(mark_read=True)
                limit = "50" if is_anim else "120"
                while limit in msg.text:
                    pack += 1
                    packname = f"a{user.id}_by_userge_{pack}"
                    packnick = f"{custom_packnick} Vol.{pack}"
                    if is_anim:
                        packname += "_anim"
                        packnick += " (Animated)"
                    await message.edit("`Switching to Pack " + str(pack) +
                                       " due to insufficient space`")
                    await conv.send_message(packname)
                    msg = await conv.get_response(mark_read=True)
                    if msg.text == "Invalid pack selected.":
                        await conv.send_message(cmd)
                        await conv.get_response(mark_read=True)
                        await conv.send_message(packnick)
                        await conv.get_response(mark_read=True)
                        await conv.send_document(photo)
                        await conv.get_response(mark_read=True)
                        await conv.send_message(emoji_)
                        await conv.get_response(mark_read=True)
                        await conv.send_message("/publish")
                        if is_anim:
                            await conv.get_response(mark_read=True)
                            await conv.send_message(f"<{packnick}>")
                        await conv.get_response(mark_read=True)
                        await conv.send_message("/skip")
                        await conv.get_response(mark_read=True)
                        await conv.send_message(packname)
                        await conv.get_response(mark_read=True)
                        if "-d" in message.flags:
                            await message.delete()
                        else:
                            out = ("__kanged__" if "-s" in message.flags else
                                   f"[kanged](t.me/addstickers/{packname})")
                            await message.edit(
                                f"**Sticker** {out} __in a Different Pack__**!**"
                            )
                        return
                await conv.send_document(photo)
                rsp = await conv.get_response(mark_read=True)
                if "Sorry, the file type is invalid." in rsp.text:
                    await message.edit(
                        "`Failed to add sticker, use` @Stickers "
                        "`bot to add the sticker manually.`")
                    return
                await conv.send_message(emoji_)
                await conv.get_response(mark_read=True)
                await conv.send_message("/done")
                await conv.get_response(mark_read=True)
        else:
            await message.edit("`Brewing a new Pack...`")
            async with userge.conversation("Stickers") as conv:
                try:
                    await conv.send_message(cmd)
                except YouBlockedUser:
                    await message.edit("first **unblock** @Stickers")
                    return
                await conv.get_response(mark_read=True)
                await conv.send_message(packnick)
                await conv.get_response(mark_read=True)
                await conv.send_document(photo)
                rsp = await conv.get_response(mark_read=True)
                if "Sorry, the file type is invalid." in rsp.text:
                    await message.edit(
                        "`Failed to add sticker, use` @Stickers "
                        "`bot to add the sticker manually.`")
                    return
                await conv.send_message(emoji_)
                await conv.get_response(mark_read=True)
                await conv.send_message("/publish")
                if is_anim:
                    await conv.get_response(mark_read=True)
                    await conv.send_message(f"<{packnick}>")
                await conv.get_response(mark_read=True)
                await conv.send_message("/skip")
                await conv.get_response(mark_read=True)
                await conv.send_message(packname)
                await conv.get_response(mark_read=True)
        if "-d" in message.flags:
            await message.delete()
        else:
            out = ("__kanged__" if "-s" in message.flags else
                   f"[kanged](t.me/addstickers/{packname})")
            await message.edit(f"**Sticker** {out}**!**")
        if os.path.exists(str(photo)):
            os.remove(photo)
示例#30
0
async def kang_(message: Message):
    """ Stikır dızla """
    user = await userge.get_me()
    replied = message.reply_to_message
    photo = None
    emoji_ = None
    is_anim = False
    resize = False
    if replied and replied.media:
        if replied.photo:
            resize = True
        elif replied.document and "image" in replied.document.mime_type:
            resize = True
        elif replied.document and "tgsticker" in replied.document.mime_type:
            is_anim = True
        elif replied.sticker:
            if not replied.sticker.file_name:
                await message.edit("`Çıkartmanın adı yok!`")
                return
            emoji_ = replied.sticker.emoji
            is_anim = replied.sticker.is_animated
            if not replied.sticker.file_name.endswith('.tgs'):
                resize = True
        else:
            await message.edit("`Desteklenmeyen dosya!`")
            return
        await message.edit(f"`{random.choice(KANGING_STR)}`")
        photo = await userge.download_media(message=replied,
                                            file_name=Config.DOWN_PATH)
    else:
        await message.edit("`Bunu Dızlayamam...`")
        return
    if photo:
        args = message.input_str.split()
        pack = 1
        if len(args) == 2:
            emoji_, pack = args
        elif len(args) == 1:
            if args[0].isnumeric():
                pack = int(args[0])
            else:
                emoji_ = args[0]

        if emoji_ and emoji_ not in emoji.UNICODE_EMOJI:
            emoji_ = None
        if not emoji_:
            emoji_ = "🤔"

        u_name = user.username
        u_name = "@" + u_name if u_name else user.first_name or user.id
        packname = f"a{user.id}_by_userge_{pack}"
        custom_packnick = Config.CUSTOM_PACK_NAME or f"{u_name}'s kang pack"
        packnick = f"{custom_packnick} Vol.{pack}"
        cmd = '/newpack'
        if resize:
            photo = resize_photo(photo)
        if is_anim:
            packname += "_anim"
            packnick += " (Animated)"
            cmd = '/newanimated'
        async with aiohttp.ClientSession() as ses:
            async with ses.get(f'http://t.me/addstickers/{packname}') as res:
                htmlstr = (await res.text()).split('\n')
        if ("  A <strong>Telegram</strong> user has created "
                "the <strong>Sticker&nbsp;Set</strong>.") not in htmlstr:
            async with userge.conversation('Stickers', limit=30) as conv:
                try:
                    await conv.send_message('/addsticker')
                except YouBlockedUser:
                    await message.edit('first **unblock** @Stickers')
                    return
                await conv.get_response(mark_read=True)
                await conv.send_message(packname)
                msg = await conv.get_response(mark_read=True)
                limit = "50" if is_anim else "120"
                while limit in msg.text:
                    pack += 1
                    packname = f"a{user.id}_by_userge_{pack}"
                    packnick = f"{custom_packnick} Vol.{pack}"
                    if is_anim:
                        packname += "_anim"
                        packnick += " (Animated)"
                    await message.edit("`Switching to Pack " + str(pack) +
                                       " due to insufficient space`")
                    await conv.send_message(packname)
                    msg = await conv.get_response(mark_read=True)
                    if msg.text == "Invalid pack selected.":
                        await conv.send_message(cmd)
                        await conv.get_response(mark_read=True)
                        await conv.send_message(packnick)
                        await conv.get_response(mark_read=True)
                        await conv.send_document(photo)
                        await conv.get_response(mark_read=True)
                        await conv.send_message(emoji_)
                        await conv.get_response(mark_read=True)
                        await conv.send_message("/publish")
                        if is_anim:
                            await conv.get_response(mark_read=True)
                            await conv.send_message(f"<{packnick}>")
                        await conv.get_response(mark_read=True)
                        await conv.send_message("/skip")
                        await conv.get_response(mark_read=True)
                        await conv.send_message(packname)
                        await conv.get_response(mark_read=True)
                        await message.edit(
                            f"`Sticker added in a Different Pack !\n"
                            "This Pack is Newly created!\n"
                            f"Your pack can be found [here](t.me/addstickers/{packname})"
                        )
                        return
                await conv.send_document(photo)
                rsp = await conv.get_response(mark_read=True)
                if "Sorry, the file type is invalid." in rsp.text:
                    await message.edit(
                        "`Failed to add sticker, use` @Stickers "
                        "`bot to add the sticker manually.`")
                    return
                await conv.send_message(emoji_)
                await conv.get_response(mark_read=True)
                await conv.send_message('/done')
                await conv.get_response(mark_read=True)
        else:
            await message.edit("`Brewing a new Pack...`")
            async with userge.conversation('Stickers') as conv:
                try:
                    await conv.send_message(cmd)
                except YouBlockedUser:
                    await message.edit('first **unblock** @Stickers')
                    return
                await conv.get_response(mark_read=True)
                await conv.send_message(packnick)
                await conv.get_response(mark_read=True)
                await conv.send_document(photo)
                rsp = await conv.get_response(mark_read=True)
                if "Sorry, the file type is invalid." in rsp.text:
                    await message.edit(
                        "`Failed to add sticker, use` @Stickers "
                        "`bot to add the sticker manually.`")
                    return
                await conv.send_message(emoji_)
                await conv.get_response(mark_read=True)
                await conv.send_message("/publish")
                if is_anim:
                    await conv.get_response(mark_read=True)
                    await conv.send_message(f"<{packnick}>")
                await conv.get_response(mark_read=True)
                await conv.send_message("/skip")
                await conv.get_response(mark_read=True)
                await conv.send_message(packname)
                await conv.get_response(mark_read=True)
        await message.edit(
            f"**Stikır dızlandı** [Burada](t.me/addstickers/{packname}) **Bulabilirsin!**"
        )
        if os.path.exists(str(photo)):
            os.remove(photo)