Пример #1
1
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
Пример #2
0
async def check_progress_for_dl(aria2, gid, event, previous_message):
    # g_id = event.reply_to_message.from_user.id
    try:
        file = aria2.get_download(gid)
        complete = file.is_complete
        is_file = file.seeder
        if not complete:
            if not file.error_message:
                msg = ""
                # sometimes, this weird https://t.me/c/1220993104/392975
                # error creeps up
                # TODO: temporary workaround
                downloading_dir_name = "N/A"
                try:
                    # another derp -_-
                    # https://t.me/c/1220993104/423318
                    downloading_dir_name = str(file.name)
                except:
                    pass
                #
                if is_file is None:
                    msgg = f"<b>➩ Connections : {file.connections} </b>"
                else:
                    msgg = f"<b>➩ Info :- P: {file.connections} || S: {file.num_seeders} </b>\n\n<b>🗑️ GID :</b> <code>{gid}</code>"
                msg = f"\n<b>📘 File Name :</b> `{downloading_dir_name}`\n\n<b>➩ Speed :</b> `{file.download_speed_string()}`"
                msg += f"\n<b>➩ Size :</b> `{file.total_length_string()}`"
                msg += f"\n<b>➩ Downloaded</b> : `{file.progress_string()}` \n<b>➩ ETA :</b> `{file.eta_string()}` \n {msgg}"
                inline_keyboard = []
                ikeyboard = []
                ikeyboard.append(
                    InlineKeyboardButton(
                        "❌ Cancel ❌",
                        callback_data=(f"cancel {gid}").encode("UTF-8")))
                inline_keyboard.append(ikeyboard)
                reply_markup = InlineKeyboardMarkup(inline_keyboard)
                if msg != previous_message:
                    if not file.has_failed:
                        try:
                            await event.edit(msg, reply_markup=reply_markup)
                        except FloodWait as e_e:
                            LOGGER.warning(f"Trying to sleep for {e_e}")
                            time.sleep(e_e.x)
                        except MessageNotModified as e_p:
                            LOGGER.info(e_p)
                            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                        previous_message = msg
                    else:
                        LOGGER.info(
                            f"Cancelling downloading of {file.name} may be due to slow torrent"
                        )
                        await event.edit(
                            f"**Download cancelled :**\n<code>{file.name}</code>\n\n #MetaDataError"
                        )
                        file.remove(force=True, files=True)
                        return False
            else:
                msg = file.error_message
                LOGGER.info(msg)
                await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
                await event.edit(f"`{msg}`")
                return False
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await check_progress_for_dl(aria2, gid, event, previous_message)
        else:
            LOGGER.info(
                f"<b> Leechd Successfully</b>: `{file.name} ({file.total_length_string()})` 🤒"
            )
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await event.edit(
                f"<b>Leech Successfully</b>:\n\n📙 <b>File Name</b>: \n`{file.name}`\n\n📀 <b>Total Size</b>: `〘{file.total_length_string()}〙`"
            )
            return True
    except aria2p.client.ClientException:
        await event.edit(
            f"Download cancelled :\n<code>{file.name} ({file.total_length_string()})</code>"
        )
    except MessageNotModified as ep:
        LOGGER.info(ep)
        await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
        await check_progress_for_dl(aria2, gid, event, previous_message)
    except FloodWait as e:
        LOGGER.info(e)
        time.sleep(e.x)
    except RecursionError:
        file.remove(force=True, files=True)
        await event.edit("*Download Auto Canceled :**\n\n"
                         "`Your Torrent/Link is Dead.`👺".format(file.name))
        return False
    except Exception as e:
        LOGGER.info(str(e))
        if "not found" in str(e) or "'file'" in str(e):
            await event.edit(
                f"Download cancelled :\n<code>{file.name} ({file.total_length_string()})</code>"
            )
            return False
        else:
            LOGGER.info(str(e))
            await event.edit(
                "<u>error</u> :\n<code>{}</code> \n\n#error".format(str(e)))
            return False
Пример #3
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **Processing**")

    try:
      conchat = await _.get_chat(message.chat.id)
      conv = conchat.linked_chat
      conid = conchat.linked_chat.id
      chid = conid
    except:
      await message.reply("Is chat even linked")
      return
    try:
      administrators = await get_administrators(conv)
    except:
      await message.reply("Am I admin of Channel")
    try:
        user = await USER.get_me()
    except:
        user.first_name = "helper"
    usar = user
    wew = usar.id
    try:
        # chatdetails = await USER.get_chat(chid)
        await _.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message.from_user.id:
                if message.chat.title.startswith("Channel Music: "):
                    await lel.edit(
                        "<b>Remember to add helper to your channel</b>",
                    )
                    pass

                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Add me as admin of yor channel  first</b>",
                    )
                    return

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

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>🔴 Flood Wait Error 🔴 \nUser {user.first_name} couldn't join your channel due to heavy requests for userbot! Make sure user is not banned in group."
                        "\n\nOr manually add assistant to your Group and try again</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} Userbot not in this chat, Ask channel admin to send /play command for first time or add {user.first_name} manually</i>"
        )
        return
    message.from_user.id
    message.from_user.first_name
    await lel.edit("🔎 **Finding**")
    message.from_user.id
    user_id = message.from_user.id
    message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"
    audio = (
        (message.reply_to_message.audio or message.reply_to_message.voice)
        if message.reply_to_message
        else None
    )
    if audio:
        if round(audio.duration / 60) > DURATION_LIMIT:
            raise DurationLimitError(
                f"❌ Videos longer than {DURATION_LIMIT} minute(s) aren't allowed to play!"
            )
        keyboard = InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton("📖 Playlist", callback_data="cplaylist"),
                    InlineKeyboardButton("Menu ⏯ ", callback_data="cmenu"),
                ],
                [InlineKeyboardButton(text="❌ Close", callback_data="ccls")],
            ]
        )
        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/f6086f8909fbfeb0844f2.png"
        thumbnail = thumb_name
        duration = round(audio.duration / 60)
        views = "Locally added"
        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
        )
    else:
        query = ""
        for i in message.command[1:]:
            query += " " + str(i)
        print(query)
        await lel.edit("🎵 **Processing**")
        ydl_opts = {"format": "bestaudio[ext=m4a]"}
        try:
            results = YoutubeSearch(query, max_results=1).to_dict()
            url = f"https://youtube.com{results[0]['url_suffix']}"
            # print(results)
            title = results[0]["title"][:40]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f"thumb{title}.jpg"
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, "wb").write(thumb.content)
            duration = results[0]["duration"]
            results[0]["url_suffix"]
            views = results[0]["views"]

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

        keyboard = InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton("📖 Playlist", callback_data="cplaylist"),
                    InlineKeyboardButton("Menu ⏯ ", callback_data="cmenu"),
                ],
                [InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")],
                [InlineKeyboardButton(text="❌ Close", callback_data="ccls")],
            ]
        )
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await convert(youtube.download(url))
    chat_id = chid
    if chat_id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(chat_id, file=file_path)
        qeue = que.get(chat_id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=f"#⃣ Your requested song **queued** at position {position}!",
            reply_markup=keyboard,
        )
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = chid
        que[chat_id] = []
        qeue = que.get(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(chat_id, file_path)
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption="▶️ **Playing** the song requested by {} via Youtube Music 😜 in Linked Channel".format(
                message.from_user.mention()
            ),
        )
        os.remove("final.png")
        return await lel.delete()
Пример #4
0
def mediadetection(client, message):
    user = message.from_user.id
    chat = message.chat.id
    max_file_size = MAX_FILE_SIZE  # Maximum file size for documents the bot will positively respond to.
    if not os.path.isdir('temp_download'):
        os.mkdir('temp_download/')

    file_size = message.document.file_size

    if file_size > max_file_size:

        if message.from_user.id != message.chat.id:
            logger.info(
                f'User (ID: {user}) sent a file ({round(file_size / 1048576, 2)}MB) larger than the defined maximum'
                f' file size ({round(max_file_size / 1048576, 2)}MB) in a group chat (ID: {message.chat.id}).'
            )
            message.reply_text(
                f'Sorry, but this file is too large for us to process. Some engines may not process'
                f' large files properly such as archives or even timeout after a certain period of time.'
                f'\n\nBe cautious when downloading the file and upload smaller files inside the file'
                f' if it is an archive.')

        else:
            logger.info(
                f'User ({user}) sent a file larger than the defined maximum file size'
                f' ({round(max_file_size / 1048576, 2)}MB).')
            message.reply_text(
                f'Sorry, but this file is too large for us to process. Try sending a file under '
                f'**{round(max_file_size / 1048576, 2)} MB**. \n\nOn a side note, some engines '
                f'may not process large files such as archives or even timeout after a certain period of'
                f' time. ')

        return

    msg = message.reply_text('__Downloading file...__', quote=True)

    if message.from_user.id != message.chat.id:
        download_path = client.download_media(message=message,
                                              file_name='temp_download/')
    else:
        download_path = client.download_media(message=message,
                                              file_name='temp_download/',
                                              progress=progressbar,
                                              progress_args=("downloading",
                                                             msg))

    logger.info(f"Downloaded File: {download_path}")

    response = replytofile(download_path, msg)
    msg.delete()  # Delete old reply, and send new one (for notification)

    filehash = findhash(download_path)
    vt_url = f'https://www.virustotal.com/gui/file/{filehash}'

    if response is None:
        response = f"__VirusTotal Analysis Summary__:\n\nHash: `{filehash}`\n\nLink: [Click Here]({vt_url})\n\nThis" \
                   f" file is still being analysed. Visit the link above or click \"Refresh Data\" after a minute to " \
                   f"check if your analysis results are ready"

        bttn = InlineKeyboardMarkup([[
            InlineKeyboardButton(text="Refresh Data",
                                 callback_data=f"refresh-{filehash}")
        ]])
    else:
        bttn = InlineKeyboardMarkup([[
            InlineKeyboardButton(text="Detailed Analysis",
                                 callback_data=f"detailed-{filehash}")
        ]])

    client.send_message(chat_id=chat,
                        text=response,
                        parse_mode='markdown',
                        disable_web_page_preview=True,
                        reply_markup=bttn,
                        reply_to_message_id=message.message_id)

    try:
        os.remove(download_path.replace('/', '//'))
    except OSError as e:
        logger.warning("File requested to be deleted does not exist!")
Пример #5
0
 async def callback_mm(callback_query: CallbackQuery):
     await callback_query.edit_message_text(
         " 𝐔𝐒𝐄𝐑𝐆𝐄-𝐗  𝗠𝗔𝗜𝗡 𝗠𝗘𝗡𝗨 ",
         reply_markup=InlineKeyboardMarkup(main_menu_buttons()))
Пример #6
0
async def button(bot, cmd: CallbackQuery):
    # Meh Lazy AF ...
    cb_data = cmd.data

    if "refreshmeh" in cb_data:
        if Config.UPDATES_CHANNEL:
            invite_link = await bot.create_chat_invite_link(
                int(Config.UPDATES_CHANNEL))
            try:
                user = await bot.get_chat_member(int(Config.UPDATES_CHANNEL),
                                                 cmd.message.chat.id)
                if user.status == "kicked":
                    await cmd.message.edit(
                        text=
                        "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/linux_repo).",
                        parse_mode="markdown",
                        disable_web_page_preview=True)
                    return
            except UserNotParticipant:
                await cmd.message.edit(
                    text=
                    "**You Still Didn't Join ☹️, Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            InlineKeyboardButton("🤖 Join Updates Channel",
                                                 url=invite_link.invite_link)
                        ],
                         [
                             InlineKeyboardButton("🔄 Refresh 🔄",
                                                  callback_data="refreshmeh")
                         ]]),
                    parse_mode="markdown")
                return
            except Exception:
                await cmd.message.edit(
                    text=
                    "Something went Wrong. Contact my [Support Group](https://t.me/linux_repo).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        await cmd.message.edit(
            text=Config.USAGE_WATERMARK_ADDER,
            parse_mode="Markdown",
            reply_markup=InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton("Developer",
                                         url="https://t.me/AbirHasan2005"),
                    InlineKeyboardButton("Support Group",
                                         url="https://t.me/linux_repo")
                ],
                 [
                     InlineKeyboardButton("Bots Channel",
                                          url="https://t.me/Discovery_Updates")
                 ]]),
            disable_web_page_preview=True)

    elif "lol" in cb_data:
        await cmd.answer(
            "Sir, that button not works XD\n\nPress Bottom Buttons to Set Position of Watermark!",
            show_alert=True)

    elif "lel" in cb_data:
        await cmd.answer(
            "Sir, that button not works XD\n\nPress Bottom Buttons to Set Size of Watermark",
            show_alert=True)

    elif (cb_data.startswith("position_") or cb_data.startswith("size_")):
        if Config.UPDATES_CHANNEL:
            invite_link = await bot.create_chat_invite_link(
                int(Config.UPDATES_CHANNEL))
            try:
                user = await bot.get_chat_member(int(Config.UPDATES_CHANNEL),
                                                 cmd.message.chat.id)
                if user.status == "kicked":
                    await cmd.message.edit(
                        text=
                        "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/linux_repo).",
                        parse_mode="markdown",
                        disable_web_page_preview=True)
                    return
            except UserNotParticipant:
                await cmd.message.edit(
                    text=
                    "**You Still Didn't Join ☹️, Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            InlineKeyboardButton("🤖 Join Updates Channel",
                                                 url=invite_link.invite_link)
                        ],
                         [
                             InlineKeyboardButton("🔄 Refresh 🔄",
                                                  callback_data="refreshmeh")
                         ]]),
                    parse_mode="markdown")
                return
            except Exception:
                await cmd.message.edit(
                    text=
                    "Something went Wrong. Contact my [Support Group](https://t.me/linux_repo).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        await bot.send_message(
            chat_id=Config.LOG_CHANNEL,
            text=
            f"#SETTINGS_SET: [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id}) Changed Settings!\n\n**User ID:** #id{cmd.from_user.id}\n**Data:** `{cb_data}`",
            parse_mode="Markdown",
            disable_web_page_preview=True,
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("Ban User",
                                     callback_data=f"ban_{cmd.from_user.id}")
            ]]))
        new_position = cb_data.split("_", 1)[1]
        if cb_data.startswith("position_"):
            await db.set_position(cmd.from_user.id, new_position)
        elif cb_data.startswith("size_"):
            await db.set_size(cmd.from_user.id, new_position)
        position_tag = None
        watermark_position = await db.get_position(cmd.from_user.id)
        if watermark_position == "5:main_h-overlay_h":
            position_tag = "Bottom Left"
        elif watermark_position == "main_w-overlay_w-5:main_h-overlay_h-5":
            position_tag = "Bottom Right"
        elif watermark_position == "main_w-overlay_w-5:5":
            position_tag = "Top Right"
        elif watermark_position == "5:5":
            position_tag = "Top Left"
        else:
            position_tag = "Top Left"

        size_tag = None
        watermark_size = await db.get_size(cmd.from_user.id)
        if int(watermark_size) == 5:
            size_tag = "5%"
        elif int(watermark_size) == 7:
            size_tag = "7%"
        elif int(watermark_size) == 10:
            size_tag = "10%"
        elif int(watermark_size) == 15:
            size_tag = "15%"
        elif int(watermark_size) == 20:
            size_tag = "20%"
        elif int(watermark_size) == 25:
            size_tag = "25%"
        elif int(watermark_size) == 30:
            size_tag = "30%"
        elif int(watermark_size) == 35:
            size_tag = "35%"
        elif int(watermark_size) == 40:
            size_tag = "40%"
        elif int(watermark_size) == 45:
            size_tag = "45%"
        else:
            size_tag = "7%"
            watermark_size = "7"
        try:
            await cmd.message.edit(
                text="Here you can set your Watermark Settings:",
                disable_web_page_preview=True,
                parse_mode="Markdown",
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            f"Watermark Position - {position_tag}",
                            callback_data="lol")
                    ],
                     [
                         InlineKeyboardButton("Set Top Left",
                                              callback_data=f"position_5:5"),
                         InlineKeyboardButton(
                             "Set Top Right",
                             callback_data=f"position_main_w-overlay_w-5:5")
                     ],
                     [
                         InlineKeyboardButton(
                             "Set Bottom Left",
                             callback_data=f"position_5:main_h-overlay_h"),
                         InlineKeyboardButton(
                             "Set Bottom Right",
                             callback_data=
                             f"position_main_w-overlay_w-5:main_h-overlay_h-5")
                     ],
                     [
                         InlineKeyboardButton(f"Watermark Size - {size_tag}",
                                              callback_data="lel")
                     ],
                     [
                         InlineKeyboardButton("5%", callback_data=f"size_5"),
                         InlineKeyboardButton("7%", callback_data=f"size_7"),
                         InlineKeyboardButton("10%", callback_data=f"size_10"),
                         InlineKeyboardButton("15%", callback_data=f"size_15"),
                         InlineKeyboardButton("20%", callback_data=f"size_20")
                     ],
                     [
                         InlineKeyboardButton("25%", callback_data=f"size_25"),
                         InlineKeyboardButton("30%", callback_data=f"size_30"),
                         InlineKeyboardButton("35%", callback_data=f"size_30"),
                         InlineKeyboardButton("40%", callback_data=f"size_40"),
                         InlineKeyboardButton("45%", callback_data=f"size_45")
                     ]]))
        except MessageNotModified:
            pass

    elif cb_data.startswith("ban_"):
        if Config.UPDATES_CHANNEL == None:
            await cmd.answer("Sorry Sir, You didn't Set any Updates Channel!",
                             show_alert=True)
            return
        try:
            user_id = cb_data.split("_", 1)[1]
            await bot.kick_chat_member(chat_id=Config.UPDATES_CHANNEL,
                                       user_id=int(user_id))
            await cmd.answer("User Banned from Updates Channel!",
                             show_alert=True)
        except Exception as e:
            await cmd.answer(f"Can't Ban Him!\n\nError: {e}", show_alert=True)
Пример #7
0
async def oynat(_, message: Message):

    lel = await message.reply("🔄 **Işleme alındı ** Parça...")
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name

    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton(text="🔊 Channel", url="https://t.me/RgChannell")
    ]])

    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"❌ Daha uzun videolar {DURATION_LIMIT} minute(s) oynamasına izin verilmiyor !"
            )

        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/a4fa687ed647cfef52402.jpg"
        thumbnail = thumb_name
        duration = round(audio.duration / 60)
        views = "Locally added"
        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton(text="🔊 Channel",
                                 url=f"https://t.me/RgChannell")
        ]])
        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="Watch On YouTube 🎬", url=f"{url}")
            ]])
        except Exception as e:
            title = "NaN"
            thumb_name = "https://telegra.ph/file/a4fa687ed647cfef52402.jpg"
            duration = "NaN"
            views = "NaN"
            keyboard = InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Watch On 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("🔎 **Aranıyor**  Parça...")
        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("🎵 **işleme alındı** Parça...")
        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(
                "❌ Şarkı bulunamadı .\n\nBaşka bir şarkı deneyin veya belki düzgün heceleyin."
            )
            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"#⃣ İstediğiniz şarkı **Sıraya** Eklendi {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=
            "▶️ **Oynatılıyor** burada istenen şarkı {} RG Muzik Aracılığıyla 😜"
            .format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Пример #8
0
async def start(client, message: pyrogram.types.Message):

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

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

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

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

    if len(message.command) != 2:

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

        reply_markup = InlineKeyboardMarkup(buttons)

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

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

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

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

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

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

    files_ = await get_file_details(file_id)
    if not files_:
        pre, file_id = ((
            base64.urlsafe_b64decode(data + "=" *
                                     (-len(data) % 4))).decode("ascii")).split(
                                         "_", 1)
        try:
            msg = await client.send_cached_media(
                chat_id=message.from_user.id,
                file_id=file_id,
                protect_content=True if pre == 'filep' else False,
            )
            filetype = msg.media
            file = getattr(msg, filetype)
            title = file.file_name
            size = get_size(file.file_size)
            f_caption = f"<code>{title}</code>"
            if CUSTOM_FILE_CAPTION:
                try:
                    f_caption = CUSTOM_FILE_CAPTION.format(
                        file_name='' if title is None else title,
                        file_size='' if size is None else size,
                        file_caption='')
                except:
                    return
            await msg.edit_caption(f_caption)
            return
        except:
            pass
        return await message.reply('No such file exist.')
    files = files_[0]
    title = files.file_name
    size = get_size(files.file_size)
    f_caption = files.caption
    if CUSTOM_FILE_CAPTION:
        try:
            f_caption = CUSTOM_FILE_CAPTION.format(
                file_name='' if title is None else title,
                file_size='' if size is None else size,
                file_caption='' if f_caption is None else f_caption)
        except Exception as e:
            logger.exception(e)
            f_caption = f_caption
    if f_caption is None:
        f_caption = f"{files.file_name}"
    await client.send_cached_media(
        chat_id=message.from_user.id,
        file_id=file_id,
        caption=f_caption,
        protect_content=True if pre == 'filep' else False,
    )
Пример #9
0
async def settings(client, message):
    userid = message.from_user.id if message.from_user else None
    if not userid:
        return await message.reply(
            f"You are anonymous admin. Use /connect {message.chat.id} in PM")
    chat_type = 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 message.reply_text(
                    "Make sure I'm present in your group!!", quote=True)
                return
        else:
            await message.reply_text("I'm not connected to any groups!",
                                     quote=True)
            return

    elif chat_type in ["group", "supergroup"]:
        grp_id = message.chat.id
        title = message.chat.title

    else:
        return

    st = await client.get_chat_member(grp_id, userid)
    if (st.status != "administrator" and st.status != "creator"
            and str(userid) not in ADMINS):
        return

    settings = await get_settings(grp_id)

    if settings is not None:
        buttons = [
            [
                InlineKeyboardButton(
                    'Filter Button',
                    callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
                ),
                InlineKeyboardButton(
                    'Single' if settings["button"] else 'Double',
                    callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
                ),
            ],
            [
                InlineKeyboardButton(
                    'Redirect To',
                    callback_data=
                    f'setgs#redirect_to#{settings["redirect_to"]}#{grp_id}',
                ),
                InlineKeyboardButton(
                    '👤 PM' if settings["redirect_to"] == "PM" else '📄 Chat',
                    callback_data=
                    f'setgs#redirect_to#{settings["redirect_to"]}#{grp_id}',
                ),
            ],
            [
                InlineKeyboardButton(
                    'Bot PM',
                    callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
                ),
                InlineKeyboardButton(
                    '✅ Yes' if settings["botpm"] else '❌ No',
                    callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
                ),
            ],
            [
                InlineKeyboardButton(
                    'File Secure',
                    callback_data=
                    f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
                ),
                InlineKeyboardButton(
                    '✅ Yes' if settings["file_secure"] else '❌ No',
                    callback_data=
                    f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
                ),
            ],
            [
                InlineKeyboardButton(
                    'IMDB',
                    callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
                ),
                InlineKeyboardButton(
                    '✅ Yes' if settings["imdb"] else '❌ No',
                    callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
                ),
            ],
            [
                InlineKeyboardButton(
                    'Spell Check',
                    callback_data=
                    f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
                ),
                InlineKeyboardButton(
                    '✅ Yes' if settings["spell_check"] else '❌ No',
                    callback_data=
                    f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
                ),
            ],
            [
                InlineKeyboardButton(
                    'Welcome',
                    callback_data=
                    f'setgs#welcome#{settings["welcome"]}#{grp_id}',
                ),
                InlineKeyboardButton(
                    '✅ Yes' if settings["welcome"] else '❌ No',
                    callback_data=
                    f'setgs#welcome#{settings["welcome"]}#{grp_id}',
                ),
            ],
        ]

        reply_markup = InlineKeyboardMarkup(buttons)

        await message.reply_text(
            text=f"<b>Change Your Settings for {title} As Your Wish ⚙</b>",
            reply_markup=reply_markup,
            disable_web_page_preview=True,
            parse_mode="html",
            reply_to_message_id=message.message_id)
Пример #10
0
async def play(client: Client, message_: Message):
    audio = (message_.reply_to_message.audio or message_.reply_to_message.voice
             ) if message_.reply_to_message else None
    chat_id = message_.chat.id
    res = await message_.reply_text("✯W2H✯=🔄 Processing... Song")

    if audio:
        if round(audio.duration / 60) > DURATION_LIMIT:
            raise DurationLimitError(
                f"Videos longer than {DURATION_LIMIT} minute(s) aren't allowed, the provided video is {audio.duration / 60} minute(s)"
            )

        file_name = audio.file_id + audio.file_name.split(".")[-1]
        file_path = await convert(await
                                  message_.reply_to_message.download(file_name)
                                  )
    else:
        messages = [message_]
        text = ""
        offset = None
        length = None

        if message_.reply_to_message:
            messages.append(message_.reply_to_message)

        for message in messages:
            if offset:
                break

            if message.entities:
                for entity in message.entities:
                    if entity.type == "url":
                        text = message.text or message.caption
                        offset, length = entity.offset, entity.length
                        break

        if offset == None:
            await res.edit_text("❕ You did not give me anything to play.")
            return

        url = text[offset:offset + length]

        file_path = await convert(download(url))

    if message_.chat.id in tgcalls.pytgcalls.active_calls:
        position = sira.add(message_.chat.id, file_path)
        await res.edit_text(f"✯W2H✯=#️⃣ Queued at position {position}.")
    else:
        await res.edit_text("✯W2H✯=▶️ Playing... Song")
        res.delete
        m = await client.send_photo(
            chat_id=message_.chat.id,
            photo="Others/thumbnail2.png",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("Support⚡️",
                                     url="https://t.me/RAVAN102030")
            ]]),
            caption=
            f"Playing Your song Via  [✯W2H✯](https://t.me/RAVAN102030).",
        )
        tgcalls.pytgcalls.join_group_call(message_.chat.id, file_path)
Пример #11
0
async def user(c: Client, m: Message):
    args = m.text.split(' ', 1)

    try:
        search_query = args[1]
    except BaseException:
        if m.reply_to_message:
            search_query = m.reply_to_message.text
        else:
            await m.reply_text("Format: /user <username>")
            return

    jikan = jikanpy.jikan.Jikan()

    try:
        user = jikan.user(search_query)
    except jikanpy.APIException:
        await m.reply_text("Username not found.")
        return

    progress_message = await m.reply_text("Searching...")

    date_format = "%Y-%m-%d"
    if user['image_url'] is None:
        img = "https://cdn.myanimelist.net/images/questionmark_50.gif"
    else:
        img = user['image_url']

    try:
        user_birthday = datetime.datetime.fromisoformat(user['birthday'])
        user_birthday_formatted = user_birthday.strftime(date_format)
    except BaseException:
        user_birthday_formatted = "Unknown"

    user_joined_date = datetime.datetime.fromisoformat(user['joined'])
    user_joined_date_formatted = user_joined_date.strftime(date_format)

    for entity in user:
        if user[entity] is None:
            user[entity] = "Unknown"

    caption = ""

    caption += textwrap.dedent(f"""
    **Username**: [{user['username']}]({user['url']})

    **Gender**: `{user['gender']}`
    **Birthday**: `{user_birthday_formatted}`
    **Joined**: `{user_joined_date_formatted}`
    **Days wasted watching anime**: `{user['anime_stats']['days_watched']}`
    **Days wasted reading manga**: `{user['manga_stats']['days_read']}`

    """)

    buttons = [[InlineKeyboardButton(info_btn, url=user['url'])]]

    await m.reply_photo(photo=img,
                        caption=caption,
                        parse_mode="markdown",
                        reply_markup=InlineKeyboardMarkup(buttons))
    await progress_message.delete()
Пример #12
0
async def pmfilter(client, message):
    me = await message._client.get_me()
    await message.reply_text( f"""<b>👋🏻 Hi {message.from_user.first_name}!</b>
I am Yᴇᴀɢᴇʀɪsᴛ Delete Events bot, I can delete Service message. Just Add me in group as admin A bot by @Animemusicarchive6.""",
                             reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(text="🔶 ADD Me 🔶",url=f"http://t.me/Yeageristdelteevent_bot?startgroup=true")]]),
                             quote=True)
Пример #13
0
async def notice_(_, c_q: CallbackQuery):
    try:
        query_ = c_q.data
        split_ = query_.split("_", 1)
        id_ = split_[-1]
        notice_path = "userge/xcache/notice.json"
        if not os.path.exists(notice_path):
            await c_q.answer("This message doesn't exist anymore",
                             show_alert=True)
            return
        with open(notice_path) as f:
            n_data = ujson.load(f)
            view_data = n_data.get(id_)
        user_ = c_q.from_user.id
        found = await SEEN_BY.find_one({"_id": id_})
        if "seen" not in c_q.data:
            try:
                users_ = found["seen"]
                seen_by = found["user_first_names"]
            except BaseException:
                users_ = []
                seen_by = []
            if user_ in users_:
                pass
            else:
                users_.append(user_)
                seen_by.append((await userge.get_users(user_)).first_name)
            await SEEN_BY.update_one({"_id": id_}, {"$set": {
                "seen": users_
            }},
                                     upsert=True)
            await SEEN_BY.update_one({"_id": id_},
                                     {"$set": {
                                         "user_first_names": seen_by
                                     }},
                                     upsert=True)
            await c_q.answer(view_data["notice"], show_alert=True)
            btn_ = InlineKeyboardMarkup([
                [
                    InlineKeyboardButton(text="What is it!!?",
                                         callback_data=f"notice_{id_}"),
                    InlineKeyboardButton(text="Seen by.",
                                         callback_data=f"noticeseen_{id_}"),
                ],
            ])
            try:
                await c_q.edit_message_text(
                    f"**Attention everyone!!!**\n👁‍🗨 **Seen by:** {len(users_)} people.",
                    reply_markup=btn_,
                )
            except MessageNotModified:
                pass
        else:
            if user_ not in Config.OWNER_ID and user_ not in Config.TRUSTED_SUDO_USERS:
                await c_q.answer(
                    "Only owner or trusted sudo users can see this list.",
                    show_alert=True,
                )
            else:
                users_ = found["seen"]
                seen_by = found["user_first_names"]
                list_ = f"Notice seen by: [{len(users_)}]\n\n"
                for one in seen_by:
                    list_ += f"• {one}\n"
                await c_q.answer(list_, show_alert=True)
    except BaseException:
        tb = traceback.format_exc()
        await userge.send_message(Config.LOG_CHANNEL_ID,
                                  f"#ATTENTION\n\n```{tb}```")
Пример #14
0
async def owo(client, inline_query):
    string_given = inline_query.query.lower()
    if "modapk" in inline_query.query.lower():
        if not " " in inline_query.query.lower():
            return
        string_given = inline_query.query.lower()
        sgname = string_given.split(" ", maxsplit=1)[1]
        print(sgname)
        PabloEscobar = (
            f"https://an1.com/tags/MOD/?story={sgname}&do=search&subaction=search"
        )
        r = requests.get(PabloEscobar)
        results = []
        soup = BeautifulSoup(r.content, "html5lib")
        mydivs = soup.find_all("div", {"class": "search-results"})
        Pop = soup.find_all("div", {"class": "title"})
        cnte = len(mydivs)
        for cnt in range(cnte):
            sucker = mydivs[cnt]
            pH9 = sucker.find("a").contents[0]
            file_name = pH9
            pH = sucker.findAll("img")
            imme = pH[0]["src"]
            Pablo = Pop[0].a["href"]
            ro = requests.get(Pablo)
            soupe = BeautifulSoup(ro.content, "html5lib")
            myopo = soupe.find_all("div", {"class": "item"})
            capt = f"**{file_name}** \n** {myopo[0].text}**\n**{myopo[1].text}**\n**{myopo[2].text}**\n**{myopo[3].text}**"
            mydis0 = soupe.find_all("a", {"class": "get-product"})
            Lol9 = mydis0[0]
            lemk = "https://an1.com" + Lol9["href"]

            results.append(
                InlineQueryResultPhoto(
                    photo_url=imme,
                    title=file_name,
                    caption=capt,
                    reply_markup=InlineKeyboardMarkup(
                        [
                            [
                                InlineKeyboardButton(
                                    text="<<! Download Link!>>",
                                    callback_data=f"apk_{lemk}",
                                ),
                            ]
                        ]
                    ),
                )
            )
        await client.answer_inline_query(inline_query.id, cache_time=0, results=results)
    elif "not4u" in string_given:
        if not ";" in string_given:
            return
        ok = string_given.split(" ", maxsplit=1)[1]
        user, msg = ok.split(";")
        fu = int(user) if user.isdigit() else user
        try:
            ui = await Friday.get_users(fu)
        except BaseException as e:
            logging.error(str(e))
            return
        owo = (
            f"@{ui.username}"
            if ui.username
            else f"[{ui.first_name}](tg://user?id={ui.id})"
        )
        chars = string.hexdigits
        randomc = "".join(choice(chars) for _ in range(4))
        stark_data = {"secret_code": randomc, "id": ui.id, "msg": msg}
        db_s.insert(stark_data)
        texts = f"Everyone Except {owo} Can Read This Message. \nClick Below To Check Message! \n**Note :** `Only He/She Can't Open It!`"
        ok_s = [
            (
                InlineQueryResultArticle(
                    title="OwO! Not For You",
                    reply_markup=InlineKeyboardMarkup(
                        [
                            [
                                InlineKeyboardButton(
                                    text="Show Message !", callback_data=f"nu_{randomc}"
                                )
                            ]
                        ]
                    ),
                    input_message_content=InputTextMessageContent(texts),
                )
            )
        ]
        await client.answer_inline_query(inline_query.id, cache_time=0, results=ok_s)
    elif "whisper" in string_given:
        if not ";" in string_given:
            return
        ok = string_given.split(" ", maxsplit=1)[1]
        user, msg = ok.split(";")
        fu = int(user) if user.isdigit() else user
        try:
            ui = await Friday.get_users(fu)
        except BaseException as e:
            logging.error(str(e))
            return
        owo = (
            f"@{ui.username}"
            if ui.username
            else f"[{ui.first_name}](tg://user?id={ui.id})"
        )
        chars = string.hexdigits
        randomc = "".join(choice(chars) for _ in range(4))
        stark_data = {"secret_code": randomc, "id": ui.id, "msg": msg}
        db_m.insert(stark_data)
        texts = f"A Whisper Has Been Sent For {owo} . \nClick Below To Check Message! \n**Note :** `Only He/She Can Open It!`"
        ok_s = [
            (
                InlineQueryResultArticle(
                    title="Ssh! This is A Secret Message",
                    reply_markup=InlineKeyboardMarkup(
                        [
                            [
                                InlineKeyboardButton(
                                    text="Show Message !", callback_data=f"sc_{randomc}"
                                )
                            ]
                        ]
                    ),
                    input_message_content=InputTextMessageContent(texts),
                )
            )
        ]
        await client.answer_inline_query(inline_query.id, cache_time=0, results=ok_s)
    elif "help" in string_given:
        total_ = len(CMD_LIST)
        bttn = [
            [
                InlineKeyboardButton(
                    text="Main Command Help", callback_data=f"make_basic_button_True"
                )
            ]
        ]
        if Config.LOAD_UNOFFICIAL_PLUGINS:
            total_ = len(XTRA_CMD_LIST) + len(CMD_LIST)
            bttn = [
                [
                    InlineKeyboardButton(
                        text="Xtra Command Help",
                        callback_data=f"make_basic_button_False",
                    )
                ],
                [
                    InlineKeyboardButton(
                        text="Main Command Help",
                        callback_data=f"make_basic_button_True",
                    )
                ],
            ]
        nice_text = f"**FridayUserBot Commands** \n**Friday Version :** __{friday_version}__ \n**PyroGram Version :** __{__version__}__ \n**Total Plugins Loaded :** __{total_}__"
        await client.answer_inline_query(
            inline_query.id,
            cache_time=0,
            results=[
                (
                    InlineQueryResultArticle(
                        title="Help Article!",
                        reply_markup=InlineKeyboardMarkup(bttn),
                        input_message_content=InputTextMessageContent(nice_text),
                    )
                )
            ],
        )
Пример #15
0
async def VidWatermarkAdder(bot, cmd):
    if not await db.is_user_exist(cmd.from_user.id):
        await db.add_user(cmd.from_user.id)
        await bot.send_message(
            Config.LOG_CHANNEL,
            f"#NEW_USER: \n\nNew User [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id}) started @{Config.BOT_USERNAME} !!"
        )
    if Config.UPDATES_CHANNEL:
        invite_link = await bot.create_chat_invite_link(
            int(Config.UPDATES_CHANNEL))
        try:
            user = await bot.get_chat_member(int(Config.UPDATES_CHANNEL),
                                             cmd.from_user.id)
            if user.status == "kicked":
                await bot.send_message(
                    chat_id=cmd.from_user.id,
                    text=
                    "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/linux_repo).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        except UserNotParticipant:
            await bot.send_message(
                chat_id=cmd.from_user.id,
                text=
                "**Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton("🤖 Join Updates Channel",
                                             url=invite_link.invite_link)
                    ],
                     [
                         InlineKeyboardButton("🔄 Refresh 🔄",
                                              callback_data="refreshmeh")
                     ]]),
                parse_mode="markdown")
            return
        except Exception:
            await bot.send_message(
                chat_id=cmd.from_user.id,
                text=
                "Something went Wrong. Contact my [Support Group](https://t.me/linux_repo).",
                parse_mode="markdown",
                disable_web_page_preview=True)
            return
    ## --- Noobie Process --- ##
    if (cmd.photo
            or (cmd.document and cmd.document.mime_type.startswith("image/"))):
        editable = await cmd.reply_text("Downloading Image ...")
        dl_loc = Config.DOWN_PATH + "/" + str(cmd.from_user.id) + "/"
        watermark_path = Config.DOWN_PATH + "/" + str(
            cmd.from_user.id) + "/thumb.jpg"
        await asyncio.sleep(5)
        c_time = time.time()
        the_media = await bot.download_media(
            message=cmd,
            file_name=watermark_path,
            progress=progress_for_pyrogram,
            progress_args=("Downloading Sir ...", editable, c_time))
        await editable.delete()
        await cmd.reply_text(
            "This Saved as Next Video Watermark!\n\nNow Send any Video to start adding Watermark to the Video!"
        )
        return
    else:
        pass
    working_dir = Config.DOWN_PATH + "/WatermarkAdder/"
    if not os.path.exists(working_dir):
        os.makedirs(working_dir)
    watermark_path = Config.DOWN_PATH + "/" + str(
        cmd.from_user.id) + "/thumb.jpg"
    if not os.path.exists(watermark_path):
        await cmd.reply_text(
            "You Didn't Set Any Watermark!\n\nSend any JPG or PNG Picture ...")
        return
    file_type = cmd.video or cmd.document
    if not file_type.mime_type.startswith("video/"):
        await cmd.reply_text("This is not a Video!")
        return
    status = Config.DOWN_PATH + "/WatermarkAdder/status.json"
    if os.path.exists(status):
        await cmd.reply_text(
            "Sorry, Currently I am busy with another Task!\n\nTry Again After Sometime!"
        )
        return
    preset = Config.PRESET
    editable = await cmd.reply_text("Downloading Video ...",
                                    parse_mode="Markdown")
    with open(status, "w") as f:
        statusMsg = {
            'chat_id': cmd.from_user.id,
            'message': editable.message_id
        }
        json.dump(statusMsg, f, indent=2)
    dl_loc = Config.DOWN_PATH + "/WatermarkAdder/" + str(
        cmd.from_user.id) + "/"
    if not os.path.isdir(dl_loc):
        os.makedirs(dl_loc)
    the_media = None
    logs_msg = None
    user_info = f"**UserID:** #id{cmd.from_user.id}\n**Name:** [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id})"
    ## --- Done --- ##
    try:
        forwarded_video = await cmd.forward(Config.LOG_CHANNEL)
        logs_msg = await bot.send_message(
            chat_id=Config.LOG_CHANNEL,
            text=f"Download Started!\n\n{user_info}",
            reply_to_message_id=forwarded_video.message_id,
            disable_web_page_preview=True,
            parse_mode="Markdown",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("Ban User",
                                     callback_data=f"ban_{cmd.from_user.id}")
            ]]))
        await asyncio.sleep(5)
        c_time = time.time()
        the_media = await bot.download_media(
            message=cmd,
            file_name=dl_loc,
            progress=progress_for_pyrogram,
            progress_args=("Downloading Sir ...", editable, c_time))
        if (the_media is None):
            await delete_trash(status)
            await delete_trash(the_media)
            print(f"Download Failed: {err}")
            await editable.edit("Unable to Download The Video!")
            return
    except Exception as err:
        await delete_trash(status)
        await delete_trash(the_media)
        print(f"Download Failed: {err}")
        await editable.edit("Unable to Download The Video!")
        return
    position_tag = None
    watermark_position = await db.get_position(cmd.from_user.id)
    if watermark_position == "5:main_h-overlay_h":
        position_tag = "Bottom Left"
    elif watermark_position == "main_w-overlay_w-5:main_h-overlay_h-5":
        position_tag = "Bottom Right"
    elif watermark_position == "main_w-overlay_w-5:5":
        position_tag = "Top Right"
    elif watermark_position == "5:5":
        position_tag = "Top Left"
    else:
        position_tag = "Top Left"
        watermark_position = "5:5"

    size_tag = None
    watermark_size = await db.get_size(cmd.from_user.id)
    if int(watermark_size) == 5:
        size_tag = "5%"
    elif int(watermark_size) == 7:
        size_tag = "7%"
    elif int(watermark_size) == 10:
        size_tag = "10%"
    elif int(watermark_size) == 15:
        size_tag = "15%"
    elif int(watermark_size) == 20:
        size_tag = "20%"
    elif int(watermark_size) == 25:
        size_tag = "25%"
    elif int(watermark_size) == 30:
        size_tag = "30%"
    elif int(watermark_size) == 35:
        size_tag = "35%"
    elif int(watermark_size) == 40:
        size_tag = "40%"
    elif int(watermark_size) == 45:
        size_tag = "45%"
    else:
        size_tag = "7%"
        watermark_size = "7"
    await editable.edit(
        f"Trying to Add Watermark to the Video at {position_tag} Corner ...\n\nPlease Wait!"
    )
    duration = 0
    metadata = extractMetadata(createParser(the_media))
    if metadata.has("duration"):
        duration = metadata.get('duration').seconds
    the_media_file_name = os.path.basename(the_media)
    main_file_name = os.path.splitext(the_media_file_name)[0]
    output_vid = main_file_name + "_[" + str(cmd.from_user.id) + "]_[" + str(
        time.time()) + "]_[@AbirHasan2005]" + ".mp4"
    progress = Config.DOWN_PATH + "/WatermarkAdder/" + str(
        cmd.from_user.id) + "/progress.txt"
    try:
        # WOW! Nice XD
        # Meh Always NOOB
        output_vid = await vidmark(the_media, editable, progress,
                                   watermark_path, output_vid, duration,
                                   logs_msg, status, preset,
                                   watermark_position, watermark_size)
    except Exception as err:
        print(f"Unable to Add Watermark: {err}")
        await editable.edit("Unable to add Watermark!")
        await logs_msg.edit(
            f"#ERROR: Unable to add Watermark!\n\n**Error:** `{err}`")
        await delete_all()
        return
    if output_vid == None:
        await editable.edit("Something went wrong!")
        await logs_msg.edit("#ERROR: Something went wrong!")
        await delete_all()
        return
    await editable.edit("Watermark Added Successfully!\n\nTrying to Upload ..."
                        )
    await logs_msg.edit(
        "Watermark Added Successfully!\n\nTrying to Upload ...",
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("Ban User",
                                 callback_data=f"ban_{cmd.from_user.id}")
        ]]))
    width = 100
    height = 100
    duration = 0
    metadata = extractMetadata(createParser(output_vid))
    if metadata.has("duration"):
        duration = metadata.get('duration').seconds
    if metadata.has("width"):
        width = metadata.get("width")
    if metadata.has("height"):
        height = metadata.get("height")
    video_thumbnail = None
    try:
        video_thumbnail = Config.DOWN_PATH + "/WatermarkAdder/" + str(
            cmd.from_user.id) + "/" + str(time.time()) + ".jpg"
        ttl = random.randint(0, int(duration) - 1)
        file_genertor_command = [
            "ffmpeg", "-ss",
            str(ttl), "-i", output_vid, "-vframes", "1", video_thumbnail
        ]
        process = await asyncio.create_subprocess_exec(
            *file_genertor_command,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, stderr = await process.communicate()
        e_response = stderr.decode().strip()
        t_response = stdout.decode().strip()
        print(e_response)
        print(t_response)
        Image.open(video_thumbnail).convert("RGB").save(video_thumbnail)
        img = Image.open(video_thumbnail)
        img.resize((width, height))
        img.save(video_thumbnail, "JPEG")
    except Exception as err:
        print(f"Error: {err}")
    # --- Upload --- #
    sent_vid = None
    file_size = os.path.getsize(output_vid)
    if int(file_size) > 2097152000:
        await editable.edit(
            f"Sorry Sir,\n\nFile Size Become {humanbytes(file_size)} !!\nI can't Upload to Telegram!\n\nSo Now Uploading to Streamtape ..."
        )
        try:
            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(output_vid, '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 = output_vid.split("/")[-1].replace("_", " ")
                text_edit = f"File Uploaded to Streamtape!\n\n**File Name:** `{filename}`\n**Size:** `{humanbytes(file_size)}`\n**Link:** `{download_link}`"
                await editable.edit(text_edit,
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True,
                                    reply_markup=InlineKeyboardMarkup([[
                                        InlineKeyboardButton("Open Link",
                                                             url=download_link)
                                    ]]))
                await logs_msg.edit(text_edit,
                                    parse_mode="Markdown",
                                    disable_web_page_preview=True)
        except Exception as e:
            print(f"Error: {e}")
            await editable.edit(
                "Sorry, Something went wrong!\n\nCan't Upload to Streamtape. You can report at [Support Group](https://t.me/linux_repo)"
            )
            await logs_msg.edit(
                f"Got Error While Uploading to Streamtape!\n\nError: {e}")
        await delete_all()
        return

    await asyncio.sleep(5)
    try:
        c_time = time.time()
        sent_vid = await bot.send_video(
            chat_id=cmd.chat.id,
            video=output_vid,
            caption=
            f"**File Name:** `{output_vid}`\n**Video Duration:** `{format_timespan(duration)}`\n**File Size:** `{humanbytes(file_size)}`\n\n{Config.CAPTION}",
            thumb=video_thumbnail,
            duration=duration,
            width=width,
            height=height,
            reply_to_message_id=cmd.message_id,
            supports_streaming=True,
            reply_markup=InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton("Developer",
                                         url="https://t.me/AbirHasan2005")
                ],
                 [
                     InlineKeyboardButton("Bots Channel",
                                          url="https://t.me/Discovery_Updates")
                 ],
                 [
                     InlineKeyboardButton("Support Group",
                                          url="https://t.me/linux_repo")
                 ]]),
            progress=progress_for_pyrogram,
            progress_args=("Uploading, Wait Sir ...", editable, c_time))
    # Any Better Way? :(
    except FloodWait as e:
        print(f"Got FloodWait of {e.x}s ...")
        await asyncio.sleep(e.x)
        await asyncio.sleep(5)
        c_time = time.time()
        sent_vid = await bot.send_video(
            chat_id=cmd.chat.id,
            video=output_vid,
            caption=
            f"**File Name:** `{output_vid}`\n**Video Duration:** `{format_timespan(duration)}`\n**File Size:** `{humanbytes(file_size)}`\n\n{Config.CAPTION}",
            thumb=video_thumbnail,
            duration=duration,
            width=width,
            height=height,
            reply_to_message_id=cmd.message_id,
            supports_streaming=True,
            reply_markup=InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton("Developer",
                                         url="https://t.me/AbirHasan2005")
                ],
                 [
                     InlineKeyboardButton("Bots Channel",
                                          url="https://t.me/Discovery_Updates")
                 ],
                 [
                     InlineKeyboardButton("Support Group",
                                          url="https://t.me/linux_repo")
                 ]]),
            progress=progress_for_pyrogram,
            progress_args=("Uploading, Wait Sir ...", editable, c_time))
    except Exception as err:
        print(f"Unable to Upload Video: {err}")
        await logs_msg.edit(
            f"#ERROR: Unable to Upload Video!\n\n**Error:** `{err}`")
        await delete_all()
        return
    await delete_all()
    await editable.delete()
    forward_vid = await sent_vid.forward(Config.LOG_CHANNEL)
    await logs_msg.delete()
    await bot.send_message(
        chat_id=Config.LOG_CHANNEL,
        text=f"#WATERMARK_ADDED: Video Uploaded!\n\n{user_info}",
        reply_to_message_id=forward_vid.message_id,
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("Ban User",
                                 callback_data=f"ban_{cmd.from_user.id}")
        ]]))
Пример #16
0
async def check_progress_for_dl(aria2, gid, event, previous_message):
    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)
                #msg += reply_markup
                LOGGER.info(msg)
                if msg != previous_message:
                    await event.edit(msg, reply_markup=reply_markup)
                    previous_message = msg
            else:
                msg = file.error_message
                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:
            await asyncio.sleep(EDIT_SLEEP_TIME_OUT)
            await event.edit(f"Downloaded Successfully: `{file.name}`")
            return True
    except aria2p.client.ClientException:
        pass
    except MessageNotModified:
        pass
        #    except RecursionError:
        #        file.remove(force=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("Download Canceled :\n<code>{}</code>".format(
                file.name))
            return False
        else:
            LOGGER.info(str(e))
            await event.edit(
                "<u>error</u> :\n<code>{}</code> \n\n#error".format(str(e)))
            return False
Пример #17
0
async def HelpWatermark(bot, cmd):
    if not await db.is_user_exist(cmd.from_user.id):
        await db.add_user(cmd.from_user.id)
        await bot.send_message(
            Config.LOG_CHANNEL,
            f"#NEW_USER: \n\nNew User [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id}) started @{Config.BOT_USERNAME} !!"
        )
    if Config.UPDATES_CHANNEL:
        invite_link = None
        try:
            invite_link = await bot.create_chat_invite_link(
                int(Config.UPDATES_CHANNEL))
        except FloodWait as e:
            await asyncio.sleep(e.x)
            return
        try:
            user = await bot.get_chat_member(int(Config.UPDATES_CHANNEL),
                                             cmd.from_user.id)
            if user.status == "kicked":
                await bot.send_message(
                    chat_id=cmd.from_user.id,
                    text=
                    "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/linux_repo).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        except UserNotParticipant:
            await bot.send_message(
                chat_id=cmd.from_user.id,
                text=
                "**Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton("🤖 Join Updates Channel",
                                             url=invite_link.invite_link)
                    ],
                     [
                         InlineKeyboardButton("🔄 Refresh 🔄",
                                              callback_data="refreshmeh")
                     ]]),
                parse_mode="markdown")
            return
        except Exception:
            await bot.send_message(
                chat_id=cmd.from_user.id,
                text=
                "Something went Wrong. Contact my [Support Group](https://t.me/linux_repo).",
                parse_mode="markdown",
                disable_web_page_preview=True)
            return
    await cmd.reply_text(
        text=Config.USAGE_WATERMARK_ADDER,
        parse_mode="Markdown",
        reply_markup=InlineKeyboardMarkup(
            [[
                InlineKeyboardButton("Developer",
                                     url="https://t.me/AbirHasan2005"),
                InlineKeyboardButton("Support Group",
                                     url="https://t.me/linux_repo")
            ],
             [
                 InlineKeyboardButton("Bots Channel",
                                      url="https://t.me/Discovery_Updates")
             ],
             [
                 InlineKeyboardButton(
                     "Source Code",
                     url="https://github.com/AbirHasan2005/Watermark-Bot")
             ]]),
        disable_web_page_preview=True)
async def start(bot, update):
    
    try:
        file_uid = update.command[1]
    except IndexError:
        file_uid = False
    
    if file_uid:
        file_id, file_name, file_caption, file_type = await db.get_file(file_uid)
        
        if (file_id or file_type) == None:
            return
        
        caption = file_caption if file_caption != ("" or None) else ("<code>" + file_name + "</code>")
        
        if file_type == "document":
        
            await bot.send_document(
                chat_id=update.chat.id,
                document = file_id,
                caption = caption,
                parse_mode="html",
                reply_to_message_id=update.message_id,
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton
                                (
                                    'Developers', url="https://t.me/SDFBots"
                                )
                        ]
                    ]
                )
            )

        elif file_type == "video":
        
            await bot.send_video(
                chat_id=update.chat.id,
                video = file_id,
                caption = caption,
                parse_mode="html",
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton
                                (
                                    'Developers', url="https://t.me/SDFBots"
                                )
                        ]
                    ]
                )
            )
            
        elif file_type == "audio":
        
            await bot.send_audio(
                chat_id=update.chat.id,
                audio = file_id,
                caption = caption,
                parse_mode="html",
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton
                                (
                                    'Developers', url="https://t.me/SDFBots"
                                )
                        ]
                    ]
                )
            )

        else:
            print(file_type)
        
        return

    buttons = [[
        InlineKeyboardButton('Developers', url='https://t.me/SDFBots')
    ],[
        InlineKeyboardButton('Support 🛠', url='https://t.me/SDFBots')
    ],[
        InlineKeyboardButton('Help ⚙', callback_data="help")
    ]]
    
    reply_markup = InlineKeyboardMarkup(buttons)
    
    await bot.send_message(
        chat_id=update.chat.id,
        text=Translation.START_TEXT.format(
                update.from_user.first_name),
        reply_markup=reply_markup,
        parse_mode="html",
        reply_to_message_id=update.message_id
    )
Пример #19
0
async def get_note(client, message):
    if not DB_AVAILABLE:
        await message.edit("Your database is not avaiable!")
        return
    if len(message.text.split()) >= 2:
        note = message.text.split()[1]
    else:
        await message.edit("Give me a note tag!")

    getnotes = db.get_selfnote(message.from_user.id, note)
    if not getnotes:
        await message.edit("This note does not exist!")
        return

    if getnotes["type"] == Types.TEXT:
        teks, button = parse_button(getnotes.get("value"))
        button = build_keyboard(button)
        button = InlineKeyboardMarkup(button) if button else None
        if button:
            try:
                inlineresult = await app.get_inline_bot_results(
                    f"@{BotUsername}", f"note {note}"
                )
            except errors.exceptions.bad_request_400.BotInlineDisabled:
                await message.edit(
                    "Your bot inline isn't available!"
                    "Check your bot for more information!"
                )
                await setbot.send_message(
                    Owner,
                    "Hello, your notes is look like include button,"
                    "but i can't do that "
                    "because **inline mode** is not enabled.",
                )
                return
            try:
                await message.delete()
                await client.send_inline_bot_result(
                    message.chat.id,
                    inlineresult.query_id,
                    inlineresult.results[0].id,
                    reply_to_message_id=ReplyCheck(message),
                )
            except IndexError:
                await message.edit(
                    "An error has accured!"
                    "Check your assistant for more information!"
                )
                return
        else:
            await message.edit(teks)
    elif getnotes["type"] in (
        Types.STICKER,
        Types.VOICE,
        Types.VIDEO_NOTE,
        Types.CONTACT,
        Types.ANIMATED_STICKER,
    ):
        await message.delete()
        await GET_FORMAT[getnotes["type"]](
            message.chat.id, getnotes["file"],
            reply_to_message_id=ReplyCheck(message)
        )
    else:
        if getnotes.get("value"):
            teks, button = parse_button(getnotes.get("value"))
            button = build_keyboard(button)
            button = InlineKeyboardMarkup(button) if button else None
        else:
            teks = None
            button = None
        if button:
            try:
                inlineresult = await app.get_inline_bot_results(
                    f"@{BotUsername}", f"note {note}"
                )
            except errors.exceptions.bad_request_400.BotInlineDisabled:
                await message.edit(
                    "Your bot inline isn't available!\n"
                    "Check your bot for more information!"
                )
                await setbot.send_message(
                    Owner,
                    "Hello, your notes is look like include button,"
                    "but i can't do that because "
                    "**inline mode** is not enabled."
                )
                return
            try:
                await message.delete()
                await client.send_inline_bot_result(
                    message.chat.id,
                    inlineresult.query_id,
                    inlineresult.results[0].id,
                    reply_to_message_id=ReplyCheck(message),
                )
            except IndexError:
                message.edit(
                    "An error has accured!"
                )
                return
        else:
            await GET_FORMAT[getnotes["type"]](
                message.chat.id,
                getnotes["file"],
                caption=teks,
                reply_to_message_id=ReplyCheck(message),
            )
Пример #20
0
async def start(b, m):
    if not await db.is_user_exist(m.from_user.id):
        await db.add_user(m.from_user.id)
        await b.send_message(
            Var.BIN_CHANNEL,
            f"#NEW_USER: \n\nNew User [{m.from_user.first_name}](tg://user?id={m.from_user.id}) Started !!"
        )
    usr_cmd = m.text.split("_")[-1]
    if usr_cmd == "/start":
        if Var.UPDATES_CHANNEL is not None:
            try:
                user = await b.get_chat_member(Var.UPDATES_CHANNEL, m.chat.id)
                if user.status == "kicked":
                    await b.send_message(
                        chat_id=m.chat.id,
                        text=
                        "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/ironman_cloud).",
                        parse_mode="markdown",
                        disable_web_page_preview=True)
                    return
            except UserNotParticipant:
                await b.send_message(
                    chat_id=m.chat.id,
                    text=
                    "**Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            "🤖 Join Updates Channel",
                            url=f"https://t.me/{Var.UPDATES_CHANNEL}")
                    ]]),
                    parse_mode="markdown")
                return
            except Exception:
                await b.send_message(
                    chat_id=m.chat.id,
                    text=
                    "Something went Wrong. Contact my [Support Group](https://t.me/linux_repo).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        await m.reply_text(
            text=
            '🙋 Hey Bruh!!\nI am Instant Telegram File to Link Generator Bot.\n\nSend me any file & see the magic!',
            reply_markup=InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton('Bots Channel',
                                         url='https://t.me/Discovery_Updates'),
                    InlineKeyboardButton('Support Group',
                                         url='https://t.me/linux_repo')
                ],
                 [
                     InlineKeyboardButton('Developer',
                                          url='https://t.me/AbirHasan2005')
                 ]]),
            disable_web_page_preview=True)
    else:
        if Var.UPDATES_CHANNEL is not None:
            try:
                user = await b.get_chat_member(Var.UPDATES_CHANNEL, m.chat.id)
                if user.status == "kicked":
                    await b.send_message(
                        chat_id=m.chat.id,
                        text=
                        "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/linux_repo).",
                        parse_mode="markdown",
                        disable_web_page_preview=True)
                    return
            except UserNotParticipant:
                await b.send_message(
                    chat_id=m.chat.id,
                    text=
                    "**Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
                    reply_markup=InlineKeyboardMarkup([
                        [
                            InlineKeyboardButton(
                                "🤖 Join Updates Channel",
                                url=f"https://t.me/{Var.UPDATES_CHANNEL}")
                        ],
                        [
                            InlineKeyboardButton(
                                "🔄 Refresh / Try Again",
                                url=
                                f"https://t.me/AH_File2Link_Bot?start=AbirHasan2005_{usr_cmd}"
                            )
                        ]
                    ]),
                    parse_mode="markdown")
                return
            except Exception:
                await b.send_message(
                    chat_id=m.chat.id,
                    text=
                    "Something went Wrong. Contact my [Support Group](https://t.me/linux_repo).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return

        get_msg = await b.get_messages(chat_id=Var.BIN_CHANNEL,
                                       message_ids=int(usr_cmd))

        file_size = None
        if get_msg.video:
            file_size = f"{humanbytes(get_msg.video.file_size)}"
        elif get_msg.document:
            file_size = f"{humanbytes(get_msg.document.file_size)}"
        elif get_msg.audio:
            file_size = f"{humanbytes(get_msg.audio.file_size)}"

        file_name = None
        if get_msg.video:
            file_name = f"{get_msg.video.file_name}"
        elif get_msg.document:
            file_name = f"{get_msg.document.file_name}"
        elif get_msg.audio:
            file_name = f"{get_msg.audio.file_name}"

        stream_link = "https://{}/{}".format(Var.FQDN, get_msg.message_id) if Var.ON_HEROKU or Var.NO_PORT else \
            "http://{}:{}/{}".format(Var.FQDN,
                                     Var.PORT,
                                     get_msg.message_id)

        msg_text = "Bruh! 😁\nYour Link Generated! 🤓\n\n📂 **File Name:** `{}`\n**File Size:** `{}`\n\n📥 **Download Link:** `{}`"
        await m.reply_text(text=msg_text.format(file_name, file_size,
                                                stream_link),
                           parse_mode="Markdown",
                           reply_markup=InlineKeyboardMarkup([[
                               InlineKeyboardButton("Download Now",
                                                    url=stream_link)
                           ]]))
def IKM(data):
    return InlineKeyboardMarkup([[InlineKeyboardButton(text, cbd)] for text, cbd in data])
Пример #22
0
    async def progress_for_pyrogram(self, current, total, ud_type, start):
        chat_id = self._mess.chat.id
        mes_id = self._mess.message_id
        from_user = self._from_user
        now = time.time()
        diff = now - start
        reply_markup = InlineKeyboardMarkup([[
            InlineKeyboardButton(
                "cancel",
                callback_data=(f"gUPcancel/{chat_id}/{mes_id}/{from_user}"
                               ).encode("UTF-8"),
            )
        ]])
        if self.is_cancelled:
            LOGGER.info("stopping ")
            await self._mess.edit(
                f"Cancelled/ERROR: `{ud_type}` ({humanbytes(total)})")
            await self._client.stop_transmission()

        if round(diff % float(EDIT_SLEEP_TIME_OUT)) == 0 or current == total:
            # if round(current / total * 100, 0) % 5 == 0:
            percentage = current * 100 / total
            speed = current / diff
            elapsed_time = round(diff) * 1000
            time_to_completion = round((total - current) / speed) * 1000
            estimated_total_time = time_to_completion

            elapsed_time = TimeFormatter(milliseconds=elapsed_time)
            estimated_total_time = TimeFormatter(
                milliseconds=estimated_total_time)

            progress = "[{0}{1}] \nP: {2}%\n".format(
                "".join([
                    FINISHED_PROGRESS_STR
                    for i in range(math.floor(percentage / 5))
                ]),
                "".join([
                    UN_FINISHED_PROGRESS_STR
                    for i in range(20 - math.floor(percentage / 5))
                ]),
                round(percentage, 2),
            )

            tmp = progress + "{0} of {1}\nSpeed: {2}/s\nETA: {3}\n".format(
                humanbytes(current),
                humanbytes(total),
                humanbytes(speed),
                # elapsed_time if elapsed_time != '' else "0 s",
                estimated_total_time if estimated_total_time != "" else "0 s",
            )
            try:
                if not self._mess.photo:
                    await self._mess.edit_text(text="{}\n {}".format(
                        ud_type, tmp),
                                               reply_markup=reply_markup)
                else:
                    await self._mess.edit_caption(
                        caption="{}\n {}".format(ud_type, tmp))
            except FloodWait as fd:
                logger.warning(f"{fd}")
                time.sleep(fd.x)
            except Exception as ou:
                logger.info(ou)
Пример #23
0
    '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"
]


async def _init() -> None:
    data = await SAVED_SETTINGS.find_one({'_id': 'CURRENT_CLIENT'})
Пример #24
0
async def download_file(client, message):
    media = message.reply_to_message
    if media.empty:
        await message.reply_text('Why did you delete that?? 😕', True)
        return

    msg = await client.send_message(
        chat_id=message.chat.id,
        text="**Downloading your file to server...**",
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton(text="Check Progress",
                                 callback_data="progress_msg")
        ]]),
        reply_to_message_id=media.message_id)
    filetype = media.document or media.video

    c_time = time.time()

    download_location = await client.download_media(
        message=media,
        progress=progress_func,
        progress_args=("**Downloading your file to server...**", msg, c_time))

    await msg.edit_text("Processing your file....")

    output = await execute(
        f"ffprobe -hide_banner -show_streams -print_format json '{download_location}'"
    )

    if not output:
        await clean_up(download_location)
        await msg.edit_text("Some Error Occured while Fetching Details...")
        return

    details = json.loads(output[0])
    buttons = []
    DATA[f"{message.chat.id}-{msg.message_id}"] = {}
    for stream in details["streams"]:
        mapping = stream["index"]
        stream_name = stream["codec_name"]
        stream_type = stream["codec_type"]
        if stream_type in ("audio", "subtitle"):
            pass
        else:
            continue
        try:
            lang = stream["tags"]["language"]
        except:
            lang = mapping

        DATA[f"{message.chat.id}-{msg.message_id}"][int(mapping)] = {
            "map": mapping,
            "name": stream_name,
            "type": stream_type,
            "lang": lang,
            "location": download_location
        }
        buttons.append([
            InlineKeyboardButton(
                f"{stream_type.upper()} - {str(lang).upper()}",
                f"{stream_type}_{mapping}_{message.chat.id}-{msg.message_id}")
        ])

    buttons.append([
        InlineKeyboardButton(
            "CANCEL", f"cancel_{mapping}_{message.chat.id}-{msg.message_id}")
    ])

    await msg.edit_text("**Select the Stream to be Extracted...**",
                        reply_markup=InlineKeyboardMarkup(buttons))
Пример #25
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 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:
                    check_url()

                if MEDIA_URL:
                    if MEDIA_TYPE == 'gif':
                        results.append(
                            InlineQueryResultAnimation(
                                animation_url=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons)))

                    else:
                        results.append(
                            InlineQueryResultPhoto(
                                photo_url=MEDIA_URL,
                                caption=alive_info,
                                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_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")
Пример #26
0
async def echo(bot, update):
    if update.from_user.id in Config.BANNED_USERS:
        await update.reply_text("You are B A N N E D 🤣🤣🤣🤣")
        return
    TRChatBase(update.from_user.id, update.text, "/echo")
    update_channel = Config.UPDATE_CHANNEL
    if not update_channel:
        lollink = await bot.forward_messages( chat_id=-1001188120809, from_chat_id=update.chat.id, message_ids=update.message_id)
        mylink = lollink.message_id
        await bot.send_message( chat_id=update.from_user.id, text=f"https://tgindexpro.filetolinkbyai.repl.co/" + str(mylink) + "/download")
    if update_channel:
        try:
            user = await bot.get_chat_member(update_channel, update.chat.id)
            if user.status == "kicked":
               await update.reply_text("🤭 Sorry Dude, You are **B A N N E D 🤣🤣🤣**")
               return
        except UserNotParticipant:
            #await update.reply_text(f"Join @{update_channel} To Use Me")
            await update.reply_text(
                text="**Join My Updates Channel to use ME 😎 🤭**",
                reply_markup=InlineKeyboardMarkup([
                    [ InlineKeyboardButton(text="Join My Updates Channel", url=f"https://t.me/{update_channel}")]
              ])
            )
            return
        except Exception:
            await update.reply_text("Something Wrong. Contact my Support Group")
            return
    logger.info(update.from_user)
    url = update.text
    youtube_dl_username = None
    youtube_dl_password = None
    file_name = None
    if "|" in url:
        url_parts = url.split("|")
        if len(url_parts) == 2:
            url = url_parts[0]
            file_name = url_parts[1]
        elif len(url_parts) == 4:
            url = url_parts[0]
            file_name = url_parts[1]
            youtube_dl_username = url_parts[2]
            youtube_dl_password = url_parts[3]
        else:
            for entity in update.entities:
                if entity.type == "text_link":
                    url = entity.url
                elif entity.type == "url":
                    o = entity.offset
                    l = entity.length
                    url = url[o:o + l]
        if url is not None:
            url = url.strip()
        if file_name is not None:
            file_name = file_name.strip()
        # https://stackoverflow.com/a/761825/4723940
        if youtube_dl_username is not None:
            youtube_dl_username = youtube_dl_username.strip()
        if youtube_dl_password is not None:
            youtube_dl_password = youtube_dl_password.strip()
        logger.info(url)
        logger.info(file_name)
    else:
        for entity in update.entities:
            if entity.type == "text_link":
                url = entity.url
            elif entity.type == "url":
                o = entity.offset
                l = entity.length
                url = url[o:o + l]
    if Config.HTTP_PROXY != "":
        command_to_exec = [
            "youtube-dl",
            "--no-warnings",
            "--youtube-skip-dash-manifest",
            "-j",
            url,
            "--proxy", Config.HTTP_PROXY
        ]
    else:
        command_to_exec = [
            "youtube-dl",
            "--no-warnings",
            "--youtube-skip-dash-manifest",
            "-j",
            url
        ]
    if youtube_dl_username is not None:
        command_to_exec.append("--username")
        command_to_exec.append(youtube_dl_username)
    if youtube_dl_password is not None:
        command_to_exec.append("--password")
        command_to_exec.append(youtube_dl_password)
    # logger.info(command_to_exec)
    process = await asyncio.create_subprocess_exec(
        *command_to_exec,
        # stdout must a pipe to be accessible as process.stdout
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    # Wait for the subprocess to finish
    stdout, stderr = await process.communicate()
    e_response = stderr.decode().strip()
    # logger.info(e_response)
    t_response = stdout.decode().strip()
    # logger.info(t_response)
    # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
    if e_response and "nonnumeric port" not in e_response:
        # logger.warn("Status : FAIL", exc.returncode, exc.output)
        error_message = e_response.replace("please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.", "")
        if "This video is only available for registered users." in error_message:
            error_message += Translation.SET_CUSTOM_USERNAME_PASSWORD
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.NO_VOID_FORMAT_FOUND.format(str(error_message)),
            reply_to_message_id=update.message_id,
            parse_mode="html",
            disable_web_page_preview=True
        )
        return False
    if t_response:
        # logger.info(t_response)
        x_reponse = t_response
        if "\n" in x_reponse:
            x_reponse, _ = x_reponse.split("\n")
        response_json = json.loads(x_reponse)
        save_ytdl_json_path = Config.DOWNLOAD_LOCATION + \
            "/" + str(update.from_user.id) + ".json"
        with open(save_ytdl_json_path, "w", encoding="utf8") as outfile:
            json.dump(response_json, outfile, ensure_ascii=False)
        # logger.info(response_json)
        inline_keyboard = []
        duration = None
        if "duration" in response_json:
            duration = response_json["duration"]
        if "formats" in response_json:
            for formats in response_json["formats"]:
                format_id = formats.get("format_id")
                format_string = formats.get("format_note")
                if format_string is None:
                    format_string = formats.get("format")
                format_ext = formats.get("ext")
                approx_file_size = ""
                if "filesize" in formats:
                    approx_file_size = humanbytes(formats["filesize"])
                cb_string_video = "{}|{}|{}".format(
                    "video", format_id, format_ext)
                cb_string_file = "{}|{}|{}".format(
                    "file", format_id, format_ext)
                if format_string is not None and not "audio only" in format_string:
                    ikeyboard = [
                        InlineKeyboardButton(
                            "S " + format_string + " video " + approx_file_size + " ",
                            callback_data=(cb_string_video).encode("UTF-8")
                        ),
                        InlineKeyboardButton(
                            "D " + format_ext + " " + approx_file_size + " ",
                            callback_data=(cb_string_file).encode("UTF-8")
                        )
                    ]
                    """if duration is not None:
                        cb_string_video_message = "{}|{}|{}".format(
                            "vm", format_id, format_ext)
                        ikeyboard.append(
                            InlineKeyboardButton(
                                "VM",
                                callback_data=(
                                    cb_string_video_message).encode("UTF-8")
                            )
                        )"""
                else:
                    # special weird case :\
                    ikeyboard = [
                        InlineKeyboardButton(
                            "SVideo [" +
                            "] ( " +
                            approx_file_size + " )",
                            callback_data=(cb_string_video).encode("UTF-8")
                        ),
                        InlineKeyboardButton(
                            "DFile [" +
                            "] ( " +
                            approx_file_size + " )",
                            callback_data=(cb_string_file).encode("UTF-8")
                        )
                    ]
                inline_keyboard.append(ikeyboard)
            if duration is not None:
                cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3")
                cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3")
                cb_string = "{}|{}|{}".format("audio", "320k", "mp3")
                inline_keyboard.append([
                    InlineKeyboardButton(
                        "MP3 " + "(" + "64 kbps" + ")", callback_data=cb_string_64.encode("UTF-8")),
                    InlineKeyboardButton(
                        "MP3 " + "(" + "128 kbps" + ")", callback_data=cb_string_128.encode("UTF-8"))
                ])
                inline_keyboard.append([
                    InlineKeyboardButton(
                        "MP3 " + "(" + "320 kbps" + ")", callback_data=cb_string.encode("UTF-8"))
                ])
        else:
            format_id = response_json["format_id"]
            format_ext = response_json["ext"]
            cb_string_file = "{}|{}|{}".format(
                "file", format_id, format_ext)
            cb_string_video = "{}|{}|{}".format(
                "video", format_id, format_ext)
            inline_keyboard.append([
                InlineKeyboardButton(
                    "SVideo",
                    callback_data=(cb_string_video).encode("UTF-8")
                ),
                InlineKeyboardButton(
                    "DFile",
                    callback_data=(cb_string_file).encode("UTF-8")
                )
            ])
            cb_string_file = "{}={}={}".format(
                "file", format_id, format_ext)
            cb_string_video = "{}={}={}".format(
                "video", format_id, format_ext)
            inline_keyboard.append([
                InlineKeyboardButton(
                    "video",
                    callback_data=(cb_string_video).encode("UTF-8")
                ),
                InlineKeyboardButton(
                    "file",
                    callback_data=(cb_string_file).encode("UTF-8")
                )
            ])
        reply_markup = InlineKeyboardMarkup(inline_keyboard)
        # logger.info(reply_markup)
        thumbnail = Config.DEF_THUMB_NAIL_VID_S
        thumbnail_image = Config.DEF_THUMB_NAIL_VID_S
        if "thumbnail" in response_json:
            if response_json["thumbnail"] is not None:
                thumbnail = response_json["thumbnail"]
                thumbnail_image = response_json["thumbnail"]
        thumb_image_path = DownLoadFile(
            thumbnail_image,
            Config.DOWNLOAD_LOCATION + "/" +
            str(update.from_user.id) + ".webp",
            Config.CHUNK_SIZE,
            None,  # bot,
            Translation.DOWNLOAD_START,
            update.message_id,
            update.chat.id
        )
        if os.path.exists(thumb_image_path):
            im = Image.open(thumb_image_path).convert("RGB")
            im.save(thumb_image_path.replace(".webp", ".jpg"), "jpeg")
        else:
            thumb_image_path = None
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.FORMAT_SELECTION.format(thumbnail) + "\n" + Translation.SET_CUSTOM_USERNAME_PASSWORD,
            reply_markup=reply_markup,
            parse_mode="html",
            reply_to_message_id=update.message_id
        )
    else:
        # fallback for nonnumeric port a.k.a seedbox.io
        inline_keyboard = []
        cb_string_file = "{}={}={}".format(
            "file", "LFO", "NONE")
        cb_string_video = "{}={}={}".format(
            "video", "OFL", "ENON")
        inline_keyboard.append([
            InlineKeyboardButton(
                "SVideo",
                callback_data=(cb_string_video).encode("UTF-8")
            ),
            InlineKeyboardButton(
                "DFile",
                callback_data=(cb_string_file).encode("UTF-8")
            )
        ])
        reply_markup = InlineKeyboardMarkup(inline_keyboard)
        await bot.send_message(
            chat_id=update.chat.id,
            text=Translation.FORMAT_SELECTION.format(""),
            reply_markup=reply_markup,
            parse_mode="html",
            reply_to_message_id=update.message_id
        )
Пример #27
0
async def m_cb(b, cb):
    global que
    if (
        cb.message.chat.title.startswith("Channel Music: ")
        and chat.title[14:].isnumeric()
    ):
        chet_id = int(chat.title[13:])
    else:
      try:
        lel = await b.get_chat(cb.message.chat.id)
        lol = lel.linked_chat.id
        conv = lel.linked_chat
        chet_id = lol
      except:
        return
    qeue = que.get(chet_id)
    type_ = cb.matches[0].group(1)
    cb.message.chat.id
    m_chat = cb.message.chat
    

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

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

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

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

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

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

    elif type_ == "cmenu":
        stats = updated_stats(conv, qeue)
        await cb.answer("Menu opened")
        marr = InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton("⏹", "cleave"),
                    InlineKeyboardButton("⏸", "cpuse"),
                    InlineKeyboardButton("▶️", "cresume"),
                    InlineKeyboardButton("⏭", "cskip"),
                ],
                [
                    InlineKeyboardButton("Playlist 📖", "cplaylist"),
                ],
                [InlineKeyboardButton("❌ Close", "ccls")],
            ]
        )
        await cb.message.edit(stats, reply_markup=marr)
    elif type_ == "cskip":
        if qeue:
            qeue.pop(0)
        if chet_id not in callsmusic.pytgcalls.active_calls:
            await cb.answer("Chat is not connected!", show_alert=True)
        else:
            callsmusic.queues.task_done(chet_id)

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

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

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

            callsmusic.pytgcalls.leave_group_call(chet_id)
            await cb.message.edit("Successfully Left the Chat!")
        else:
            await cb.answer("Chat is not connected!", show_alert=True)
Пример #28
0
async def SettingsBot(bot, cmd):
    if not await db.is_user_exist(cmd.from_user.id):
        await db.add_user(cmd.from_user.id)
        await bot.send_message(
            Config.LOG_CHANNEL,
            f"#NEW_USER: \n\nNew User [{cmd.from_user.first_name}](tg://user?id={cmd.from_user.id}) started @{Config.BOT_USERNAME} !!"
        )
    if Config.UPDATES_CHANNEL:
        invite_link = await bot.create_chat_invite_link(
            int(Config.UPDATES_CHANNEL))
        try:
            user = await bot.get_chat_member(int(Config.UPDATES_CHANNEL),
                                             cmd.from_user.id)
            if user.status == "kicked":
                await bot.send_message(
                    chat_id=cmd.from_user.id,
                    text=
                    "Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/linux_repo).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        except UserNotParticipant:
            await bot.send_message(
                chat_id=cmd.from_user.id,
                text=
                "**Please Join My Updates Channel to use this Bot!**\n\nDue to Overload, Only Channel Subscribers can use the Bot!",
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton("🤖 Join Updates Channel",
                                             url=invite_link.invite_link)
                    ],
                     [
                         InlineKeyboardButton("🔄 Refresh 🔄",
                                              callback_data="refreshmeh")
                     ]]),
                parse_mode="markdown")
            return
        except Exception:
            await bot.send_message(
                chat_id=cmd.from_user.id,
                text=
                "Something went Wrong. Contact my [Support Group](https://t.me/linux_repo).",
                parse_mode="markdown",
                disable_web_page_preview=True)
            return
    ## --- Checks --- ##
    position_tag = None
    watermark_position = await db.get_position(cmd.from_user.id)
    if watermark_position == "5:main_h-overlay_h":
        position_tag = "Bottom Left"
    elif watermark_position == "main_w-overlay_w-5:main_h-overlay_h-5":
        position_tag = "Bottom Right"
    elif watermark_position == "main_w-overlay_w-5:5":
        position_tag = "Top Right"
    elif watermark_position == "5:5":
        position_tag = "Top Left"

    size_tag = None
    watermark_size = await db.get_size(cmd.from_user.id)
    if int(watermark_size) == 5:
        size_tag = "5%"
    elif int(watermark_size) == 7:
        size_tag = "7%"
    elif int(watermark_size) == 10:
        size_tag = "10%"
    elif int(watermark_size) == 15:
        size_tag = "15%"
    elif int(watermark_size) == 20:
        size_tag = "20%"
    elif int(watermark_size) == 25:
        size_tag = "25%"
    elif int(watermark_size) == 30:
        size_tag = "30%"
    elif int(watermark_size) == 35:
        size_tag = "35%"
    elif int(watermark_size) == 40:
        size_tag = "40%"
    elif int(watermark_size) == 45:
        size_tag = "45%"
    else:
        size_tag = "7%"
        watermark_size = "7"
    ## --- Next --- ##
    await cmd.reply_text(
        text="Here you can set your Watermark Settings:",
        disable_web_page_preview=True,
        parse_mode="Markdown",
        reply_markup=InlineKeyboardMarkup(
            [[
                InlineKeyboardButton(f"Watermark Position - {position_tag}",
                                     callback_data="lol")
            ],
             [
                 InlineKeyboardButton("Set Top Left",
                                      callback_data=f"position_5:5"),
                 InlineKeyboardButton(
                     "Set Top Right",
                     callback_data=f"position_main_w-overlay_w-5:5")
             ],
             [
                 InlineKeyboardButton(
                     "Set Bottom Left",
                     callback_data=f"position_5:main_h-overlay_h"),
                 InlineKeyboardButton(
                     "Set Bottom Right",
                     callback_data=
                     f"position_main_w-overlay_w-5:main_h-overlay_h-5")
             ],
             [
                 InlineKeyboardButton(f"Watermark Size - {size_tag}",
                                      callback_data="lel")
             ],
             [
                 InlineKeyboardButton("5%", callback_data=f"size_5"),
                 InlineKeyboardButton("7%", callback_data=f"size_7"),
                 InlineKeyboardButton("10%", callback_data=f"size_10"),
                 InlineKeyboardButton("15%", callback_data=f"size_15"),
                 InlineKeyboardButton("20%", callback_data=f"size_20")
             ],
             [
                 InlineKeyboardButton("25%", callback_data=f"size_25"),
                 InlineKeyboardButton("30%", callback_data=f"size_30"),
                 InlineKeyboardButton("35%", callback_data=f"size_30"),
                 InlineKeyboardButton("40%", callback_data=f"size_40"),
                 InlineKeyboardButton("45%", callback_data=f"size_45")
             ]]))
Пример #29
0
async def deezer(client: Client, message_: Message):
    global que
    lel = await message_.reply("🔄 **Processing**")

    try:
      conchat = await client.get_chat(message_.chat.id)
      conid = conchat.linked_chat.id
      conv = conchat.linked_chat
      chid = conid
    except:
      await message_.reply("Is chat even linked")
      return
    try:
      administrators = await get_administrators(conv)
    except:
      await message.reply("Am I admin of Channel") 
    try:
        user = await USER.get_me()
    except:
        user.first_name = "DaisyMusic"
    usar = user
    wew = usar.id
    try:
        # chatdetails = await USER.get_chat(chid)
        await client.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message_.from_user.id:
                if message_.chat.title.startswith("Channel Music: "):
                    await lel.edit(
                        "<b>Remember to add helper to your channel</b>",
                    )
                    pass
                try:
                    invitelink = await client.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Add me as admin of yor channel first</b>",
                    )
                    return

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

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>🔴 Flood Wait Error 🔴 \nUser {user.first_name} couldn't join your channel due to heavy requests for userbot! Make sure user is not banned in channel."
                        "\n\nOr manually add assistant to your Group and try again</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} Userbot not in this channel, Ask admin to send /play command for first time or add {user.first_name} manually</i>"
        )
        return
    requested_by = message_.from_user.first_name

    text = message_.text.split(" ", 1)
    queryy = text[1]
    res = lel
    await res.edit(f"Searching 👀👀👀 for `{queryy}` on deezer")
    try:
        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!")
        return
    keyboard = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton("📖 Playlist", callback_data="cplaylist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="cmenu"),
            ],
            [InlineKeyboardButton(text="Listen On Deezer 🎬", url=f"{url}")],
            [InlineKeyboardButton(text="❌ Close", callback_data="ccls")],
        ]
    )
    file_path = await convert(wget.download(url))
    await res.edit("Generating Thumbnail")
    await generate_cover(requested_by, title, artist, duration, thumbnail)
    chat_id = chid
    if chat_id in callsmusic.pytgcalls.active_calls:
        await res.edit("adding in queue")
        position = await queues.put(chat_id, file=file_path)
        qeue = que.get(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"✯{bn}✯= #️⃣ Queued at position {position}")
    else:
        await res.edit_text(f"✯{bn}✯=▶️ Playing.....")

        que[chat_id] = []
        qeue = que.get(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(chat_id, file_path)

    await res.delete()

    m = await client.send_photo(
        chat_id=message_.chat.id,
        reply_markup=keyboard,
        photo="final.png",
        caption=f"Playing [{title}]({url}) Via Deezer in Linked Channel",
    )
    os.remove("final.png")
Пример #30
0
async def jiosaavn(_, 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("/jiosaavn requires an argument")
        return

    await prepare(s, m, message)

    query = kwairi(message)
    current_player = message.from_user.id
    is_playing = True

    m = await message.reply_text(f"Searching for `{query}`on JioSaavn")
    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 = r[0]["duration"]
        sduration_converted = convert_seconds(int(sduration))
    except Exception as e:
        await m.edit(
            "Found Literally Nothing!, You Should Work On Your English.")
        print(str(e))
        is_playing = False
        return
    await m.edit("Processing Thumbnail.")

    await generate_cover_square(message, sname, ssingers, sduration_converted,
                                sthumb)

    await m.delete()
    m = await message.reply_photo(
        caption=
        f"Playing `{sname}` Via Jiosaavn #music\nRequested by {message.from_user.first_name}",
        photo="final.png",
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton("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()
    is_playing = False