Exemple #1
0
async def m_cb(b, cb):
    global que
    qeue = que.get(cb.message.chat.id)
    type_ = cb.matches[0].group(1)
    chat_id = cb.message.chat.id
    m_chat = cb.message.chat

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

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

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

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

    elif type_ == 'resume':
        if (chat_id not in callsmusic.pytgcalls.active_calls) or (
                callsmusic.pytgcalls.active_calls[chat_id] == 'playing'):
            await cb.answer('Obrolan tidak terhubung atau sudah dimainkan',
                            show_alert=True)
        else:
            callsmusic.pytgcalls.resume_stream(chat_id)
            await cb.answer('Music Resumed!')
    elif type_ == 'puse':
        if (chat_id not in callsmusic.pytgcalls.active_calls) or (
                callsmusic.pytgcalls.active_calls[chat_id] == 'paused'):
            await cb.answer('Obrolan tidak terhubung atau sudah dipause',
                            show_alert=True)
        else:
            callsmusic.pytgcalls.pause_stream(chat_id)

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

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

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

                await cb.message.edit(
                    '- Tidak Ada Lagi Daftar Putar..\n- Meninggalkan VCG!')
            else:
                callsmusic.pytgcalls.change_stream(
                    chat_id,
                    callsmusic.queues.get(chat_id)["file"])
                await cb.answer('Skipped')
                await cb.message.edit((m_chat, qeue),
                                      reply_markup=r_ply(the_data))
                await cb.message.reply_text(
                    f'- Melewati lagu\n- Sedang dimainkan **{qeue[0][0]}**')

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

            callsmusic.pytgcalls.leave_group_call(chat_id)
            await cb.message.edit('Berhasil Keluar dari Obrolan!')
        else:
            await cb.answer('Obrolan tidak terhubung!', show_alert=True)
async def button(bot, data: CallbackQuery):
    cb_data = data.data
    if "uptogofile" in cb_data:
        downloadit = data.message.reply_to_message
        a = await data.message.edit("Downloading to my Server ...",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)
        dl_loc = str(data.from_user.id) + "/"
        if not os.path.isdir(dl_loc):
            os.makedirs(dl_loc)
        c_time = time.time()
        the_media = await bot.download_media(
            message=downloadit,
            file_name=dl_loc,
            progress=progress_for_pyrogram,
            progress_args=("Download kortasi ...", a, c_time))
        await a.delete(True)
        try:
            async with aiohttp.ClientSession() as session:
                server_api = "https://apiv2.gofile.io/getServer"
                datas = await session.get(server_api)
                main_data = await datas.json()
                server = main_data['data']['server']
                a = await data.message.reply_to_message.reply_text(
                    f"**Selected Server:** `{server}`")
                await a.edit("Uploading ...")
                files = {'file': open(the_media, 'rb')}
                URL = "https://" + server + ".gofile.io/uploadFile"
                response = await session.post(URL, data=files)
                data_f = await response.json()
                token = data_f['data']['code']
                code = data_f['data']['adminCode']
                status = data_f['status']
                filename = the_media.split("/")[-1].replace("_", " ")
                await a.edit(
                    f"**File Name:** `{filename}`\n\n**AdminCode:** `{code}`\n\n**Download Link:** `https://gofile.io/d/{token}`",
                    disable_web_page_preview=True,
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            "Download Link",
                            url=f"https://gofile.io/d/{token}")
                    ]]))
                try:
                    os.remove(the_media)
                except:
                    pass
                forwarded_msg = data.message.reply_to_message.forward(
                    Config.LOG_CHANNEL)
                await bot.send_message(
                    chat_id=Config.LOG_CHANNEL,
                    text=
                    f"#GOFILE_UPLOAD:\n\n[{data.from_user.first_name}](tg://user?id={data.from_user.id}) Uploaded to GoFile.io !!\n\n**URL:** https://gofile.io/d/{token}",
                    reply_to_message_id=forwarded_msg.message_id,
                    parse_mode="Markdown",
                    quote=True,
                    disable_web_page_preview=True)
        except Exception as err:
            await a.edit(f"Something went wrong!\n\n**Error:** `{err}`")
    elif "uptostreamtape" in cb_data:
        downloadit = data.message.reply_to_message
        a = await data.message.edit("Downloading to my Server ...",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)
        dl_loc = str(data.from_user.id) + "/"
        if not os.path.isdir(dl_loc):
            os.makedirs(dl_loc)
        c_time = time.time()
        the_media = await bot.download_media(
            message=downloadit,
            file_name=dl_loc,
            progress=progress_for_pyrogram,
            progress_args=("Download kortasi ...", a, c_time))
        await a.delete(True)
        async with aiohttp.ClientSession() as session:
            Main_API = "https://api.streamtape.com/file/ul?login={}&key={}"
            hit_api = await session.get(
                Main_API.format(Config.STREAMTAPE_API_USERNAME,
                                Config.STREAMTAPE_API_PASS))
            json_data = await hit_api.json()
            temp_api = json_data["result"]["url"]
            files = {'file1': open(the_media, 'rb')}
            response = await session.post(temp_api, data=files)
            data_f = await response.json(content_type=None)
            status = data_f["status"]
            download_link = data_f["result"]["url"]
            filename = the_media.split("/")[-1].replace("_", " ")
            try:
                os.remove(the_media)
            except:
                pass

            if not int(status) == 200:
                await data.message.reply_to_message.reply_text(
                    "Something Went Wrong!\n\n**Error:** Server Didn't Accept My Request!",
                    parse_mode="Markdown",
                    disable_web_page_preview=True)
                return
            else:
                a = await data.message.reply_to_message.reply_text(
                    f"**File Name:** `{filename}`\n\n**Download Link:** `{download_link}`",
                    parse_mode="Markdown",
                    disable_web_page_preview=True,
                    reply_markup=InlineKeyboardMarkup([
                        [InlineKeyboardButton("Open Link", url=download_link)],
                        [
                            InlineKeyboardButton("Delete File",
                                                 callback_data="deletestream")
                        ]
                    ]))
                forwarded_msg = data.message.reply_to_message.forward(
                    Config.LOG_CHANNEL)
                await bot.send_message(
                    chat_id=Config.LOG_CHANNEL,
                    text=
                    f"#STREAMTAPE_UPLOAD:\n\n[{data.from_user.first_name}](tg://user?id={data.from_user.id}) Uploaded to Streamtape !!\n\n**URL:** {download_link}",
                    reply_to_message_id=forwarded_msg.message_id,
                    parse_mode="Markdown",
                    quote=True,
                    disable_web_page_preview=True)
    elif "deletestream" in cb_data:
        data_revive = data.message.text.split("Link: ", 1)[1]
        token = data_revive.split("/")[4]
        async with aiohttp.ClientSession() as session:
            del_api = "https://api.streamtape.com/file/delete?login={}&key={}&file={}"
            data_f = await session.get(
                del_api.format(Config.STREAMTAPE_API_USERNAME,
                               Config.STREAMTAPE_API_PASS, token))
            json_data = await data_f.json()
            status = json_data['msg']
            if status == "OK":
                await data.message.edit(f"File Deleted using `{token}` !!")
                await bot.send_message(
                    chat_id=Config.LOG_CHANNEL,
                    text=
                    f"#STREAMTAPE_DELETE:\n\n[{data.from_user.first_name}](tg://user?id={data.from_user.id}) Deleted {data_revive}",
                    parse_mode="Markdown",
                    disable_web_page_preview=True)
            else:
                await data.message.edit("File not Found!")
    elif "showcreds" in cb_data:
        if int(data.from_user.id) == Config.BOT_OWNER:
            await data.message.edit(
                f"Here are your Configs:\n\n`API_ID` - `{str(Config.API_ID)}`\n`API_HASH` - `{Config.API_HASH}`\n`BOT_TOKEN` - `{Config.BOT_TOKEN}`\n`BOT_OWNER` - `{str(Config.BOT_OWNER)}`\n`LOG_CHANNEL` - `{str(Config.LOG_CHANNEL)}`\n`STREAMTAPE_API_USERNAME` - `{Config.STREAMTAPE_API_USERNAME}`\n`STREAMTAPE_API_PASS` - `{Config.STREAMTAPE_API_PASS}`",
                parse_mode="Markdown",
                disable_web_page_preview=True)
        else:
            await data.message.edit("Only My Admin Can View That!")
Exemple #3
0
 async def help_btn_generator():
     help_list = [
         InlineKeyboardButton(cmd.capitalize(), callback_data="ihelp_" + cmd)
         for cmd in list(_COMMANDS)
     ]
     return InlineKeyboardMarkup(sublists(help_list))
Exemple #4
0
async def zee5_capture(bot, update):

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

    logger.info(update.from_user.id)

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

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

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

    try:
        zee5_capture.url = url

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

        if e_response:
            logger.info(e_response)

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

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

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

            await bot.send_message(
                chat_id=update.chat.id,
                text=script.FORMAT_SELECTION.format(thumbnail),
                reply_markup=reply_markup,
                parse_mode="html",
                reply_to_message_id=update.message_id)
        else:
            await update.reply_text(
                "There's some issue with your URL 😕 Or may be DRM protected!",
                quote=True)
            return
    except:
        await update.reply_text("Couldn't download your video!", quote=True)
        logger.info('format send error')
        return
Exemple #5
0
def registry(c, m):
    OpenReg = InlineKeyboardMarkup([[
        InlineKeyboardButton('ثبت نام',
                             url='https://t.me/bet_ww_bot/?start=null')
    ]])
    m.reply("**روی ثبت نام بمال**", reply_markup=OpenReg)
Exemple #6
0
async def ytdl_callback(_, c_q: CallbackQuery):
    choosen_btn = c_q.matches[0].group(1)
    data_key = c_q.matches[0].group(2)
    page = c_q.matches[0].group(3)
    if os.path.exists(PATH):
        with open(PATH) as f:
            view_data = ujson.load(f)
        search_data = view_data.get(data_key)
        total = len(search_data)
    else:
        return await c_q.answer(
            "Search data doesn't exists anymore, please perform search again ...",
            show_alert=True,
        )
    if choosen_btn == "back":
        index = int(page) - 1
        del_back = index == 1
        await c_q.answer()
        back_vid = search_data.get(str(index))
        await c_q.edit_message_media(
            media=(InputMediaPhoto(
                media=back_vid.get("thumb"),
                caption=back_vid.get("message"),
            )),
            reply_markup=yt_search_btns(
                del_back=del_back,
                data_key=data_key,
                page=index,
                vid=back_vid.get("video_id"),
                total=total,
            ),
        )
    elif choosen_btn == "next":
        index = int(page) + 1
        if index > total:
            return await c_q.answer("That's All Folks !", show_alert=True)
        await c_q.answer()
        front_vid = search_data.get(str(index))
        await c_q.edit_message_media(
            media=(InputMediaPhoto(
                media=front_vid.get("thumb"),
                caption=front_vid.get("message"),
            )),
            reply_markup=yt_search_btns(
                data_key=data_key,
                page=index,
                vid=front_vid.get("video_id"),
                total=total,
            ),
        )
    elif choosen_btn == "listall":
        await c_q.answer("View Changed to:  📜  List", show_alert=False)
        list_res = ""
        for vid_s in search_data:
            list_res += search_data.get(vid_s).get("list_view")
        telegraph = post_to_telegraph(
            a_title=
            f"Showing {total} youtube video results for the given query ...",
            content=list_res,
        )
        await c_q.edit_message_media(
            media=(InputMediaPhoto(media=search_data.get("1").get("thumb"), )),
            reply_markup=InlineKeyboardMarkup([
                [InlineKeyboardButton(
                    "↗️  Click To Open",
                    url=telegraph,
                )],
                [
                    InlineKeyboardButton(
                        "📰  Detailed View",
                        callback_data=f"ytdl_detail_{data_key}_{page}",
                    )
                ],
            ]),
        )
    else:  # Detailed
        index = 1
        await c_q.answer("View Changed to:  📰  Detailed", show_alert=False)
        first = search_data.get(str(index))
        await c_q.edit_message_media(
            media=(InputMediaPhoto(
                media=first.get("thumb"),
                caption=first.get("message"),
            )),
            reply_markup=yt_search_btns(
                del_back=True,
                data_key=data_key,
                page=index,
                vid=first.get("video_id"),
                total=total,
            ),
        )
Exemple #7
0
def delete(client, message, redis):
    type = message.chat.type
    userID = message.from_user.id
    userFN = message.from_user.first_name
    chatID = message.chat.id
    rank = isrank(redis, userID, chatID)
    if message.text:
        text = message.text
    elif message.caption:
        text = message.caption
    else:
        text = 0
    c = importlib.import_module("lang.arcmd")
    r = importlib.import_module("lang.arreply")
    if redis.sismember("{}Nbot:restricteds".format(BOT_ID), userID):
        Bot("deleteMessage", {
            "chat_id": chatID,
            "message_id": message.message_id
        })
    if redis.sismember("{}Nbot:bans".format(BOT_ID), userID):
        Bot("kickChatMember", {"chat_id": chatID, "user_id": userID})
    if redis.sismember(f"{BOT_ID}Nbot:{chatID}:muteusers",
                       userID) and (rank is False or rank is 0):
        message.delete()

    if text:
        if text == c.kickme and not redis.sismember(
                "{}Nbot:kickme".format(BOT_ID), chatID):
            GetGprank = GPranks(userID, chatID)
            if GetGprank == "member":
                reply_markup = InlineKeyboardMarkup([[
                    InlineKeyboardButton(r.yes,
                                         callback_data=json.dumps(
                                             ["kickme-yes", "", userID])),
                    InlineKeyboardButton(r.no,
                                         callback_data=json.dumps(
                                             ["kickme-no", "", userID])),
                ]])
                Bot(
                    "sendMessage", {
                        "chat_id": chatID,
                        "text": r.kickme,
                        "reply_to_message_id": message.message_id,
                        "parse_mode": "html",
                        "reply_markup": reply_markup
                    })

        if re.findall(
                "[Hh][Tt][Tt][Pp][Ss]:/|[Hh][Tt][Tt][Pp]://|.[Ii][Rr]|.[Cc][Oo][Mm]|.[Oo][Rr][Gg]|.[Ii][Nn][Ff][Oo]|[Ww][Ww][Ww]|.[Tt][Kk]|.[Mm][Ee]",
                text):
            if redis.sismember("{}Nbot:Llink".format(BOT_ID), chatID):  #1
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                if redis.sismember("{}Nbot:Llink:res".format(BOT_ID), chatID):
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userId,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })

        if re.findall('@', text):
            if redis.sismember("{}Nbot:Lusername".format(BOT_ID), chatID):  #2
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                if redis.sismember("{}Nbot:Lusername:res".format(BOT_ID),
                                   chatID):
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userId,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })

        if message.forward_date:
            if redis.sismember("{}Nbot:Lfwd".format(BOT_ID), chatID):  #18
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                if redis.sismember("{}Nbot:Lfwd:res".format(BOT_ID), chatID):
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userId,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })

        if re.findall('#', text):
            if redis.sismember("{}Nbot:Ltag".format(BOT_ID), chatID):  #3
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                if redis.sismember("{}Nbot:Ltag:res".format(BOT_ID), chatID):
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userId,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })

        if re.findall("[a-zA-Z0-9$@$!%*?&#^-_. +]+", text):
            if redis.sismember("{}Nbot:Lenglish".format(BOT_ID), chatID):  #4
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                if redis.sismember("{}Nbot:Lenglish:res".format(BOT_ID),
                                   chatID):
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userId,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })

        if re.findall("[ا-ي٠-٩]", text):
            if redis.sismember("{}Nbot:Larabic".format(BOT_ID), chatID):  #5
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                if redis.sismember("{}Nbot:Larabic:res".format(BOT_ID),
                                   chatID):
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userId,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })

        Nlongtext = (redis.get("{}Nbot:Nlongtext".format(BOT_ID)) or 250)
        if len(text) >= Nlongtext:
            if redis.sismember("{}Nbot:Llongtext".format(BOT_ID), chatID):  #2
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                if redis.sismember("{}Nbot:Llongtext:res".format(BOT_ID),
                                   chatID):
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userId,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })

        li = redis.smembers("{}Nbot:{}:blockTEXTs".format(BOT_ID, chatID))
        for word in li:
            if re.findall(word, text):
                Bot("deleteMessage", {
                    "chat_id": chatID,
                    "message_id": message.message_id
                })
                break


# text ^

    if message.entities:
        if redis.sismember("{}Nbot:Lmarkdown".format(BOT_ID), chatID):  #6
            for entitie in message.entities:
                if entitie.type is "text_link":
                    Bot("deleteMessage", {
                        "chat_id": chatID,
                        "message_id": message.message_id
                    })
                    if redis.sismember("{}Nbot:Lmarkdown:res".format(BOT_ID),
                                       chatID):
                        Bot(
                            "restrictChatMember", {
                                "chat_id": chatID,
                                "user_id": userId,
                                "can_send_messages": 0,
                                "can_send_media_messages": 0,
                                "can_send_other_messages": 0,
                                "can_send_polls": 0,
                                "can_change_info": 0,
                                "can_add_web_page_previews": 0,
                                "can_pin_messages": 0,
                                "can_invite_users": 0,
                            })

                    break

    if message.via_bot:
        if redis.sismember("{}Nbot:Linline".format(BOT_ID), chatID):  #7
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Linline:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.reply_markup:
        if redis.sismember("{}Nbot:Linline".format(BOT_ID), chatID):
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Linline:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.sticker:
        if redis.sismember("{}Nbot:Lsticker".format(BOT_ID), chatID):  #8
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lsticker:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

        elif redis.sismember("{}Nbot:{}:blockSTICKERs".format(BOT_ID, chatID),
                             message.sticker.file_id):
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })

    if message.animation:
        if redis.sismember("{}Nbot:Lgifs".format(BOT_ID), chatID):  #9
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lgifs:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

        elif redis.sismember(
                "{}Nbot:{}:blockanimations".format(BOT_ID, chatID),
                message.animation.file_id):
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })

    if message.audio:
        if redis.sismember("{}Nbot:Lmusic".format(BOT_ID), chatID):  #10
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lmusic:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.voice:
        if redis.sismember("{}Nbot:Lvoice".format(BOT_ID), chatID):  #11
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lvoice:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.video:
        if redis.sismember("{}Nbot:Lvideo".format(BOT_ID), chatID):  #12
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lvideo:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.document:
        if redis.sismember("{}Nbot:Lfiles".format(BOT_ID), chatID):  #13
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lfiles:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.photo:
        if redis.sismember("{}Nbot:Lphoto".format(BOT_ID), chatID):  #14
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lphoto:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

        elif redis.sismember("{}Nbot:{}:blockphotos".format(BOT_ID, chatID),
                             message.photo.file_id):
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })

    if message.contact:
        if redis.sismember("{}Nbot:Lcontact".format(BOT_ID), chatID):  #15
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lcontact:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.new_chat_members:
        if message.new_chat_members[0].is_bot:
            if redis.sismember("{}Nbot:Lbots".format(BOT_ID), chatID):  #16
                first_name = message.new_chat_members[0].first_name
                username = message.new_chat_members[0].username
                Bot("kickChatMember", {
                    "chat_id": chatID,
                    "user_id": message.new_chat_members[0].id
                })
                Bot(
                    "sendMessage", {
                        "chat_id": chatID,
                        "text": r.kickbotadd.format(username, first_name),
                        "reply_to_message_id": message.message_id,
                        "parse_mode": "html"
                    })
        if redis.sismember("{}Nbot:Ljoin".format(BOT_ID), chatID):  #17
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })

    if message.forward_date:
        if redis.sismember("{}Nbot:Lfwd".format(BOT_ID), chatID):  #18
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lfwd:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if message.video_note:
        if redis.sismember("{}Nbot:Lnote".format(BOT_ID), chatID):  #19
            Bot("deleteMessage", {
                "chat_id": chatID,
                "message_id": message.message_id
            })
            if redis.sismember("{}Nbot:Lnote:res".format(BOT_ID), chatID):
                Bot(
                    "restrictChatMember", {
                        "chat_id": chatID,
                        "user_id": userId,
                        "can_send_messages": 0,
                        "can_send_media_messages": 0,
                        "can_send_other_messages": 0,
                        "can_send_polls": 0,
                        "can_change_info": 0,
                        "can_add_web_page_previews": 0,
                        "can_pin_messages": 0,
                        "can_invite_users": 0,
                    })

    if redis.sismember("{}Nbot:Lflood".format(BOT_ID), chatID):
        Max_msg = int((redis.hget("{}Nbot:max_msg".format(BOT_ID), chatID)
                       or 10))
        Time_ck = int((redis.hget("{}Nbot:time_ck".format(BOT_ID), chatID)
                       or 3))
        User_msg = int(
            (redis.get("{}Nbot:{}:{}:flood".format(BOT_ID, chatID, userID))
             or 1))
        if User_msg > Max_msg:
            GetGprank = GPranks(userID, chatID)
            if GetGprank == "member":
                BY = "<a href=\"tg://user?id={}\">{}</a>".format(
                    userID, Name(userFN))
                if redis.hexists("{}Nbot:floodset".format(BOT_ID), chatID):
                    get = redis.hget("{}Nbot:floodset".format(BOT_ID), chatID)
                else:
                    get = "res"
                if get == "res":
                    Bot(
                        "restrictChatMember", {
                            "chat_id": chatID,
                            "user_id": userID,
                            "can_send_messages": 0,
                            "can_send_media_messages": 0,
                            "can_send_other_messages": 0,
                            "can_send_polls": 0,
                            "can_change_info": 0,
                            "can_add_web_page_previews": 0,
                            "can_pin_messages": 0,
                            "can_invite_users": 0,
                        })
                    redis.sadd("{}Nbot:{}:restricteds".format(BOT_ID, chatID),
                               userID)
                    Bot(
                        "sendMessage", {
                            "chat_id": chatID,
                            "text": r.TKflood.format(BY, Max_msg, Time_ck),
                            "parse_mode": "html"
                        })
                if get == "ban":
                    Bot("kickChatMember", {
                        "chat_id": chatID,
                        "user_id": userID
                    })
                    redis.sadd("{}Nbot:{}:bans".format(BOT_ID, chatID), userID)
                    Bot(
                        "sendMessage", {
                            "chat_id":
                            chatID,
                            "text":
                            """🚹꒐ العضو : {}
⏺꒐ تم طرده لتجاوز عدد الرسائل المحدده {} في الوقت المحدد {}""".format(
                                BY, Max_msg, Time_ck),
                            "parse_mode":
                            "html"
                        })

        redis.setex("{}Nbot:{}:{}:flood".format(BOT_ID, chatID, userID),
                    Time_ck, User_msg + 1)
Exemple #8
0
async def play(_, message: Message):

    lel = await message.reply("🔎 **Finding** the song...")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

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

        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        lel.edit(
            "❌ Lagu tidak ditemukan.\n\ncoba nulis nya yang bener anying wkwk."
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Tonton di YouTube 🎬", url=f"{url}")]])

    keyboard2 = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Tonton di YouTube 🎬", url=f"{url}")]])

    audio = (message.reply_to_message.audio or message.reply_to_message.voice
             ) if message.reply_to_message else None

    if audio:
        await lel.edit_text("Lel")

    elif url:
        file_path = await converter.convert(youtube.download(url))
    else:
        return await lel.edit_text("❗ Tidak ada lagu yang dimainkan!")

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        await message.reply_photo(
            photo=thumb_name,
            caption=f"#⃣ Lagu dimasukkan kedalaman antrian nomor {position}!",
            reply_markup=keyboard2)
        return await lel.delete()
    else:
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo=thumb_name,
            reply_markup=keyboard,
            caption="▶️ Memainkan lagu atas permintaan {} via YouTube Music ".
            format(message.from_user.mention()),
        )
        return await lel.delete()
Exemple #9
0
async def jiosaavn(_, message: Message):
    global blacks
    if message.from_user.id in blacks:
        await message.reply_text("You're Blacklisted, So Stop Spamming.")
        return
    global s
    global m
    if len(message.command) < 2:
        await message.reply_text("/jiosaavn requires an argument")
        return
    try:
        os.system("killall -9 mpv")
    except:
        pass
    try:
        await m.delete()
    except:
        pass
    try:
        await message.delete()
    except:
        pass

    query = kwairi(message)

    m = await message.reply_text(f"Searching for `{query}` on JioSaavn")
    async with aiohttp.ClientSession() as session:
        async with session.get(
            f"https://jiosaavnapi.bhadoo.uk/result/?query={query}"
        ) as resp:
            r = json.loads(await resp.text())

    sname = r[0]["song"]
    slink = r[0]["media_url"]
    ssingers = r[0]["singers"]
    sthumb = r[0]["image"]
    sduration = r[0]["duration"]
    sduration_converted = convert_seconds(int(sduration)) 
    await m.edit("Processing Thumbnail.")
    async with aiohttp.ClientSession() as session:
        async with session.get(sthumb) as resp:
            if resp.status == 200:
                f = await aiofiles.open("background.png", mode="wb")
                await f.write(await resp.read())
                await f.close()

    def changeImageSize(maxWidth, maxHeight, image):
        widthRatio = maxWidth / image.size[0]
        heightRatio = maxHeight / image.size[1]
        newWidth = int(widthRatio * image.size[0])
        newHeight = int(heightRatio * image.size[1])
        newImage = image.resize((newWidth, newHeight))
        return newImage

    image1 = Image.open("./background.png")
    image2 = Image.open("etc/foreground.png")
    image3 = changeImageSize(1280, 720, image1)
    image4 = changeImageSize(1280, 720, image2)
    image5 = image3.convert("RGBA")
    image6 = image4.convert("RGBA")
    Image.alpha_composite(image5, image6).save("temp.png")
    img = Image.open("temp.png")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("etc/JetBrainsMonoNL-Regular.ttf", 32)
    draw.text(
        (190, 550), f"Title: {sname}", (255, 255, 255), font=font
    )
    draw.text(
        (190, 590), f"Artist: {ssingers}", (255, 255, 255), font=font
    )
    draw.text(
        (190, 630),
        f"Duration: {sduration_converted} Seconds",
        (255, 255, 255),
        font=font,
    )
    draw.text(
        (190, 670),
        f"Played By: {message.from_user.first_name}",
        (255, 255, 255),
        font=font,
    )
    img.save("final.png")
    os.system("rm temp.png")
    os.system("rm background.png")
    await m.delete()
    m = await message.reply_photo(
        caption=f"Playing `{sname}` Via Jiosaavn #music",
        photo="final.png",
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        f"STOP", callback_data="end"
                    )
                ]
            ]
        ),
        parse_mode="markdown",
    )

    s = await asyncio.create_subprocess_shell(
        f"mpv {slink} --no-video",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    await s.wait()
    await m.delete()
Exemple #10
0
async def call_seedr_download(msg: Message, torrent_type: str):
    if torrent_type == "magnet":
        ack_msg = await msg.reply_text("About to add the magnet link to seedr."
                                       )

        tr_process = await SeedrAPI().add_url(msg.text, "magnet")
    else:
        ack_msg = await msg.reply_text("About to add the link to seedr.")
        tr_process = await SeedrAPI().add_url(msg.text, "other")

    if tr_process["result"] is True:
        try:
            while True:
                await asyncio.sleep(4)
                tr_progress = await SeedrAPI().get_torrent_details(
                    tr_process["user_torrent_id"])
                if tr_progress["progress"] < 100:
                    try:
                        await ack_msg.edit_text(
                            f"Uploading to Seedr: \n"
                            f"Progress: {tr_progress['progress']}% | "
                            f"Size: {size.format_size(tr_progress['size'], binary=True)}"
                        )
                    except MessageNotModified as e:
                        logging.error(e)
                else:
                    await asyncio.sleep(10)
                    tr_progress = await SeedrAPI().get_torrent_details(
                        tr_process["user_torrent_id"])
                    await ack_msg.edit_text(
                        "How would you like to upload the contents?")
                    await ack_msg.edit_reply_markup(
                        InlineKeyboardMarkup([
                            [
                                InlineKeyboardButton(
                                    text=f"{emoji.PACKAGE} Compressed",
                                    callback_data=
                                    f"sdlc_{str(tr_progress['folder_created'])}"
                                    f"_{msg.chat.id}_{msg.message_id}"
                                    f"_{ack_msg.message_id}")
                            ],
                            [
                                InlineKeyboardButton(
                                    text=f"{emoji.CARD_FILE_BOX} UnCompressed",
                                    callback_data=
                                    f"unsd_{str(tr_progress['folder_created'])}"
                                    f"_{msg.chat.id}_{msg.message_id}"
                                    f"_{ack_msg.message_id}")
                            ]
                        ]))
                    break
        except Exception as e:
            logging.error(e)
    else:
        try:
            error = tr_process['error']
        except KeyError:
            error = None

        logging.error(error)
        await ack_msg.edit_text(f"An error occurred:\n<pre>{error}</pre>",
                                parse_mode="html")
Exemple #11
0
async def url_process(m: Message):
    if m.text.startswith("magnet"):
        await m.reply_text(
            text="What would you like to do with this file?",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(
                    text=f"{emoji.MAGNET} Proceed with Download",
                    callback_data=f"magnet_{m.chat.id}_{m.message_id}")
            ]]))
    else:
        header_info = await Downloader.get_headers(m.text)
        file_type_raw = header_info.get(
            "Content-Type") if "Content-Type" in header_info else "None/None"
        file_type_split = file_type_raw.split("/")[0]
        file_content_disposition = header_info.get("content-disposition")
        file_name_f_headers = re.findall(
            "filename=(.+)",
            file_content_disposition)[0] if file_content_disposition else None
        file_ext_f_name = os.path.splitext(
            str(file_name_f_headers).replace('"', ""))[1]

        if header_info is None:
            await m.reply_text(
                f"I do not know the details of the file to download the file! {emoji.MAN_RAISING_HAND_DARK_SKIN_TONE}"
            )
        elif (tldextract.extract(m.text)).domain != "youtube":
            file_size = header_info.get(
                "Content-Length") if "Content-Length" in header_info else None
            if file_size is not None and int(file_size) > 2147483648:
                await m.reply_text(
                    f"Well that file is bigger than I can upload to telegram! {emoji.MAN_SHRUGGING_DARK_SKIN_TONE}"
                )
            else:
                inline_buttons = [[
                    InlineKeyboardButton(
                        text=f"{emoji.FLOPPY_DISK} Download",
                        callback_data=f"download_{m.chat.id}_{m.message_id}"),
                    InlineKeyboardButton(
                        text=f"{emoji.PENCIL} Rename",
                        callback_data=f"rename_{m.chat.id}_{m.message_id}")
                ]]
                if file_type_split.lower() == "video":
                    inline_buttons.append([
                        InlineKeyboardButton(
                            text=f"{emoji.LIGHT_BULB} Media Info",
                            callback_data=f"info_{m.chat.id}_{m.message_id}"),
                        InlineKeyboardButton(
                            text=f"{emoji.FRAMED_PICTURE} Screens",
                            callback_data=f"screens_{m.chat.id}_{m.message_id}"
                        )
                    ])
                elif file_ext_f_name == ".torrent" and Common(
                ).seedr_username is not None:
                    inline_buttons.append([
                        InlineKeyboardButton(
                            text=f"{emoji.TORNADO} Download Torrent",
                            callback_data=f"torrent_{m.chat.id}_{m.message_id}"
                        )
                    ])
                await m.reply_text(
                    text="What would you like to do with this file?",
                    reply_markup=InlineKeyboardMarkup(inline_buttons))

        elif (tldextract.extract(m.text)).domain == "youtube":
            inline_buttons = [
                [
                    InlineKeyboardButton(
                        text=f"{emoji.LOUDSPEAKER} Extract Audio",
                        callback_data=f"ytaudio_{m.chat.id}_{m.message_id}"),
                    InlineKeyboardButton(
                        text=f"{emoji.VIDEOCASSETTE} Extract Video",
                        callback_data=f"ytvid_{m.chat.id}_{m.message_id}")
                ],
                [
                    InlineKeyboardButton(
                        text=f"{emoji.LIGHT_BULB} Media Info",
                        callback_data=f"ytmd_{m.chat.id}_{m.message_id}")
                ]
            ]
            await m.reply_text(
                text="What would you like to do with this file?",
                reply_markup=InlineKeyboardMarkup(inline_buttons))
Exemple #12
0
async def jiosaavn(client: Client, message_: Message):
    global que
    lel = await message_.reply("🔄 **Processing**")
    administrators = await get_administrators(message_.chat)
    chid = message_.chat.id
    usar = await USER.get_me()
    wew = usar.id

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

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

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

    else:
        await res.edit_text("▶️ Memutar lagu...")
        chat_id = message_.chat.id
        que[chat_id] = []
        qeue = que.get(message_.chat.id)
        s_name = sname
        r_by = message_.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message_.chat.id, file_path)
    await res.edit("Generating Thumbnail.")
    await generate_cover(requested_by, sname, ssingers, sduration, sthumb)
    await res.delete()
    m = await client.send_photo(
        chat_id=message_.chat.id,
        reply_markup=keyboard,
        photo="final.png",
        caption=f"Memutar Lagu {sname} Via Jiosaavn",
    )
    os.remove("final.png")
Exemple #13
0
async def deezer(client: Client, message_: Message):
    global que
    lel = await message_.reply("🔄 **Sedang Memproses**")
    administrators = await get_administrators(message_.chat)
    chid = message_.chat.id
    usar = await USER.get_me()
    wew = usar.id
    for administrator in administrators:
        if administrator == message_.from_user.id:
            try:
                invitelink = await client.export_chat_invite_link(chid)
            except:
                await lel.edit("<b>Add me as admin of yor group first</b>", )
                return

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

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

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

    await res.delete()

    m = await client.send_photo(
        chat_id=message_.chat.id,
        reply_markup=keyboard,
        photo="final.png",
        caption=f"#️⃣ Mengantri di posisi {position}.).")
    os.remove("final.png")
Exemple #14
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **Sedang Memproses**")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id
    usar = await USER.get_me()
    wew = usar.id
    for administrator in administrators:
        if administrator == message.from_user.id:
            try:
                invitelink = await _.export_chat_invite_link(chid)
            except:
                await lel.edit(
                    "<b>Tambahkan saya sebagai admin grup terlebih dahulu</b>",
                )
                return

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

            except UserAlreadyParticipant:
                pass
            except Exception as e:
                #print(e)
                #await lel.edit(
                #    f"<b>User {user.first_name} couldn't join your group! Make sure user is not banned in group."
                #    "\n\nOr manually add @DaisyXmusic to your Group and try again</b>",
                #)
                pass
    try:
        chatdetails = await USER.get_chat(chid)
        #lmoa = await _.get_chat_member(chid,wew)
    except:
        await lel.edit(
            "<i>helper Userbot tidak ada dalam obrolan ini, Minta admin untuk mengirim /play perintah untuk pertama kalinya atau tambahkan asisten secara manual</i>"
        )
        return
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name
    await lel.edit("🔎 **Sedang Mencari**")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

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

    except Exception as e:
        await lel.edit(
            "Lagu tidak ditemukan. Coba cari dengan judul lagu yang lebih jelas"
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup(
        [[
            InlineKeyboardButton('📖 Playlist', callback_data='playlist'),
            InlineKeyboardButton('Menu ⏯ ', callback_data='menu')
        ],
         [
             InlineKeyboardButton("Group Support",
                                  url="https://t.me/SharingUserbot"),
             InlineKeyboardButton("Owner Music Man",
                                  url="https://instagram.com/mrismanaziz_")
         ], [InlineKeyboardButton(text="❌ Close", callback_data='cls')]])
    requested_by = message.from_user.first_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file_path = await converter.convert(youtube.download(url))

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Lagu yang Anda minta **Sedang Antri** di posisi **{position}**",
            reply_markup=keyboard)
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = message.chat.id
        que[chat_id] = []
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption="▶️ **Memutar** Lagu Permintaan dari {}".format(
                message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Exemple #15
0
async def cb_handler(client: Bot, query: CallbackQuery):
    if query.message.reply_to_message.from_user.id == query.from_user.id:
        if query.data == "back1":
            try:
                buttons = []
                async for msg in client.USER.search_messages(
                        MAINCHANNEL_ID,
                        query=query.message.reply_to_message.text,
                        filter='document',
                        limit=10,
                        offset=0):
                    name = msg.document.file_name
                    link = msg.link
                    buttons.append(
                        [InlineKeyboardButton(text=f"{name}", url=link)])

                if buttons:
                    buttons.append([
                        InlineKeyboardButton(text=f"NEXT ⏩",
                                             callback_data="next1")
                    ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
            except:
                await query.answer("No more results found", show_alert=True)

        elif (query.data == "next1") or (query.data == "back2"):
            try:
                buttons = []
                async for msg in client.USER.search_messages(
                        MAINCHANNEL_ID,
                        query=query.message.reply_to_message.text,
                        filter='document',
                        limit=10,
                        offset=10):
                    name = msg.document.file_name
                    link = msg.link
                    buttons.append(
                        [InlineKeyboardButton(text=f"{name}", url=link)])

                if buttons:
                    buttons.append([
                        InlineKeyboardButton(text=f"⏪ BACK",
                                             callback_data="back1"),
                        InlineKeyboardButton(text=f"NEXT ⏩",
                                             callback_data="next2")
                    ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
            except:
                await query.answer("No more results found", show_alert=True)

        elif (query.data == "next2") or (query.data == "back3"):
            try:
                buttons = []
                async for msg in client.USER.search_messages(
                        MAINCHANNEL_ID,
                        query=query.message.reply_to_message.text,
                        filter='document',
                        limit=10,
                        offset=20):
                    name = msg.document.file_name
                    link = msg.link
                    buttons.append(
                        [InlineKeyboardButton(text=f"{name}", url=link)])

                if buttons:
                    buttons.append([
                        InlineKeyboardButton(text=f"⏪ BACK",
                                             callback_data="back2"),
                        InlineKeyboardButton(text=f"NEXT ⏩",
                                             callback_data="next3")
                    ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
            except:
                await query.answer("No more results found", show_alert=True)

        elif (query.data == "next3") or (query.data == "back4"):
            try:
                buttons = []
                async for msg in client.USER.search_messages(
                        MAINCHANNEL_ID,
                        query=query.message.reply_to_message.text,
                        filter='document',
                        limit=10,
                        offset=30):
                    name = msg.document.file_name
                    link = msg.link
                    buttons.append(
                        [InlineKeyboardButton(text=f"{name}", url=link)])

                if buttons:
                    buttons.append([
                        InlineKeyboardButton(text=f"⏪ BACK",
                                             callback_data="back3"),
                        InlineKeyboardButton(text=f"NEXT ⏩",
                                             callback_data="next4")
                    ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
            except:
                await query.answer("No more results found", show_alert=True)

        elif query.data == "next4":
            try:
                buttons = []
                async for msg in client.USER.search_messages(
                        MAINCHANNEL_ID,
                        query=query.message.reply_to_message.text,
                        filter='document',
                        limit=10,
                        offset=40):
                    name = msg.document.file_name
                    link = msg.link
                    buttons.append(
                        [InlineKeyboardButton(text=f"{name}", url=link)])

                if buttons:
                    buttons.append([
                        InlineKeyboardButton(text=f"⏪ BACK",
                                             callback_data="back4")
                    ])

                await query.edit_message_reply_markup(
                    reply_markup=InlineKeyboardMarkup(buttons))
            except:
                await query.answer("No more results found", show_alert=True)

        elif query.data == "start_data":

            keyboard = InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton("HELP", callback_data="help_data"),
                    InlineKeyboardButton("ABOUT", callback_data="about_data")
                ],
                 [
                     InlineKeyboardButton("⭕️ JOIN OUR CHANNEL ⭕️",
                                          url="https://t.me/MATSchannel")
                 ]])

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

        elif query.data == "help_data":

            keyboard = InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton("BACK", callback_data="start_data"),
                    InlineKeyboardButton("ABOUT", callback_data="about_data")
                ],
                 [
                     InlineKeyboardButton("⭕️ SUPPORT ⭕️",
                                          url="https://t.me/MATShub")
                 ]])

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

        elif query.data == "about_data":

            keyboard = InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton("BACK", callback_data="help_data"),
                    InlineKeyboardButton("START", callback_data="start_data")
                ],
                 [
                     InlineKeyboardButton("OUR CHANNEL",
                                          url="https://t.me/MATSchannel")
                 ]])

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

    else:
        await query.answer("Thats not for you!!", show_alert=True)
Exemple #16
0
async def ytplay(_, message: Message):
    global blacks
    if message.from_user.id in blacks:
        await message.reply_text("You're Blacklisted, So Stop Spamming.")
        return
    global m
    global s

    if len(message.command) < 2:
        await message.reply_text("/youtube requires one argument")
        return
    try:
        await message.delete()
    except:
        pass
    try:
        await m.delete()
    except:
        pass
    try:
        os.system("killall -9 mpv")
    except:
        pass
    try:
        os.remove("audio.mp3")
    except:
        pass
    ydl_opts = {"format": "bestaudio"}
    query = kwairi(message)
    m = await message.reply_text(f"Searching for `{query}` on YouTube")
    results = YoutubeSearch(query, max_results=1).to_dict()
    link = f"https://youtube.com{results[0]['url_suffix']}"
    title = results[0]["title"]
    thumbnail = results[0]["thumbnails"][0]
    duration = results[0]["duration"]
    views = results[0]["views"]
    await m.edit("Processing Thumbnail.")
    async with aiohttp.ClientSession() as session:
        async with session.get(thumbnail) as resp:
            if resp.status == 200:
                f = await aiofiles.open("background.png", mode="wb")
                await f.write(await resp.read())
                await f.close()

    def changeImageSize(maxWidth, maxHeight, image):
        widthRatio = maxWidth / image.size[0]
        heightRatio = maxHeight / image.size[1]
        newWidth = int(widthRatio * image.size[0])
        newHeight = int(heightRatio * image.size[1])
        newImage = image.resize((newWidth, newHeight))
        return newImage

    image1 = Image.open("./background.png")
    image2 = Image.open("etc/foreground.png")
    image3 = changeImageSize(1280, 720, image1)
    image4 = changeImageSize(1280, 720, image2)
    image5 = image3.convert("RGBA")
    image6 = image4.convert("RGBA")
    Image.alpha_composite(image5, image6).save("temp.png")
    img = Image.open("temp.png")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("etc/JetBrainsMonoNL-Regular.ttf", 32)
    draw.text((190, 550), f"Title: {title}", (255, 255, 255), font=font)
    draw.text(
        (190, 590), f"Duration: {duration}", (255, 255, 255), font=font
    )
    draw.text((190, 630), f"Views: {views}", (255, 255, 255), font=font)
    draw.text(
        (190, 670),
        f"Played By: {message.from_user.first_name}",
        (255, 255, 255),
        font=font,
    )
    img.save("final.png")
    os.system("rm temp.png")
    os.system("rm background.png")
    await m.edit("Downloading Music.")
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(link, download=False)
        audio_file = ydl.prepare_filename(info_dict)
        ydl.process_info(info_dict)
        os.rename(audio_file, "audio.webm")
    await m.delete()
    m = await message.reply_photo(
        caption=f"Playing [{title}]({link}) Via YouTube #music",
        photo="final.png",
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        f"STOP", callback_data="end"
                    )
                ]
            ]
        ),
        parse_mode="markdown",
    )
    os.system("rm final.png")
    s = await asyncio.create_subprocess_shell(
        "mpv audio.webm --no-video",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    await s.wait()
    await m.delete()
Exemple #17
0
async def iytdl_inline(client: Client, message: Message):
    reply = message.reply_to_message
    input_url = None
    k = message.text.split(None, 1)
    if len(k) == 2:
        input_url = k[1]
    elif reply:
        if reply.text:
            input_url = reply.text
        elif reply.caption:
            input_url = reply.caption
    if not input_url:
        x = await message.reply_text("Input or reply to a valid youtube URL")
        await asyncio.sleep(5)
        await x.delete()
        return
    x = await message.reply_text(
        f"🔎 Searching Youtube for: <code>'{input_url}'</code>")
    input_url = input_url.strip()
    link = get_yt_video_id(input_url)
    if link is None:
        search_ = VideosSearch(input_url, limit=15)
        resp = (search_.result()).get("result")
        if len(resp) == 0:
            await x.edit_text(f'No Results found for "{input_url}"')
            await asyncio.sleep(5)
            await x.delete()
            return
        outdata = await result_formatter(resp)
        key_ = rand_key()
        ytsearch_data.store_(key_, outdata)
        buttons = InlineKeyboardMarkup([
            [
                InlineKeyboardButton(
                    text=f"1 / {len(outdata)}",
                    callback_data=f"ytdl_next_{key_}_1",
                )
            ],
            [
                InlineKeyboardButton(
                    text="📜  List all",
                    callback_data=f"ytdl_listall_{key_}_1",
                ),
                InlineKeyboardButton(
                    text="⬇️  Download",
                    callback_data=f'ytdl_download_{outdata[1]["video_id"]}_0',
                ),
            ],
        ])
        caption = outdata[1]["message"]
        photo = outdata[1]["thumb"]
    else:
        caption, buttons = await download_button(link, body=True)
        photo = await get_ytthumb(link)
    msg = await client.send_photo(
        message.chat.id,
        photo=photo,
        caption=caption,
        reply_markup=buttons,
    )
    await x.delete()
    user_search[message.from_user.id].append([msg.chat.id, msg.message_id])
Exemple #18
0
    "temp": "♻️",
    "plugins": "💎",
    "bot": "💠",
}
# Database
SAVED_SETTINGS = get_collection("CONFIGS")
BUTTON_BASE = get_collection("TEMP_BUTTON")  # TODO use json cache
REPO_X = InlineQueryResultArticle(
    title="Repo",
    input_message_content=InputTextMessageContent(
        "**Here's how to setup USERGE-X** "),
    url="https://github.com/code-rgb/USERGE-X",
    description="Setup Your Own",
    thumb_url="https://i.imgur.com/1xsOo9o.png",
    reply_markup=InlineKeyboardMarkup([[
        InlineKeyboardButton("🔥 USERGE-X Repo",
                             url="https://github.com/code-rgb/USERGE-X"),
        InlineKeyboardButton(
            "🚀 Deploy USERGE-X",
            url=("https://heroku.com/deploy?template="
                 "https://github.com/code-rgb/USERGE-X/tree/alpha"),
        ),
    ]]),
)
# Thanks boi @FLAMEPOSEIDON
ALIVE_IMGS = [
    "https://telegra.ph/file/11123ef7dff2f1e19e79d.jpg",
    "https://i.imgur.com/uzKdTXG.jpg",
    "https://telegra.ph/file/6ecab390e4974c74c3764.png",
    "https://telegra.ph/file/995c75983a6c0e4499b55.png",
    "https://telegra.ph/file/86cc25c78ad667ca5e691.png",
]
Exemple #19
0
def download_button(vid: str, body: bool = False):
    try:
        vid_data = youtube_dl.YoutubeDL({
            "no-playlist": True
        }).extract_info(BASE_YT_URL + vid, download=False)
    except ExtractorError:
        vid_data = {"formats": []}
    buttons = [[
        InlineKeyboardButton("⭐️ BEST - 📹 MKV",
                             callback_data=f"ytdl_download_{vid}_mkv_v"),
        InlineKeyboardButton(
            "⭐️ BEST - 📹 WebM/MP4",
            callback_data=f"ytdl_download_{vid}_mp4_v",
        ),
    ]]
    # ------------------------------------------------ #
    qual_dict = defaultdict(lambda: defaultdict(int))
    qual_list = ["144p", "240p", "360p", "480p", "720p", "1080p", "1440p"]
    audio_dict = {}
    # ------------------------------------------------ #
    for video in vid_data["formats"]:

        fr_note = video.get("format_note")
        fr_id = int(video.get("format_id"))
        fr_size = video.get("filesize")
        if video.get("ext") == "mp4":
            for frmt_ in qual_list:
                if fr_note in (frmt_, frmt_ + "60"):
                    qual_dict[frmt_][fr_id] = fr_size
        if video.get("acodec") != "none":
            bitrrate = int(video.get("abr", 0))
            if bitrrate != 0:
                audio_dict[
                    bitrrate] = f"🎵 {bitrrate}Kbps ({humanbytes(fr_size) or 'N/A'})"

    video_btns = []
    for frmt in qual_list:
        frmt_dict = qual_dict[frmt]
        if len(frmt_dict) != 0:
            frmt_id = sorted(list(frmt_dict))[-1]
            frmt_size = humanbytes(frmt_dict.get(frmt_id)) or "N/A"
            video_btns.append(
                InlineKeyboardButton(
                    f"📹 {frmt} ({frmt_size})",
                    callback_data=f"ytdl_download_{vid}_{frmt_id}_v",
                ))
    buttons += sublists(video_btns, width=2)
    buttons += [[
        InlineKeyboardButton("⭐️ BEST - 🎵 320Kbps - MP3",
                             callback_data=f"ytdl_download_{vid}_mp3_a")
    ]]
    buttons += sublists(
        [
            InlineKeyboardButton(audio_dict.get(key_),
                                 callback_data=f"ytdl_download_{vid}_{key_}_a")
            for key_ in sorted(audio_dict.keys())
        ],
        width=2,
    )
    if body:
        vid_body = f"<b><a href='{vid_data.get('webpage_url')}'>{vid_data.get('title')}</a></b>"
        return vid_body, InlineKeyboardMarkup(buttons)
    return InlineKeyboardMarkup(buttons)
Exemple #20
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 == 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)
                    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()}`

    🕔 Uptime : {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 string == "buttonnn":
                async for data in BUTTON_BASE.find():
                    button_data = data["msg_data"]
                text, buttons = pb(button_data)
                try:
                    photo_url = data["photo_url"]
                except KeyError:
                    photo_url = None
                if photo_url:
                    results.append(
                        InlineQueryResultPhoto(photo_url=photo_url,
                                               caption=text,
                                               reply_markup=buttons))
                else:
                    results.append(
                        InlineQueryResultArticle(
                            title=text,
                            input_message_content=InputTextMessageContent(
                                text),
                            reply_markup=buttons,
                        ))

            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",
            )
Exemple #21
0
async def zee5_execute(bot, update):

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

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

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

        youtube_dl_url = zee5_capture.url

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

        custom_file_name = videoname + ".mp4"

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

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

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

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

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

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

        ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output."
        if e_response and ad_string_to_replace in e_response:
            error_message = e_response.replace(ad_string_to_replace, "")
            await bot.edit_message_text(chat_id=update.message.chat.id,
                                        message_id=update.message.message_id,
                                        text=error_message)
            return False
        if t_response:
            os.remove(save_ytdl_json_path)
            end_one = datetime.now()
            time_taken_for_download = (end_one - start).seconds
            file_size = Config.TG_MAX_FILE_SIZE + 1
            try:
                file_size = os.stat(download_directory).st_size
            except FileNotFoundError as exc:
                download_directory = os.path.splitext(
                    download_directory)[0] + "." + "mp4"
                file_size = os.stat(download_directory).st_size
            if file_size > Config.TG_MAX_FILE_SIZE:
                await bot.edit_message_text(
                    chat_id=update.message.chat.id,
                    text=script.RCHD_TG_API_LIMIT.format(
                        time_taken_for_download, humanbytes(file_size)),
                    message_id=update.message.message_id)
            else:
                await bot.edit_message_text(
                    text=script.UPLOAD_START,
                    chat_id=update.message.chat.id,
                    message_id=update.message.message_id)

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

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

                start_time = time.time()

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

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

                await bot.edit_message_text(
                    text=script.AFTER_SUCCESSFUL_UPLOAD_MSG_WITH_TS,
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            text="🙌🏻 SHARE ME 🙌🏻",
                            url=
                            "tg://msg?text=%2A%2AHai%20%E2%9D%A4%EF%B8%8F%2C%2A%2A%20%0A__Today%20i%20just%20found%20out%20an%20intresting%20and%20Powerful__%20%2A%2AZee5%20Downloader%20Bot%2A%2A%20__for%20Free%F0%9F%A5%B0.__%20%20%0A%2A%2ABot%20Link%20%3A%20%40Zee5HEXBot%2A%2A%20%F0%9F%94%A5"
                        )
                    ]]),
                    chat_id=update.message.chat.id,
                    message_id=update.message.message_id,
                    disable_web_page_preview=True)
    except:
        await update.reply_text("Couldn't download your video!", quote=True)
        logger.info('error in process')
import inspect
from unittest.mock import Mock

import pytest
from pyrogram import Client
from pyrogram.types import InlineKeyboardButton

from tgintegration import BotController
from tgintegration.containers import InlineKeyboard
from tgintegration.containers import NoButtonFound

BTN_A = InlineKeyboardButton("a", callback_data="a")
BTN_B = InlineKeyboardButton("b", callback_data="b")
BTN_C = InlineKeyboardButton("c", callback_data="c")


@pytest.mark.parametrize(
    "rows,idx,expected",
    [
        pytest.param(
            [[
                BTN_A,
                BTN_B,
            ]],
            0,
            BTN_A,
        ),
        pytest.param(
            [[
                BTN_A,
                BTN_B,
Exemple #23
0
async def help_button(client, query):
    mod_match = re.match(r"help_module\((.+?)\)", query.data)
    prev_match = re.match(r"help_prev\((.+?)\)", query.data)
    next_match = re.match(r"help_next\((.+?)\)", query.data)
    back_match = re.match(r"help_back", query.data)
    create_match = re.match(r"help_create", query.data)
    top_text = f"""
Hello {query.from_user.first_name}! My name is {BOT_NAME}!
I'm a group management bot with some usefule features.
You can choose an option below, by clicking a button.
Also you can ask anything in Support Group.

General command are:
 - /start: Start the bot
 - /help: Give this message
 """
    if mod_match:
        module = mod_match.group(1)
        text = ("{} **{}**:\n".format("Here is the help for",
                                      HELPABLE[module].__MODULE__) +
                HELPABLE[module].__HELP__)

        await query.message.edit(
            text=text,
            reply_markup=InlineKeyboardMarkup(
                [[InlineKeyboardButton("back", callback_data="help_back")]]),
            disable_web_page_preview=True,
        )

    elif prev_match:
        curr_page = int(prev_match.group(1))
        await query.message.edit(
            text=top_text,
            reply_markup=InlineKeyboardMarkup(
                paginate_modules(curr_page - 1, HELPABLE, "help")),
            disable_web_page_preview=True,
        )

    elif next_match:
        next_page = int(next_match.group(1))
        await query.message.edit(
            text=top_text,
            reply_markup=InlineKeyboardMarkup(
                paginate_modules(next_page + 1, HELPABLE, "help")),
            disable_web_page_preview=True,
        )

    elif back_match:
        await query.message.edit(
            text=top_text,
            reply_markup=InlineKeyboardMarkup(
                paginate_modules(0, HELPABLE, "help")),
            disable_web_page_preview=True,
        )

    elif create_match:
        text, keyboard = await help_parser(query)
        await query.message.edit(
            text=text,
            reply_markup=keyboard,
            disable_web_page_preview=True,
        )

    return await client.answer_callback_query(query.id)
Exemple #24
0
async def cb_handler(client, query):

    if query.data == "start_data":
        await query.answer()
        keyboard = InlineKeyboardMarkup(
            [[InlineKeyboardButton("Command Help",
                                   callback_data="help_data")]])

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

    elif query.data == "help_data":
        await query.answer()
        keyboard = InlineKeyboardMarkup(
            [[
                InlineKeyboardButton("How to Deploy?",
                                     url="https://youtu.be/hkmc3e7U7R4"),
                InlineKeyboardButton("About Me", callback_data="about_data")
            ],
             [
                 InlineKeyboardButton(
                     "BOT Channel",
                     url="https://t.me/joinchat/7qlEga5lO0o2MTg0"),
                 InlineKeyboardButton(
                     "Support Group",
                     url="https://t.me/joinchat/YS-WlsUC9nFiOWM0")
             ]])

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

    elif query.data == "about_data":
        await query.answer()
        keyboard = InlineKeyboardMarkup(
            [[
                InlineKeyboardButton(
                    "SOURCE CODE",
                    url="https://github.com/jinspalakkattu/UFS-Filter-Bot")
            ],
             [
                 InlineKeyboardButton("BACK", callback_data="help_data"),
                 InlineKeyboardButton("CLOSE", callback_data="close_data"),
             ]])

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

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

    elif query.data == "delallconfirm":
        userid = query.from_user.id
        chat_type = query.message.chat.type

        if chat_type == "private":
            grpid = await active_connection(str(userid))
            if grpid is not None:
                grp_id = grpid
                try:
                    chat = await client.get_chat(grpid)
                    title = chat.title
                except:
                    await query.message.edit_text(
                        "Make sure I'm present in your group!!", quote=True)
                    return
            else:
                await query.message.edit_text(
                    "I'm not connected to any groups!\nCheck /connections or connect to any groups",
                    quote=True)
                return

        elif (chat_type == "group") or (chat_type == "supergroup"):
            grp_id = query.message.chat.id
            title = query.message.chat.title

        else:
            return

        st = await client.get_chat_member(grp_id, userid)
        if (st.status == "creator") or (str(userid) in Config.AUTH_USERS):
            await del_all(query.message, grp_id, title)
        else:
            await query.answer(
                "You need to be Group Owner or an Auth User to do that!",
                show_alert=True)

    elif query.data == "delallcancel":
        userid = query.from_user.id
        chat_type = query.message.chat.type

        if chat_type == "private":
            await query.message.reply_to_message.delete()
            await query.message.delete()

        elif (chat_type == "group") or (chat_type == "supergroup"):
            grp_id = query.message.chat.id
            st = await client.get_chat_member(grp_id, userid)
            if (st.status == "creator") or (str(userid) in Config.AUTH_USERS):
                await query.message.delete()
                try:
                    await query.message.reply_to_message.delete()
                except:
                    pass
            else:
                await query.answer("Thats not for you!!", show_alert=True)

    elif "groupcb" in query.data:
        await query.answer()

        group_id = query.data.split(":")[1]
        title = query.data.split(":")[2]
        act = query.data.split(":")[3]
        user_id = query.from_user.id

        if act == "":
            stat = "CONNECT"
            cb = "connectcb"
        else:
            stat = "DISCONNECT"
            cb = "disconnect"

        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton(f"{stat}",
                                 callback_data=f"{cb}:{group_id}:{title}"),
            InlineKeyboardButton("DELETE",
                                 callback_data=f"deletecb:{group_id}")
        ], [InlineKeyboardButton("BACK", callback_data="backcb")]])

        await query.message.edit_text(
            f"Group Name : **{title}**\nGroup ID : `{group_id}`",
            reply_markup=keyboard,
            parse_mode="md")
        return

    elif "connectcb" in query.data:
        await query.answer()

        group_id = query.data.split(":")[1]
        title = query.data.split(":")[2]
        user_id = query.from_user.id

        mkact = await make_active(str(user_id), str(group_id))

        if mkact:
            await query.message.edit_text(f"Connected to **{title}**",
                                          parse_mode="md")
            return
        else:
            await query.message.edit_text(f"Some error occured!!",
                                          parse_mode="md")
            return

    elif "disconnect" in query.data:
        await query.answer()

        title = query.data.split(":")[2]
        user_id = query.from_user.id

        mkinact = await make_inactive(str(user_id))

        if mkinact:
            await query.message.edit_text(f"Disconnected from **{title}**",
                                          parse_mode="md")
            return
        else:
            await query.message.edit_text(f"Some error occured!!",
                                          parse_mode="md")
            return
    elif "deletecb" in query.data:
        await query.answer()

        user_id = query.from_user.id
        group_id = query.data.split(":")[1]

        delcon = await delete_connection(str(user_id), str(group_id))

        if delcon:
            await query.message.edit_text("Successfully deleted connection")
            return
        else:
            await query.message.edit_text(f"Some error occured!!",
                                          parse_mode="md")
            return

    elif query.data == "backcb":
        await query.answer()

        userid = query.from_user.id

        groupids = await all_connections(str(userid))
        if groupids is None:
            await query.message.edit_text(
                "There are no active connections!! Connect to some groups first.",
            )
            return
        buttons = []
        for groupid in groupids:
            try:
                ttl = await client.get_chat(int(groupid))
                title = ttl.title
                active = await if_active(str(userid), str(groupid))
                if active:
                    act = " - ACTIVE"
                else:
                    act = ""
                buttons.append([
                    InlineKeyboardButton(
                        text=f"{title}{act}",
                        callback_data=f"groupcb:{groupid}:{title}:{act}")
                ])
            except:
                pass
        if buttons:
            await query.message.edit_text(
                "Your connected group details ;\n\n",
                reply_markup=InlineKeyboardMarkup(buttons))

    elif "alertmessage" in query.data:
        grp_id = query.message.chat.id
        i = query.data.split(":")[1]
        keyword = query.data.split(":")[2]
        reply_text, btn, alerts, fileid = await find_filter(grp_id, keyword)
        if alerts is not None:
            alerts = ast.literal_eval(alerts)
            alert = alerts[int(i)]
            alert = alert.replace("\\n", "\n").replace("\\t", "\t")
            await query.answer(alert, show_alert=True)
async def answer(bot, query: InlineQuery):
    answers = []
    string = query.query.lower()
    search_query = query.query
    if string == "":
        answers.append(
            InlineQueryResultArticle(
                title="Help & Usage",
                input_message_content=InputTextMessageContent(
                    Config.HELP_TEXT,
                    disable_web_page_preview=True,
                    parse_mode="Markdown"),
                description="Documention of How to Use this Bot.",
                thumb_url="https://i.imgur.com/6jZsMYG.png",
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton("Support Group",
                                             url="https://t.me/linux_repo"),
                        InlineKeyboardButton("Developer",
                                             url="https://t.me/AbirHasan2005")
                    ],
                     [
                         InlineKeyboardButton(
                             "Delete GoFile.io File",
                             switch_inline_query_current_chat="!godel ")
                     ],
                     [
                         InlineKeyboardButton(
                             "Delete Streamtape File (Admin Only)",
                             switch_inline_query_current_chat="!stdel ")
                     ],
                     [
                         InlineKeyboardButton(
                             "Rename Streamtape File (Admin Only)",
                             switch_inline_query_current_chat="!strename ")
                     ],
                     [
                         InlineKeyboardButton(
                             "Add Remote URL in Streamtape",
                             switch_inline_query_current_chat="!stremote ")
                     ],
                     [
                         InlineKeyboardButton(
                             "Get Status of Streamtape Token",
                             switch_inline_query_current_chat="!show ")
                     ],
                     [
                         InlineKeyboardButton(
                             "Rmeove Remote URL (Admin Only)",
                             switch_inline_query_current_chat="!strmdel ")
                     ],
                     [
                         InlineKeyboardButton("Show Configs (Admin Only)",
                                              callback_data="showcreds")
                     ]])))
        await bot.answer_inline_query(query.id,
                                      results=answers,
                                      switch_pm_text="How to Use Me?",
                                      switch_pm_parameter="help",
                                      cache_time=0)
    elif search_query.startswith("!stdel"):
        if not int(query.from_user.id) == Config.BOT_OWNER:
            answers.append(
                InlineQueryResultArticle(
                    title="You Can't Do That!",
                    description="This is only for Bot Owner!",
                    input_message_content=InputTextMessageContent(
                        message_text=
                        "This is only for Bot Owner!\n\nOnly Developer have Streamtape File Delete Rights!"
                    ),
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            InlineKeyboardButton("Support Group",
                                                 url="https://t.me/linux_repo")
                        ],
                         [
                             InlineKeyboardButton(
                                 "Developer", url="https://t.me/AbirHasan2005")
                         ]])))
        else:
            try:
                await asyncio.sleep(
                    5)  # Waiting for 5 Sec for getting Correct User Input!
                async with aiohttp.ClientSession() as session:
                    api_link = "https://api.streamtape.com/file/delete?login={}&key={}&file={}"
                    main_text = None
                    splited = None
                    token = None
                    try:
                        main_text = search_query.split("!stdel ")[1]
                        splited = main_text.split(" ")[0]
                        token = splited.split("/")[4]
                    except IndexError:
                        print("Got IndexError - Skiping [token]")
                        main_text = ""
                        splited = ""
                        token = ""
                    except Exception as error:
                        print(f"Got Error - {error} - Skiping [token]")
                        main_text = ""
                        splited = ""
                        token = ""
                    if token == "":
                        answers.append(
                            InlineQueryResultArticle(
                                title="!stdel [file_link]",
                                description=
                                "Put File Link to Delete Streamtape File!",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    "This for Deleting Streamtape File via File Link.\n\n**Format:** `@Cloud_UPManager_Bot !stdel `__[file_link]__",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True),
                                reply_markup=InlineKeyboardMarkup([[
                                    InlineKeyboardButton(
                                        "Delete Streamtape File",
                                        switch_inline_query_current_chat=
                                        "!stdel ")
                                ]])))
                    else:
                        delete = await session.get(
                            api_link.format(Config.STREAMTAPE_API_USERNAME,
                                            Config.STREAMTAPE_API_PASS, token))
                        data = await delete.json()
                        status = data['msg']
                        if status == "OK":
                            answers.append(
                                InlineQueryResultArticle(
                                    title="Deleted File!",
                                    description=f"Deleted [{token}]",
                                    input_message_content=
                                    InputTextMessageContent(
                                        message_text=
                                        f"**Deleted:** {splited}\n\n**File Token:** `{token}`",
                                        parse_mode="Markdown",
                                        disable_web_page_preview=True)))
                            await bot.send_message(
                                chat_id=Config.LOG_CHANNEL,
                                text=
                                f"#STREAMTAPE_DELETE:\n\n[{query.from_user.first_name}](tg://user?id={query.from_user.id}) Deleted Streamtape File !!\n\n**File Name:** {splited}\n\n**File Token:** `{token}`",
                                parse_mode="Markdown",
                                disable_web_page_preview=True)
                        else:
                            answers.append(
                                InlineQueryResultArticle(
                                    title="File Not Deleted!",
                                    description=f"Can't Delete [{token}]",
                                    input_message_content=
                                    InputTextMessageContent(
                                        message_text=
                                        f"Can't Delete - {splited}\nUsing [{token}]",
                                        disable_web_page_preview=True,
                                        parse_mode="Markdown")))
            except Exception as err:
                answers.append(
                    InlineQueryResultArticle(
                        title="Something Went Wrong!",
                        description=f"Error: {err}",
                        input_message_content=InputTextMessageContent(
                            message_text=
                            f"Something Went Wrong!\n\n**Error:** `{err}`"),
                        reply_markup=InlineKeyboardMarkup([[
                            InlineKeyboardButton("Support Group",
                                                 url="https://t.me/linux_repo")
                        ]])))

        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(results=answers,
                               cache_time=0,
                               switch_pm_text="Error: Search timed out!",
                               switch_pm_parameter="help")
    elif search_query.startswith("!godel"):
        try:
            await asyncio.sleep(
                5)  # Waiting for 5 Sec for getting Correct User Input!
            async with aiohttp.ClientSession() as session:
                api_link = "https://apiv2.gofile.io/deleteUpload?c={}&ac={}"
                main_text = None
                splited = None
                token = None
                adminCode = None
                try:
                    main_text = search_query.split("!godel ")[1]
                    splited = main_text.split(" ")[0]
                    token = splited.split("/")[4]
                    adminCode = main_text.split(" ", 1)[1]
                except IndexError:
                    print("Got IndexError - Skiping [token] [adminCode]")
                    main_text = ""
                    splited = ""
                    token = ""
                    adminCode = ""
                except Exception as error:
                    print(f"Got Error - {error} - Skiping [token] [adminCode]")
                    main_text = ""
                    splited = ""
                    token = ""
                    adminCode = ""
                if (token == "" or adminCode == ""):
                    answers.append(
                        InlineQueryResultArticle(
                            title="!godel [file_link] [AdminCode]",
                            description=
                            "Put File Link to Delete GoFile.io File!",
                            input_message_content=InputTextMessageContent(
                                message_text=
                                "This for Deleting GoFile.io File via File Link.\n\n**Format:** `@Cloud_UPManager_Bot !godel `__[file_link] [AdminCode]__",
                                parse_mode="Markdown",
                                disable_web_page_preview=True),
                            reply_markup=InlineKeyboardMarkup([[
                                InlineKeyboardButton(
                                    "Delete GoFile.io File",
                                    switch_inline_query_current_chat="!godel ")
                            ]])))
                else:
                    response = await session.get(
                        api_link.format(token, adminCode))
                    data_f = await response.json()
                    status = data_f['status']
                    if status == "ok":
                        answers.append(
                            InlineQueryResultArticle(
                                title="Deleted File!",
                                description=
                                f"Deleted [{token}], Using [{adminCode}]",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    f"**Deleted:** {splited}\n\n**Using AdminCode:** `{adminCode}`\n**File Token:** `{token}`",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)))
                        await bot.send_message(
                            chat_id=Config.LOG_CHANNEL,
                            text=
                            f"#GOFILE_DELETE:\n\n[{query.from_user.first_name}](tg://user?id={query.from_user.id}) Deleted GoFile.io File !!\n\n**File Name:** {splited}\n\n**AdminCode:** `{adminCode}`\n\n**File Token:** `{token}`",
                            parse_mode="Markdown",
                            disable_web_page_preview=True)
                    else:
                        answers.append(
                            InlineQueryResultArticle(
                                title="File Not Deleted!",
                                description=
                                f"Can't Delete [{token}], Using [{adminCode}]",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    f"Can't Delete - {splited}\nUsing [{adminCode}]",
                                    disable_web_page_preview=True,
                                    parse_mode="Markdown")))

        except Exception as err:
            answers.append(
                InlineQueryResultArticle(
                    title="Something Went Wrong!",
                    description=f"Error: {err}",
                    input_message_content=InputTextMessageContent(
                        message_text=
                        f"Something Went Wrong!\n\n**Error:** `{err}`"),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton("Support Group",
                                             url="https://t.me/linux_repo")
                    ]])))

        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(results=answers,
                               cache_time=0,
                               switch_pm_text="Error: Search timed out!",
                               switch_pm_parameter="help")
    elif search_query.startswith("!strename"):
        if not int(query.from_user.id) == Config.BOT_OWNER:
            answers.append(
                InlineQueryResultArticle(
                    title="You Can't Do That!",
                    description="This is only for Bot Owner!",
                    input_message_content=InputTextMessageContent(
                        message_text=
                        "This is only for Bot Owner!\n\nOnly Developer have Streamtape File Delete Rights!"
                    ),
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            InlineKeyboardButton("Support Group",
                                                 url="https://t.me/linux_repo")
                        ],
                         [
                             InlineKeyboardButton(
                                 "Developer", url="https://t.me/AbirHasan2005")
                         ]])))
        else:
            parts = search_query.split(" ", 2)
            token, new_filename = "", ""
            try:
                token, new_filename = parts[1], input_f[2]
            except IndexError:
                print("Got IndexError - Skiping [token], [new_filename]")
                token, new_filename = "", ""
            except Exception as error:
                print(f"Got Error - {error} - Skiping [token], [new_filename]")
                token, new_filename = "", ""
            if (input_f == "" or token == "" or new_filename == ""):
                answers.append(
                    InlineQueryResultArticle(
                        title="!strename [token] [new_filename]",
                        description=
                        "Put File Token & New File Name to Rename Streamtape File!",
                        input_message_content=InputTextMessageContent(
                            message_text=
                            "This for Renaming Streamtape File via File Token & New File Name.\n\n**Format:** `@Cloud_UPManager_Bot !strename `__[token] [new_filename]__",
                            parse_mode="Markdown",
                            disable_web_page_preview=True),
                        reply_markup=InlineKeyboardMarkup([[
                            InlineKeyboardButton(
                                "Rename Streamtape File",
                                switch_inline_query_current_chat="!stdel ")
                        ]])))
            else:
                try:
                    await asyncio.sleep(
                        5)  # Waiting for 5 Sec for getting Correct User Input!
                    async with aiohttp.ClientSession() as session:
                        api_link = "https://api.streamtape.com/file/rename?login={}&key={}&file={}&name={}"
                        hit_api = await session.get(
                            api_link.format(Config.STREAMTAPE_API_USERNAME,
                                            Config.STREAMTAPE_API_PASS, token,
                                            new_filename))
                        data_f = await hit_api.json()
                        status = data_f['msg']
                        if status == "OK":
                            answers.append(
                                InlineQueryResultArticle(
                                    title="File Renamed!",
                                    description=
                                    f"Renamed to {new_filename} using {token}",
                                    input_message_content=
                                    InputTextMessageContent(
                                        message_text=
                                        f"Successfully Renamed file to - `{new_filename}`\n\nUsing `{token}`",
                                        parse_mode="Markdown",
                                        disable_web_page_preview=True)))
                            await bot.send_message(
                                chat_id=Config.LOG_CHANNEL,
                                text=
                                f"#STREAMTAPE_RENAME:\n\n[{query.from_user.first_name}](tg://user?id={query.from_user.id}) Renamed Streamtape File !!\n\n**New File Name:** {new_filename}\n\n**File Token:** `{token}`",
                                parse_mode="Markdown",
                                disable_web_page_preview=True)
                        else:
                            answers.append(
                                InlineQueryResultArticle(
                                    title="Can't Rename File!",
                                    description=f"Token: {token} is Invalid!",
                                    input_message_content=
                                    InputTextMessageContent(
                                        message_text=
                                        f"Can't Rename File to - `{new_filename}`\n\nUsing `{token}`",
                                        parse_mode="Markdown",
                                        disable_web_page_preview=True)))
                except Exception as e:
                    answers.append(
                        InlineQueryResultArticle(
                            title="Something Went Wrong!",
                            description=f"Error: {e}",
                            input_message_content=InputTextMessageContent(
                                message_text=
                                f"Something Went Wrong!\n\n**Error:** `{e}`",
                                parse_mode="Markdown",
                                disable_web_page_preview=True)))

        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(results=answers,
                               cache_time=0,
                               switch_pm_text="Error: Search timed out!",
                               switch_pm_parameter="help")
    elif search_query.startswith("!strmdel"):
        if not int(query.from_user.id) == Config.BOT_OWNER:
            answers.append(
                InlineQueryResultArticle(
                    title="You Can't Do That!",
                    description="This is only for Bot Owner!",
                    input_message_content=InputTextMessageContent(
                        message_text=
                        "This is only for Bot Owner!\n\nOnly Developer have Streamtape File Delete Rights!"
                    ),
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            InlineKeyboardButton("Support Group",
                                                 url="https://t.me/linux_repo")
                        ],
                         [
                             InlineKeyboardButton(
                                 "Developer", url="https://t.me/AbirHasan2005")
                         ]])))
        token = None
        try:
            token = search_query.split("!strmdel ")[1]
        except IndexError:
            print("Got IndexError - Skiping [token]")
            token = ""
        except Exception as error:
            print(f"Got Error - {error} - Skiping [token]")
        if token == "":
            answers.append(
                InlineQueryResultArticle(
                    title="!strmdel [token]",
                    description=
                    "Put Streamtape Remote Token to remove Remote from Streamtape Account!",
                    input_message_content=InputTextMessageContent(
                        message_text=
                        "This for Removing Remote URL from Streamtape Account via Remote Token.\n\n**Format:** `@Cloud_UPManager_Bot !strmdel `__[token]__",
                        parse_mode="Markdown",
                        disable_web_page_preview=True),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            "Remove Remote from Streamtape",
                            switch_inline_query_current_chat="!strmdel ")
                    ]])))
        else:
            try:
                async with aiohttp.ClientSession() as session:
                    api_link = "https://api.streamtape.com/remotedl/remove?login={}&key={}&id={}"
                    hit_api = await session.get(
                        api_link.format(Config.STREAMTAPE_API_USERNAME,
                                        Config.STREAMTAPE_API_PASS, token))
                    data_f = await hit_api.json()
                    status = data_f['msg']
                    if status == "OK":
                        answers.append(
                            InlineQueryResultArticle(
                                title="Removed Remote!",
                                description=
                                "Remote URL Removed from Streamtape Account!",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    f"Successfully Removed Remote URL from Streamtape Account!\n\n**Remote Token:** `{token}`",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)))
                        await bot.send_message(
                            chat_id=Config.LOG_CHANNEL,
                            text=
                            f"#REMOTE_URL_REMOVE:\n\n[{query.from_user.first_name}](tg://user?id={query.from_user.id}) Removed Remote URL from Streamtape Account !!\n\n**Remote Token:** `{token}`",
                            parse_mode="Markdown",
                            disable_web_page_preview=True)
                    else:
                        answers.append(
                            InlineQueryResultArticle(
                                title="Can't Remove Remote URL!",
                                description=f"Some Issues with Remote Token!",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    f"Can't Remove Remote URL!\n\nRemote Token: {token}\nHaving Some Issues.",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)))
            except Exception as e:
                answers.append(
                    InlineQueryResultArticle(
                        title="Something Went Wrong!",
                        description=f"Error: {e}",
                        input_message_content=InputTextMessageContent(
                            message_text=
                            f"Something Went Wrong!\n\n**Error:** `{e}`",
                            parse_mode="Markdown",
                            disable_web_page_preview=True)))

        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(results=answers,
                               cache_time=0,
                               switch_pm_text="Error: Search timed out!",
                               switch_pm_parameter="help")
    elif search_query.startswith("!stremote"):
        remote_link = None
        try:
            remote_link = search_query.split("!stremote ")[1]
        except IndexError:
            print("Got IndexError - Skiping [download_url]")
            remote_link = ""
        except Exception as error:
            print(f"Got Error - {error} - Skiping [download_url]")
        if remote_link == "":
            answers.append(
                InlineQueryResultArticle(
                    title="!stremote [download_url]",
                    description=
                    "Put Direct Download Link to Upload to Streamtape!",
                    input_message_content=InputTextMessageContent(
                        message_text=
                        "This for Uploading to Streamtape via Any Direct Download Link.\n\n**Format:** `@Cloud_UPManager_Bot !stremote `__[download_url]__",
                        parse_mode="Markdown",
                        disable_web_page_preview=True),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            "Add Remote to Streamtape",
                            switch_inline_query_current_chat="!stremote ")
                    ]])))
        else:
            try:
                async with aiohttp.ClientSession() as session:
                    api_link = "https://api.streamtape.com/remotedl/add?login={}&key={}&url={}"
                    hit_api = await session.get(
                        api_link.format(Config.STREAMTAPE_API_USERNAME,
                                        Config.STREAMTAPE_API_PASS,
                                        remote_link))
                    data_f = await hit_api.json()
                    status = data_f['msg']
                    if status == "OK":
                        token = data_f['result']['id']
                        answers.append(
                            InlineQueryResultArticle(
                                title="URL Added!",
                                description="Remote URL Added to List!",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    f"Successfully Added Remote URL( {remote_link} ) to Remote List!\n\n**Remote Token:** `{token}`",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True),
                                reply_markup=InlineKeyboardMarkup([[
                                    InlineKeyboardButton(
                                        "Show Status",
                                        switch_inline_query_current_chat=
                                        f"!show {token}")
                                ]])))
                        await bot.send_message(
                            chat_id=Config.LOG_CHANNEL,
                            text=
                            f"#REMOTE_URL_ADD:\n\n[{query.from_user.first_name}](tg://user?id={query.from_user.id}) Added Remote URL to Streamtape Account !!\n\n**Remote URL:** {remote_link}\n\n**Remote Token:** `{token}`",
                            parse_mode="Markdown",
                            disable_web_page_preview=True)
                    else:
                        answers.append(
                            InlineQueryResultArticle(
                                title="Can't Add Remote URL!",
                                description=f"Some Issues with Remote URL!",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    f"Can't Upload Remote URL!\n\nRemote Link: {remote_link}\nHaving Some Issues.",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)))
            except Exception as e:
                answers.append(
                    InlineQueryResultArticle(
                        title="Something Went Wrong!",
                        description=f"Error: {e}",
                        input_message_content=InputTextMessageContent(
                            message_text=
                            f"Something Went Wrong!\n\n**Error:** `{e}`",
                            parse_mode="Markdown",
                            disable_web_page_preview=True)))

        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(results=answers,
                               cache_time=0,
                               switch_pm_text="Error: Search timed out!",
                               switch_pm_parameter="help")
    elif search_query.startswith("!show"):
        input_f = None
        try:
            input_f = search_query.split("!show ")[1]
        except IndexError:
            print("Got IndexError - Skiping [token]")
            input_f = ""
        except Exception as error:
            print(f"Got Error - {error} - Skiping [token]")
            input_f = ""
        if input_f == "":
            answers.append(
                InlineQueryResultArticle(
                    title="!show [token]",
                    description=
                    "Put Streamtape Remote Access Token to Get Current Status of Streamtape Remote!",
                    input_message_content=InputTextMessageContent(
                        message_text=
                        "This for Getting Current Status of Streamtape Remote via Streamtape Remote Access Token. \n\n**Format:** `@Cloud_UPManager_Bot !show `__[token]__",
                        parse_mode="Markdown",
                        disable_web_page_preview=True),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            "Get Streamtape Remote Status",
                            switch_inline_query_current_chat="!show ")
                    ]])))
        else:
            try:
                async with aiohttp.ClientSession() as session:
                    api_link = "https://api.streamtape.com/remotedl/status?login={}&key={}&id={}"
                    hit_api = await session.get(
                        api_link.format(Config.STREAMTAPE_API_USERNAME,
                                        Config.STREAMTAPE_API_PASS, input_f))
                    data_f = await hit_api.json()
                    status = data_f['msg']
                    if status == "OK":
                        remote_URL = data_f["result"][f"{input_f}"][
                            "remoteurl"]
                        downloaded = data_f["result"][f"{input_f}"][
                            "bytes_loaded"]
                        total_size = data_f["result"][f"{input_f}"][
                            "bytes_total"]
                        added_at = data_f["result"][f"{input_f}"]["added"]
                        last_update = data_f["result"][f"{input_f}"][
                            "last_update"]
                        url = data_f["result"][f"{input_f}"]["url"]
                        answers.append(
                            InlineQueryResultArticle(
                                title=f"TOKEN: {input_f}",
                                description=
                                f"Uploaded: {humanbytes(downloaded)}, Total: {humanbytes(total_size)}",
                                input_message_content=InputTextMessageContent(
                                    message_text=
                                    f"**Token:** `{input_f}`\n**Uploaded:** `{humanbytes(downloaded)}`\n**Total:** `{humanbytes(total_size)}`\n**Added Remote at:** `{added_at}`\n**Last Updated at:** `{last_update}`\n\n**URL:** {url}",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True),
                                reply_markup=InlineKeyboardMarkup([[
                                    InlineKeyboardButton(
                                        "Show Status",
                                        switch_inline_query_current_chat=
                                        f"!show {input_f}")
                                ]])))
                    else:
                        answers.append(
                            InlineQueryResultArticle(
                                title="Nothing Found!",
                                description="Nothing ...",
                                input_message_content=InputTextMessageContent(
                                    message_text="Nothing Found ...",
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)))
            except Exception as e:
                answers.append(
                    InlineQueryResultArticle(
                        title="Something Went Wrong!",
                        description=f"Error: {e}",
                        input_message_content=InputTextMessageContent(
                            message_text=
                            f"Something Went Wrong!\n\n**Error:** `{e}`",
                            parse_mode="Markdown",
                            disable_web_page_preview=True)))

        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(results=answers,
                               cache_time=0,
                               switch_pm_text="Error: Search timed out!",
                               switch_pm_parameter="help")
async def check_progress_for_dl(aria2, gid, event, previous_message):
    #g_id = event.reply_to_message.from_user.id
    try:
        file = aria2.get_download(gid)
        complete = file.is_complete
        is_file = file.seeder
        if not complete:
            if not file.error_message:
                msg = ""
                # sometimes, this weird https://t.me/c/1220993104/392975
                # error creeps up
                # TODO: temporary workaround
                downloading_dir_name = "N/A"
                try:
                    # another derp -_-
                    # https://t.me/c/1220993104/423318
                    downloading_dir_name = str(file.name)
                except:
                    pass
                #
                if is_file is None:
                    msgg = f"Conn: {file.connections} <b>|</b> GID: <code>{gid}</code>"
                else:
                    msgg = f"P: {file.connections} | S: {file.num_seeders} <b>|</b> GID: <code>{gid}</code>"
                msg = f"\n`{downloading_dir_name}`"
                msg += f"\n<b>Speed</b>: {file.download_speed_string()}"
                msg += f"\n<b>Status</b>: {file.progress_string()} <b>of</b> {file.total_length_string()} <b>|</b> {file.eta_string()} <b>|</b> {msgg}"
                #msg += f"\nSize: {file.total_length_string()}"

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

                #msg += f"\nStatus: {file.status}"
                #msg += f"\nETA: {file.eta_string()}"
                #msg += f"\nGID: <code>{gid}</code>"
                inline_keyboard = []
                ikeyboard = []
                ikeyboard.append(
                    InlineKeyboardButton(
                        "Cancel 🚫",
                        callback_data=(f"cancel {gid}").encode("UTF-8")))
                inline_keyboard.append(ikeyboard)
                reply_markup = InlineKeyboardMarkup(inline_keyboard)
                if msg != previous_message:
                    if not file.has_failed:
                        await event.edit(msg, reply_markup=reply_markup)
                        previous_message = msg
                    else:
                        LOGGER.info(
                            f"Cancelling downloading of {file.name} may be due to slow torrent"
                        )
                        await event.edit(
                            f"Download cancelled :\n<code>{file.name}</code>\n\n #MetaDataError"
                        )
                        file.remove(force=True, files=True)
                        return False
            else:
                msg = file.error_message
                LOGGER.info(msg)
                await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                await event.edit(f"`{msg}`")
                return False
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await check_progress_for_dl(aria2, gid, event, previous_message)
        else:
            LOGGER.info(
                f"Downloaded Successfully: `{file.name} ({file.total_length_string()})` 🤒"
            )
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await event.edit(
                f"Downloaded Successfully: `{file.name} ({file.total_length_string()})` 🤒"
            )
            return True
    except aria2p.client.ClientException:
        await event.edit(
            f"Download cancelled :\n<code>{file.name} ({file.total_length_string()})</code>"
        )
    except MessageNotModified as ep:
        LOGGER.info(ep)
    except FloodWait as e:
        LOGGER.info(e)
        time.sleep(e.x)
    except RecursionError:
        file.remove(force=True, files=True)
        await event.edit("Download Auto Canceled :\n\n"
                         "Your Torrent/Link is Dead.".format(file.name))
        return False
    except Exception as e:
        LOGGER.info(str(e))
        if "not found" in str(e) or "'file'" in str(e):
            await event.edit(
                f"Download cancelled :\n<code>{file.name} ({file.total_length_string()})</code>"
            )
            return False
        else:
            LOGGER.info(str(e))
            await event.edit(
                "<u>error</u> :\n<code>{}</code> \n\n#error".format(str(e)))
            return False
Exemple #27
0
    async def send_flood_alert(user_id: Union[int, User]) -> None:
        user_ = await userge.bot.get_user_dict(user_id, attr_dict=True)
        buttons = InlineKeyboardMarkup([[
            InlineKeyboardButton("🚫  BAN",
                                 callback_data=f"bot_pm_ban_{user_.id}"),
            InlineKeyboardButton(
                "➖ Bot Antiflood [OFF]",
                callback_data="toggle_bot-antiflood_off",
            ),
        ]])
        found = False
        if FloodConfig.ALERT and (user_.id in FloodConfig.ALERT.keys()):
            found = True
            FloodConfig.ALERT[user_.id]["count"] += 1
            flood_count = FloodConfig.ALERT[user_.id]["count"]
        else:
            flood_count = FloodConfig.ALERT[user_.id]["count"] = 1

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

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

    lel = await message.reply("🔄 Memproses lagu...")
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name

    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton(text="Cara Penggunaan",
                             url="https://t.me/boimusicbotinfo/17")
    ]])

    audio = (message.reply_to_message.audio or message.reply_to_message.voice
             ) if message.reply_to_message else None
    url = get_url(message)

    if audio:
        if round(audio.duration / 60) > DURATION_LIMIT:
            raise DurationLimitError(
                f"❌ Durasi lagu melebihi {DURATION_LIMIT} menit tidak dapat diputar!"
            )

        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/a58d286859538f27dd48b.png"
        thumbnail = thumb_name
        duration = round(audio.duration / 60)
        views = "Locally added"
        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton(text="Cara Penggunaan",
                                 url=f"https://t.me/boimusicbotinfo/17")
        ]])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await converter.convert((
            await message.reply_to_message.download(file_name)
        ) if not path.isfile(path.join("downloads", file_name)) else file_name)
    elif url:
        try:
            results = YoutubeSearch(url, max_results=1).to_dict()
            # url = f"https://youtube.com{results[0]['url_suffix']}"
            #print(results)
            title = results[0]["title"][:40]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f'thumb{title}.jpg'
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, 'wb').write(thumb.content)
            duration = results[0]["duration"]
            url_suffix = results[0]["url_suffix"]
            views = results[0]["views"]
            keyboard = InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Tonton di YouTube", url=f"{url}")
            ]])
        except Exception as e:
            title = "NaN"
            thumb_name = "https://telegra.ph/file/a58d286859538f27dd48b.png"
            duration = "NaN"
            views = "NaN"
            keyboard = InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Tonton di YouTube",
                                     url=f"https://youtube.com")
            ]])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await converter.convert(youtube.download(url))
    else:
        await lel.edit("🔎 Lagu dalam pencarian...")
        sender_id = message.from_user.id
        user_id = message.from_user.id
        sender_name = message.from_user.first_name
        user_name = message.from_user.first_name
        rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

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

        except Exception as e:
            lel.edit(
                "Lagu tidak ditemukan, silahkan coba lagi dengan kata kunci yang lebih mendetail."
            )
            print(str(e))
            return

        keyboard = InlineKeyboardMarkup(
            [[InlineKeyboardButton(text="Watch On YouTube", url=f"{url}")]])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await converter.convert(youtube.download(url))

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        await message.reply_photo(
            photo="final.png",
            caption=f"Lagu dimasukkan kedalam antrian nomor {position}!",
            reply_markup=keyboard)
        os.remove("final.png")
        return await lel.delete()
    else:
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption="▶️ Memainkan lagu! \nAtas permintaan: {}.".format(
                message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Exemple #29
0
async def play(_, message: Message):

    lel = await message.reply(f"**{bn} :-** 🔎 Finding song...")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

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

        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        lel.edit(
            f"**{bn} :-** ❌ Song not found.\nTry another song or maybe try to spell it properly."
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")]])

    keyboard2 = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")]])

    audio = (message.reply_to_message.audio or message.reply_to_message.voice
             ) if message.reply_to_message else None

    if audio:
        await lel.edit_text(f"**{bn} :-** Hehe 🥴")

    elif url:
        file_path = await converter.convert(youtube.download(url))
    else:
        return await lel.edit_text(
            f"**{bn} :-** ❗ You did not give me anything to play!")

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        await message.reply_photo(
            photo=thumb_name,
            caption=
            f"**{bn} :-** Your requested song is **queued** at position #{position} !",
            reply_markup=keyboard2)
        return await lel.delete()
    else:
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo=thumb_name,
            reply_markup=keyboard,
            caption="▶️ **Playing** here the song requested by {}".format(
                message.from_user.mention()),
        )
        return await lel.delete()
Exemple #30
0
async def ytplay(_, message: Message):
    global blacks, is_playing, current_player, s, m, d

    if message.from_user.id in blacks:
        await message.reply_text("You're Blacklisted, So Stop Spamming.")
        return
    elif is_playing:
        list_of_admins = await getadmins(message.chat.id)
        if message.from_user.id in list_of_admins:
            pass
        else:
            d = await message.reply_text(
                text="stop interrupting while others playing!",
                disable_notification=True,
            )
            await asyncio.sleep(2)  # 2 sec delay before deletion
            await d.delete()
            await message.delete()
            return

    elif len(message.command) < 2:
        await message.reply_text("/youtube requires one argument")
        return
    
    await prepare(s, m, message)
    
    ydl_opts = {"format": "bestaudio"}
    query = kwairi(message)
    current_player = message.from_user.id
    is_playing = True

    m = await message.reply_text(f"Searching for `{query}`on YouTube")
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        link = f"https://youtube.com{results[0]['url_suffix']}"
        title = results[0]["title"]
        thumbnail = results[0]["thumbnails"][0]
        duration = results[0]["duration"]
        views = results[0]["views"]
        if time_to_seconds(duration)>=1800: #duration limit
            await m.edit("Bruh! Only songs within 30 Mins")
            is_playing=False
            return    
    except Exception as e:
        await m.edit(
            "Found Literally Nothing!, You Should Work On Your English."
        )
        is_playing=False
        print(str(e))
        return
    await m.edit("Processing Thumbnail.")

    await generate_cover(message, title, views, duration, thumbnail)

    await m.edit("Downloading Music.")
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(link, download=False)
        audio_file = ydl.prepare_filename(info_dict)
        ydl.process_info(info_dict)
        os.rename(audio_file, "audio.webm")
    await m.delete()
    m = await message.reply_photo(
        caption=f"Playing [{title}]({link}) Via YouTube #music\nRequested by {message.from_user.first_name}",
        photo="final.png",
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton("STOP", callback_data="end")]]
        ),
        parse_mode="markdown",
    )
    os.remove("final.png")
    s = await asyncio.create_subprocess_shell(
        "mpv audio.webm --no-video",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    await s.wait()
    await m.delete()
    is_playing = False