Пример #1
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}")
        ]]))
Пример #2
0
async def ana_sayfa(client:Client, callback_query:CallbackQuery):
    await callback_query.edit_message_text(
        start_mesajı, reply_markup=InlineKeyboardMarkup(start_butonu)
    )
Пример #3
0
async def auto_filter(bot, update):
    """
    A Funtion To Handle Incoming Text And Reply With Appropriate Results
    """
    group_id = update.chat.id

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

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

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

    if len(query) < 2:
        return

    results = []

    global ACTIVE_CHATS
    global FIND

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

    if not configs:
        return

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

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

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

    filters = await db.get_filters(group_id, query)

    if filters:
        results.append([
            InlineKeyboardButton("💢 𝗝𝗼𝗶𝗻 𝗢𝘂𝗿 Update 𝗰𝗵𝗮𝗻𝗻𝗲𝗹 💢",
                                 url=f"https://t.me/tvseriezzz_update")
        ])
        for filter in filters:  # iterating through each files
            file_name = filter.get("file_name")
            file_type = filter.get("file_type")
            file_link = filter.get("file_link")
            file_size = int(filter.get("file_size", "0"))

            # from B to MB

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

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

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

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

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

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

            if len(results) >= max_results:
                break

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

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

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

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

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

    else:

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

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

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

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

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

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

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

            ACTIVE_CHATS[str(group_id)] = achatId

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

                chat_id = int(y["chat_id"])

                if chat_id not in achatId:
                    continue

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

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

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

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

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

        reply_markup = InlineKeyboardMarkup(result[0])

        try:
            await bot.send_photo(
                chat_id=update.chat.id,
                photo=MASSAGE_PHOTO,
                caption=
                f"<b>🗂️ Total Files Found :- {(len_results)}</b>\n<b>🎬 Requested Query :-</b> <code>{query}</code>",
                reply_markup=reply_markup,
                parse_mode="html",
                reply_to_message_id=update.message_id)

        except ButtonDataInvalid:
            print(result[0])

        except Exception as e:
            print(e)
Пример #4
0
def allGP(client, message,redis):
  type = message.chat.type
  userID = message.from_user.id
  chatID = message.chat.id
  username = message.from_user.username
  if username is None:
    username = "******"
  userFN = message.from_user.first_name
  title = message.chat.title
  rank = isrank(redis,userID,chatID)
  text = message.text
  c = importlib.import_module("lang.arcmd")
  r = importlib.import_module("lang.arreply")
  redis.hincrby("{}Nbot:{}:msgs".format(BOT_ID,chatID),userID)
  if text :
    if text == "منو ضافني":
      get = redis.hget("{}Nbot:MowAddMe:{}".format(BOT_ID,chatID),userID)
      if get:
        Bot("sendMessage",{"chat_id":chatID,"text":f"تم اضافتك بواسطة ⏺: {get}","reply_to_message_id":message.message_id})
    if re.search(c.setGPadmin,text):
      if re.search("@",text):
        user = text.split("@")[1]
      if re.search(c.setGPadmin2,text):
        user = int(re.search(r'\d+', text).group())
      if message.reply_to_message:
        user = message.reply_to_message.from_user.id
      if 'user' not in locals():return False
      if GPranks(userID,chatID) == "member":return False
      Getus = Bot("getChatMember",{"chat_id":chatID,"user_id":userID})["result"]
      if Getus["status"] == "administrator" and not Getus["can_promote_members"]:return False
      try:
        getUser = client.get_users(user)
        userId = getUser.id
        userFn = getUser.first_name
        if GPranks(userId,chatID) != "member":return False
        pr = Bot("promoteChatMember",{"chat_id":chatID,"user_id":userId,"can_change_info":1,"can_delete_messages":1,"can_invite_users":1,"can_restrict_members":1,"can_pin_messages":1})
        if pr["ok"]:
          T ="<a href=\"tg://user?id={}\">{}</a>".format(userId,Name(userFn))
          Bot("sendMessage",{"chat_id":chatID,"text":r.prGPadmin.format(T),"reply_to_message_id":message.message_id,"parse_mode":"html"})
      except Exception as e:
        Bot("sendMessage",{"chat_id":chatID,"text":r.userNocc,"reply_to_message_id":message.message_id,"parse_mode":"html"})

    if re.search(c.sors,text):
      kb = InlineKeyboardMarkup([[InlineKeyboardButton("قناه السورس 📢", url="t.me/zx_xx")],[InlineKeyboardButton("تواصل السورس 💬", url="t.me/A_5bot")],[InlineKeyboardButton("شروحات السورس 📑", url="t.me/tshaketeam")]])
      Botuser = client.get_me().username
      Bot("sendMessage",{"chat_id":chatID,"text":r.sors.format("@"+Botuser),"disable_web_page_preview":True,"reply_to_message_id":message.message_id,"parse_mode":"markdown","reply_markup":kb})
    
    if re.search(c.dellink,text):
      kb = InlineKeyboardMarkup([[InlineKeyboardButton(c.dellink2, url="https://telegram.org/deactivate")]])
      Botuser = client.get_me().username
      Bot("sendMessage",{"chat_id":chatID,"text":r.dellink,"disable_web_page_preview":True,"reply_to_message_id":message.message_id,"parse_mode":"markdown","reply_markup":kb})

    if re.search(c.ShowO,text) and (rank is not False or rank is not  0 or rank != "vip"):
      reply_markup = getOR(rank,r,userID)
      Bot("sendMessage",{"chat_id":chatID,"text":r.Showall,"reply_to_message_id":message.message_id,"parse_mode":"html","disable_web_page_preview":True,"reply_markup":reply_markup})

    if text == "عدد الكروب" and (rank is not False or rank is not  0 ):
      from pyrogram.raw.functions.channels import GetFullChannel
      chat = client.resolve_peer(chatID)
      full_chat = client.send(GetFullChannel(channel=chat)).full_chat
      Bot("sendMessage",{"chat_id":chatID,"text":r.gpinfo.format(message.chat.title,full_chat.participants_count,full_chat.admins_count,full_chat.kicked_count,full_chat.banned_count,message.message_id),"reply_to_message_id":message.message_id,"parse_mode":"html","disable_web_page_preview":True})
    if text == c.ID and not redis.sismember("{}Nbot:IDSend".format(BOT_ID),chatID) and not message.reply_to_message:
      Ch = True
      t = IDrank(redis,userID,chatID,r)
      msgs = (redis.hget("{}Nbot:{}:msgs".format(BOT_ID,chatID),userID) or 0)
      edits = (redis.hget("{}Nbot:{}:edits".format(BOT_ID,chatID),userID) or 0)
      rate = int(msgs)*100/20000
      age = getAge(userID,r)
      if redis.hget("{}Nbot:SHOWid".format(BOT_ID),chatID):
        tx = redis.hget("{}Nbot:SHOWid".format(BOT_ID),chatID)
        rep = {"#age":"{age}","#name":"{name}","#id":"{id}","#username":"******","#msgs":"{msgs}","#stast":"{stast}","#edits":"{edits}","#rate":"{rate}","{us}":"{username}","#us":"{username}"}
        for v in rep.keys():
          tx = tx.replace(v,rep[v])
      else:
        tx = r.IDnPT
      if not redis.sismember("{}Nbot:IDSendPH".format(BOT_ID),chatID):
        get = Bot("getUserProfilePhotos",{"user_id":userID,"offset":0,"limit":1})
        if get["ok"] == False: 
          Ch = True
        elif get["result"]["total_count"] == 0:
          Ch = True
        else:
          Ch = False
          file_id = get["result"]["photos"][0][0]["file_id"]
          Bot("sendPhoto",{"chat_id":chatID,"photo":file_id,"caption":tx.format(username=("@"+username or "None"),id=userID,stast=t,msgs=msgs,edits=edits,age=age,rate=str(rate)+"%"),"reply_to_message_id":message.message_id,"parse_mode":"html"})
      if Ch == True:
        Bot("sendMessage",{"chat_id":chatID,"text":tx.format(username=("@"+username or "None"),id=userID,stast=t,msgs=msgs,edits=edits,age=age,rate=str(rate)+"%"),"reply_to_message_id":message.message_id,"parse_mode":"html"})

    if text == "رتبتي":
      t = IDrank(redis,userID,chatID,r)
      Bot("sendMessage",{"chat_id":chatID,"text":f"⏏️꒐ موقعك : {t}","reply_to_message_id":message.message_id,"parse_mode":"html"})
    if text == c.ID and not redis.sismember("{}Nbot:IDSend".format(BOT_ID),chatID) and message.reply_to_message:
      us = message.reply_to_message.from_user.id
      rusername = message.reply_to_message.from_user.username
      if rusername is None:
        rusername = "******"
      t = IDrank(redis,us,chatID,r)
      msgs = (redis.hget("{}Nbot:{}:msgs".format(BOT_ID,chatID),us) or 0)
      edits = (redis.hget("{}Nbot:{}:edits".format(BOT_ID,chatID),us) or 0)
      rate = int(msgs)*100/20000
      age = getAge(us,r)
      tx = r.ReIDnPT
      if redis.hget("{}Nbot:SHOWid".format(BOT_ID),chatID):
        tx = redis.hget("{}Nbot:SHOWid".format(BOT_ID),chatID)
        rep = {"#age":"{age}","#name":"{name}","#id":"{id}","#username":"******","#msgs":"{msgs}","#stast":"{stast}","#edits":"{edits}","#rate":"{rate}","{us}":"{username}","#us":"{username}"}
        for v in rep.keys():
          tx = tx.replace(v,rep[v])
      else:
        tx = r.ReIDnPT
      Bot("sendMessage",{"chat_id":chatID,"text":tx.format(username=("@"+rusername or "None"),id=us,stast=t,msgs=msgs,edits=edits,age=age,rate=str(rate)+"%"),"reply_to_message_id":message.message_id,"parse_mode":"html"})
    if re.search(c.idus,text) and not redis.sismember("{}Nbot:IDSend".format(BOT_ID),chatID):
      user = text.split("@")[1]
      try:
        getUser = client.get_users(user)
        us = getUser.id
        rusername = user
        if rusername is None:
          rusername = "******"
        age = getAge(us,r)
        t = IDrank(redis,us,chatID,r)
        msgs = (redis.hget("{}Nbot:{}:msgs".format(BOT_ID,chatID),us) or 0)
        edits = (redis.hget("{}Nbot:{}:edits".format(BOT_ID,chatID),us) or 0)
        rate = int(msgs)*100/20000
        tx = r.ReIDnPT
        Bot("sendMessage",{"chat_id":chatID,"text":tx.format(username=("@"+rusername or "None"),id=us,stast=t,msgs=msgs,edits=edits,age=age,rate=str(rate)+"%"),"reply_to_message_id":message.message_id,"parse_mode":"html"})
      except Exception as e:
        print(e)

    if re.search(c.ShowSudos, text):
      tx = (redis.get("{}Nbot:SHOWsudos".format(BOT_ID)) or "")
      Bot("sendMessage",{"chat_id":chatID,"text":tx,"reply_to_message_id":message.message_id,"parse_mode":"html"})
    if text == c.mymsgs:
      get = redis.hget("{}Nbot:{}:msgs".format(BOT_ID,chatID),userID)
      Bot("sendMessage",{"chat_id":chatID,"text":r.yourmsgs.format((get or 0)),"reply_to_message_id":message.message_id,"parse_mode":"html"})
    if text == c.link and not redis.sismember("{}Nbot:showlink".format(BOT_ID),chatID):
      get = (redis.hget("{}Nbot:links".format(BOT_ID),chatID) or GetLink(chatID) or "none")
      Bot("sendMessage",{"chat_id":chatID,"text":r.showGPlk.format(get),"reply_to_message_id":message.message_id,"parse_mode":"html","disable_web_page_preview":True})

    if text == c.myedits:
      get = redis.hget("{}Nbot:{}:edits".format(BOT_ID,chatID),userID)
      Bot("sendMessage",{"chat_id":chatID,"text":r.youredits.format((get or 0)),"reply_to_message_id":message.message_id,"parse_mode":"html"})

    if text == c.myaddcontact:
      get = redis.hget("{}Nbot:{}:addcontact".format(BOT_ID,chatID),userID)
      Bot("sendMessage",{"chat_id":chatID,"text":r.youraddcontact.format((get or 0)),"reply_to_message_id":message.message_id,"parse_mode":"html"})
    
    
    if not redis.sismember("{}Nbot:ReplySendBOT".format(BOT_ID),chatID):
      if redis.hexists("{}Nbot:TXreplys".format(BOT_ID),text):
        tx = redis.hget("{}Nbot:TXreplys".format(BOT_ID),text)
        try:
          rep = {"#cn":"{cn}","#age":"{age}","#fn":"{fn}","#id":"{id}","#username":"******","#msgs":"{msgs}","#stast":"{stast}","#edits":"{edits}","#rate":"{rate}","{us}":"{username}","#us":"{username}"}
          for v in rep.keys():
            tx = tx.replace(v,rep[v])
          Bot("sendMessage",{"chat_id":chatID,"text":tx.format(fn=userFN,username=("@"+username or "n"),id=userID,stast=IDrank(redis,userID,chatID,r),cn=title),"reply_to_message_id":message.message_id,"parse_mode":"html"})
        except Exception as e:
          Bot("sendMessage",{"chat_id":chatID,"text":tx,"reply_to_message_id":message.message_id,"parse_mode":"html"})
      if not redis.sismember("{}Nbot:ReplyMedia".format(BOT_ID),chatID):
        if redis.hexists("{}Nbot:STreplys".format(BOT_ID),text):
          ID = redis.hget("{}Nbot:STreplys".format(BOT_ID),text)
          Bot("sendSticker",{"chat_id":chatID,"sticker":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:GFreplys".format(BOT_ID),text):
          ID = redis.hget("{}Nbot:GFreplys".format(BOT_ID),text)
          Bot("sendanimation",{"chat_id":chatID,"animation":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:{}:VOreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:VOreplys".format(BOT_ID),text)
          Bot("sendvoice",{"chat_id":chatID,"voice":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:PHreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:PHreplys".format(BOT_ID),text)
          Bot("sendphoto",{"chat_id":chatID,"photo":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:DOreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:DOreplys".format(BOT_ID),text)
          Bot("sendDocument",{"chat_id":chatID,"document":ID,"reply_to_message_id":message.message_id})



    if not redis.sismember("{}Nbot:ReplySend".format(BOT_ID),chatID):
      if redis.hexists("{}Nbot:{}:TXreplys".format(BOT_ID,chatID),text):
        tx = redis.hget("{}Nbot:{}:TXreplys".format(BOT_ID,chatID),text)
        try:
          rep = {"#cn":"{cn}","#age":"{age}","#fn":"{fn}","#id":"{id}","#username":"******","#msgs":"{msgs}","#stast":"{stast}","#edits":"{edits}","#rate":"{rate}","{us}":"{username}","#us":"{username}"}
          for v in rep.keys():
            tx = tx.replace(v,rep[v])
          Bot("sendMessage",{"chat_id":chatID,"text":tx.format(fn=userFN,username=("@"+username or "n"),id=userID,stast=IDrank(redis,userID,chatID,r),cn=title),"reply_to_message_id":message.message_id,"parse_mode":"html"})
        except Exception as e:
          Bot("sendMessage",{"chat_id":chatID,"text":tx,"reply_to_message_id":message.message_id,"parse_mode":"html"})
      if not redis.sismember("{}Nbot:ReplyMedia".format(BOT_ID),chatID):
        if redis.hexists("{}Nbot:{}:STreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:{}:STreplys".format(BOT_ID,chatID),text)
          Bot("sendSticker",{"chat_id":chatID,"sticker":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:{}:GFreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:{}:GFreplys".format(BOT_ID,chatID),text)
          Bot("sendanimation",{"chat_id":chatID,"animation":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:{}:VOreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:{}:VOreplys".format(BOT_ID,chatID),text)
          Bot("sendvoice",{"chat_id":chatID,"voice":ID,"reply_to_message_id":message.message_id})
        
        if redis.hexists("{}Nbot:{}:AUreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:{}:AUreplys".format(BOT_ID,chatID),text)
          Bot("sendaudio",{"chat_id":chatID,"audio":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:{}:PHreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:{}:PHreplys".format(BOT_ID,chatID),text)
          Bot("sendphoto",{"chat_id":chatID,"photo":ID,"reply_to_message_id":message.message_id})
        if redis.hexists("{}Nbot:{}:DOreplys".format(BOT_ID,chatID),text):
          ID = redis.hget("{}Nbot:{}:DOreplys".format(BOT_ID,chatID),text)
          Bot("sendDocument",{"chat_id":chatID,"document":ID,"reply_to_message_id":message.message_id})

  if redis.smembers("{}Nbot:botfiles".format(BOT_ID)):
    onlyfiles = [f for f in listdir("files") if isfile(join("files", f))]
    filesR = redis.smembers("{}Nbot:botfiles".format(BOT_ID))
    for f in onlyfiles:
      if f in filesR:
        fi = f.replace(".py","")
        UpMs= "files."+fi
        try:
          U = importlib.import_module(UpMs)
          t = threading.Thread(target=U.updateMsgs,args=(client, message,redis))
          t.daemon = True
          t.start()
          importlib.reload(U)
        except Exception as e:
          import traceback
          traceback.print_exc()
          print(e)
          pass
Пример #5
0
async def geri_don_bilgisi(client:Client, callback_query:CallbackQuery):
    await callback_query.edit_message_text(start_mesajı, reply_markup=InlineKeyboardMarkup(start_butonu))
    await callback_query.answer('Afferin !\nGeri dönmeyi başaran ilk kişi oldun..', show_alert=True)
Пример #6
0
async def start(bot, cmd):
    usr_cmdall1 = cmd.text
    if usr_cmdall1.startswith("/start subinps"):
        if AUTH_CHANNEL:
            invite_link = await bot.create_chat_invite_link(int(AUTH_CHANNEL))
            try:
                user = await bot.get_chat_member(int(AUTH_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.",
                        parse_mode="markdown",
                        disable_web_page_preview=True)
                    return
            except UserNotParticipant:
                ident, file_id = cmd.text.split("_-_-_-_")
                await bot.send_message(
                    chat_id=cmd.from_user.id,
                    text="**Please Join My Updates Channel to use this Bot!**",
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            InlineKeyboardButton("🤖 Join Updates Channel",
                                                 url=invite_link.invite_link)
                        ],
                         [
                             InlineKeyboardButton(
                                 " 🔄 Try Again",
                                 callback_data=f"checksub#{file_id}")
                         ]]),
                    parse_mode="markdown")
                return
            except Exception:
                await bot.send_message(chat_id=cmd.from_user.id,
                                       text="Something went Wrong.",
                                       parse_mode="markdown",
                                       disable_web_page_preview=True)
                return
        try:
            ident, file_id = cmd.text.split("_-_-_-_")
            filedetails = await get_file_details(file_id)
            for files in filedetails:
                file_caption = files.caption
                buttons = [[
                    InlineKeyboardButton('Search again',
                                         switch_inline_query_current_chat=''),
                    InlineKeyboardButton('More Bots',
                                         url='https://t.me/subin_works/122')
                ]]
                await bot.send_cached_media(
                    chat_id=cmd.from_user.id,
                    file_id=file_id,
                    caption=file_caption,
                    reply_markup=InlineKeyboardMarkup(buttons))
        except Exception as err:
            await cmd.reply_text(f"Something went wrong!\n\n**Error:** `{err}`"
                                 )
    elif len(cmd.command) > 1 and cmd.command[1] == 'subscribe':
        invite_link = await bot.create_chat_invite_link(int(AUTH_CHANNEL))
        await bot.send_message(
            chat_id=cmd.from_user.id,
            text="**Please Join My Updates Channel to use this Bot!**",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("🤖 Join Updates Channel",
                                     url=invite_link.invite_link)
            ]]))
    else:
        await cmd.reply_text(
            START_MSG,
            parse_mode="Markdown",
            disable_web_page_preview=True,
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("Search Here",
                                     switch_inline_query_current_chat=''),
                InlineKeyboardButton("Other Bots",
                                     url="https://t.me/subin_works/122")
            ], [InlineKeyboardButton("About", callback_data="about")]]))
Пример #7
0
def message(client, message):
    if message.text.startswith("/"):
        return

    if not is_youtube(message.text):
        message.reply_text(_("play_1"))
        return

    if "list=" in message.text:
        message.reply_text(_("play_2"))
        return

    m = message.reply_text(_("play_3"), quote=True)

    download(
        (m.edit, (_("ytdl_1"), )),
        (m.edit, (_("ytdl_2").format(player.q.qsize() + 1), )),
        [
            player.play,
            [
                None,
                (message.reply_text, (_("player_1"), )),
                (message.reply_text, (_("player_2"), )),
                None,
                None,
                message.from_user.id,
                message.from_user.first_name,
                [
                    client.send_photo,
                    [
                        LOG_GROUP,
                        None,
                        _("group_1").format(
                            '<a href="{}">{}</a>',
                            "{}",
                            '<a href="tg://user?id={}">{}</a>',
                        ),
                        "HTML",
                        None,
                        None,
                        True,
                        None,
                        None,
                        InlineKeyboardMarkup([
                            [
                                InlineKeyboardButton(_("playlist_3"),
                                                     "add_to_playlist"),
                            ],
                        ]),
                    ],
                ] if LOG_GROUP else None,
                None,
                (message.reply_text, (_("skip_3"), )),
            ],
        ],
        (m.edit, (_("ytdl_3"), )),
        message.text,
        (m.edit, (_("error"), )),
        [
            m.edit,
            [
                _("ytdl_4"),
            ],
        ],
    )
Пример #8
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!")
Пример #9
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'})
Пример #10
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()
def IKM(data):
    return InlineKeyboardMarkup([[InlineKeyboardButton(text, cbd)] for text, cbd in data])
Пример #12
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),
            )
Пример #13
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)
Пример #14
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)
Пример #15
0
async def cb_handler(client: Client, query: CallbackQuery):
    if query.from_user.id not in Config.ADMINS and query.data != "help":
        await query.answer("Who the hell you are", show_alert=True)
        return
    else:
        await query.answer()
    if query.data == "replay":
        group_call = mp.group_call
        if not playlist:
            return
        group_call.restart_playout()
        if not playlist:
            pl = f"{emoji.NO_ENTRY} Empty Playlist"
        else:
            pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
                f"**{i}**. **🎸{x[1]}**\n   👤**Requested by:** {x[4]}"
                for i, x in enumerate(playlist)
            ])
        await query.edit_message_text(
            f"{pl}",
            parse_mode="Markdown",
            reply_markup=InlineKeyboardMarkup([
                [
                    InlineKeyboardButton("🔄", callback_data="replay"),
                    InlineKeyboardButton("⏯", callback_data="pause"),
                    InlineKeyboardButton("⏩", callback_data="skip")
                ],
            ]))

    elif query.data == "pause":
        if not playlist:
            return
        else:
            mp.group_call.pause_playout()
            pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
                f"**{i}**. **🎸{x[1]}**\n   👤**Requested by:** {x[4]}"
                for i, x in enumerate(playlist)
            ])
        await query.edit_message_text(
            f"{emoji.PLAY_OR_PAUSE_BUTTON} Paused\n\n{pl}",
            reply_markup=InlineKeyboardMarkup([
                [
                    InlineKeyboardButton("🔄", callback_data="replay"),
                    InlineKeyboardButton("⏯", callback_data="resume"),
                    InlineKeyboardButton("⏩", callback_data="skip")
                ],
            ]))

    elif query.data == "resume":
        if not playlist:
            return
        else:
            mp.group_call.resume_playout()
            pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
                f"**{i}**. **🎸{x[1]}**\n   👤**Requested by:** {x[4]}"
                for i, x in enumerate(playlist)
            ])
        await query.edit_message_text(
            f"{emoji.PLAY_OR_PAUSE_BUTTON} Resumed\n\n{pl}",
            reply_markup=InlineKeyboardMarkup([
                [
                    InlineKeyboardButton("🔄", callback_data="replay"),
                    InlineKeyboardButton("⏯", callback_data="pause"),
                    InlineKeyboardButton("⏩", callback_data="skip")
                ],
            ]))

    elif query.data == "skip":
        if not playlist:
            return
        else:
            await mp.skip_current_playing()
            pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
                f"**{i}**. **🎸{x[1]}**\n   👤**Requested by:** {x[4]}"
                for i, x in enumerate(playlist)
            ])
        try:
            await query.edit_message_text(
                f"{emoji.PLAY_OR_PAUSE_BUTTON} Skipped\n\n{pl}",
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton("🔄", callback_data="replay"),
                        InlineKeyboardButton("⏯", callback_data="pause"),
                        InlineKeyboardButton("⏩", callback_data="skip")
                    ],
                ]))
        except:
            pass
    elif query.data == "help":
        buttons = [[
            InlineKeyboardButton('🎟 Request Movies',
                                 url='https://t.me/MOVIECLUB_CHAT'),
            InlineKeyboardButton('Official Channel 🍿',
                                 url='https://t.me/MovieClubOfficiall'),
        ],
                   [
                       InlineKeyboardButton('👨🏼‍💻 Owner',
                                            url='https://t.me/NickxFury_bot'),
                   ]]
        reply_markup = InlineKeyboardMarkup(buttons)
        await query.edit_message_text(HELP, reply_markup=reply_markup)
Пример #16
0
 async def callback_mm(callback_query: CallbackQuery):
     await callback_query.edit_message_text(
         " 𝐔𝐒𝐄𝐑𝐆𝐄-𝐗  𝗠𝗔𝗜𝗡 𝗠𝗘𝗡𝗨 ",
         reply_markup=InlineKeyboardMarkup(main_menu_buttons()))
Пример #17
0
async def inline(_, query: InlineQuery):
    string = query.query.lower()

    if string == "":
        await query.answer(
            results=docs.DEFAULT_RESULTS,
            cache_time=CACHE_TIME,
            switch_pm_text=f"{emoji.MAGNIFYING_GLASS_TILTED_RIGHT} Type to search Pyrogram Docs",
            switch_pm_parameter="start",
        )

        return

    results = []
    offset = int(query.offset or 0)
    switch_pm_text = f"{emoji.OPEN_BOOK} Pyrogram Docs"

    if string == "!m":
        switch_pm_text = f"{emoji.CLOSED_BOOK} Pyrogram Methods ({len(docs.METHODS)})"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Methods",
                    description="Pyrogram Methods online documentation page",
                    input_message_content=InputTextMessageContent(
                        f"{emoji.FIRE} **Pyrogram Methods**\n\n"
                        f"`This page contains all available high-level Methods existing in Pyrogram v{VERSION}.`"
                    ),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            f"{emoji.OPEN_BOOK} Online docs",
                            url="https://docs.pyrogram.org/api/methods"
                        )
                    ]]),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.METHODS[offset: offset + NEXT_OFFSET]:
            results.append(i[1])
    elif string == "!t":
        switch_pm_text = f"{emoji.GREEN_BOOK} Pyrogram Types ({len(docs.TYPES)})"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Types",
                    description="Pyrogram Types online documentation page",
                    input_message_content=InputTextMessageContent(
                        f"{emoji.FIRE} **Pyrogram Types**\n\n"
                        f"`This page contains all available high-level Types existing in Pyrogram v{VERSION}.`"
                    ),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            f"{emoji.OPEN_BOOK} Online docs",
                            url="https://docs.pyrogram.org/api/types"
                        )
                    ]]),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.TYPES[offset: offset + NEXT_OFFSET]:
            results.append(i[1])
    elif string == "!b":
        switch_pm_text = f"{emoji.CLOSED_BOOK} Pyrogram Bound Methods ({len(docs.BOUND_METHODS)})"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Types",
                    description="Pyrogram Bound Methods online documentation page",
                    input_message_content=InputTextMessageContent(
                        f"{emoji.FIRE} **Pyrogram Bound Methods**\n\n"
                        f"`This page contains all available bound methods existing in Pyrogram v{VERSION}.`"
                    ),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            f"{emoji.OPEN_BOOK} Online docs",
                            url="https://docs.pyrogram.org/api/bound-methods"
                        )]]
                    ),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.BOUND_METHODS[offset: offset + NEXT_OFFSET]:
            results.append(i[1])
    elif string == "!d":
        switch_pm_text = f"{emoji.CLOSED_BOOK} Pyrogram Decorators ({len(docs.DECORATORS)})"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Decorators",
                    description="Pyrogram Decorators online documentation page",
                    input_message_content=InputTextMessageContent(
                        f"{emoji.FIRE} **Pyrogram Decorators**\n\n"
                        f"`This page contains all available decorators existing in Pyrogram v{VERSION}.`"
                    ),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            f"{emoji.OPEN_BOOK} Online docs",
                            url="https://docs.pyrogram.org/api/decorators"
                        )]]
                    ),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.DECORATORS[offset: offset + NEXT_OFFSET]:
            results.append(i[1])
    elif string == "!f":
        switch_pm_text = f"{emoji.CONTROL_KNOBS} Pyrogram Filters ({len(docs.FILTERS)})"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Filters",
                    description="Pyrogram Filters online documentation page",
                    input_message_content=InputTextMessageContent(
                        f"{emoji.FIRE} **Pyrogram Filters**\n\n"
                        f"`This page contains all library-defined Filters available in Pyrogram v{VERSION}.`"
                    ),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            f"{emoji.OPEN_BOOK} Online docs",
                            url="https://docs.pyrogram.org/api/filters"
                        )
                    ]]),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.FILTERS[offset: offset + NEXT_OFFSET]:
            results.append(i[1])
    elif string == "!rm":
        switch_pm_text = f"{emoji.BLUE_BOOK} Raw Methods ({len(docs.RAW_METHODS)})"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Raw Methods",
                    description="Pyrogram Raw Methods online documentation page",
                    input_message_content=InputTextMessageContent(
                        f"{emoji.FIRE} **Pyrogram Raw Methods**\n\n"
                        f"`This page contains all available Raw Methods existing in the Telegram Schema, Layer `"
                        f"`{docs.layer}.`"
                    ),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            f"{emoji.OPEN_BOOK} Online docs",
                            url="https://docs.pyrogram.org/telegram/functions"
                        ),
                        InlineKeyboardButton(
                            f"{emoji.SCROLL} TL Schema",
                            url="https://github.com/pyrogram/pyrogram/blob/develop/compiler/api/source/main_api.tl"
                        ),
                    ]]),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.RAW_METHODS[offset: offset + NEXT_OFFSET]:
            results.append(i[1])
    elif string == "!rt":
        switch_pm_text = f"{emoji.ORANGE_BOOK} Raw Types ({len(docs.RAW_TYPES)})"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Raw Types",
                    description="Pyrogram Raw Types online documentation page",
                    input_message_content=InputTextMessageContent(
                        f"{emoji.FIRE} **Pyrogram Raw Types**\n\n"
                        f"`This page contains all available Raw Types existing in the Telegram Schema, Layer "
                        f"{docs.layer}.`"
                    ),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            f"{emoji.OPEN_BOOK} Online docs",
                            url="https://docs.pyrogram.org/telegram/types"
                        ),
                        InlineKeyboardButton(
                            f"{emoji.SCROLL} TL Schema",
                            url="https://github.com/pyrogram/pyrogram/blob/develop/compiler/api/source/main_api.tl",
                        ),
                    ]]),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.RAW_TYPES[offset: offset + NEXT_OFFSET]:
            results.append(i[1])
    elif string == "rules":
        switch_pm_text = f"{emoji.SCROLL} Chat Rules"

        if offset == 0:
            results.append(
                InlineQueryResultArticle(
                    title="Chat Rules",
                    description="These are the rules for the Pyrogram Inn and the chats for other languages.",
                    input_message_content=InputTextMessageContent(docs.rules),
                    thumb_url=FIRE_THUMB,
                )
            )

        for i in docs.RULES[offset: offset + NEXT_OFFSET]:
            results.append(i)
    elif string == "colin":
        switch_pm_text = f"{emoji.SHARK} Hidden Shark"

        if offset == 0:
            results.append(
                InlineQueryResultPhoto(
                    photo_url="https://i.imgur.com/f32hngs.jpg",
                    # thumb_url="https://i.imgur.com/f32hngs.jpg",
                    title="You found the secret Sharkception :O",
                    description="You might not get anything from it, but you can feel proud to have found me!",
                    caption=f"Hey, I found @ColinShark {emoji.SHARK}",
                    # input_message_content=InputTextMessageContent(f"Hey, I found @ColinShark {emoji.SHARK}"),
                )
            )

    if results:
        await query.answer(
            results=results,
            cache_time=CACHE_TIME,
            switch_pm_text=switch_pm_text,
            switch_pm_parameter="start",
            next_offset=str(offset + NEXT_OFFSET),
            is_gallery=False
        )
    else:
        if offset:
            await query.answer(
                results=[],
                cache_time=CACHE_TIME,
                switch_pm_text=switch_pm_text,
                switch_pm_parameter="start",
                next_offset="",
            )

        if string.startswith("!r"):
            string = " ".join(string.split(" ")[1:])

            if string == "":
                await query.answer(
                    results=[],
                    cache_time=CACHE_TIME,
                    switch_pm_text=f"{emoji.MAGNIFYING_GLASS_TILTED_RIGHT} Type to search Raw Docs",
                    switch_pm_parameter="start",
                )

            for i in docs.RAW_METHODS:
                if string in i[0].lower():
                    results.append(i[1])

            for i in docs.RAW_TYPES:
                if string in i[0].lower():
                    results.append(i[1])

        else:
            for i in docs.METHODS:
                if string in i[0].lower():
                    results.append(i[1])

            for i in docs.TYPES:
                if string in i[0].lower():
                    results.append(i[1])

            for i in docs.BOUND_METHODS:
                if string in i[0].lower():
                    results.append(i[1])

            for i in docs.DECORATORS:
                if string in i[0].lower():
                    results.append(i[1])

            for i in docs.FILTERS:
                if string in i[0].lower():
                    results.append(i[1])

        if results:
            count = len(results)
            switch_pm_text = f"{emoji.OPEN_BOOK} {count} Result{'s' if count > 1 else ''} for \"{string}\""

            await query.answer(
                results=results[:50],
                cache_time=CACHE_TIME,
                switch_pm_text=switch_pm_text,
                switch_pm_parameter="start"
            )
        else:
            await query.answer(
                results=[],
                cache_time=CACHE_TIME,
                switch_pm_text=f'{emoji.CROSS_MARK} No results for "{string}"',
                switch_pm_parameter="okay",
            )
Пример #18
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")
Пример #19
0
async def rename_doc(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, "rename")
    if (" " in update.text) and (update.reply_to_message is not None):
        cmd, file_name = update.text.split(" ", 1)
        if len(file_name) > 64:
            await update.reply_text(
                Translation.IFLONG_FILE_NAME.format(alimit="64",
                                                    num=len(file_name)))
            return
        description = Translation.CUSTOM_CAPTION_UL_FILE
        download_location = Config.DOWNLOAD_LOCATION + "/"
        a = await bot.send_message(chat_id=update.chat.id,
                                   text=Translation.DOWNLOAD_START,
                                   reply_to_message_id=update.message_id)
        c_time = time.time()
        the_real_download_location = await bot.download_media(
            message=update.reply_to_message,
            file_name=download_location,
            progress=progress_for_pyrogram,
            progress_args=(Translation.DOWNLOAD_START, a, c_time))
        if the_real_download_location is not None:
            try:
                await bot.edit_message_text(
                    text=Translation.SAVED_RECVD_DOC_FILE,
                    chat_id=update.chat.id,
                    message_id=a.message_id)
            except:
                pass
            new_file_name = download_location + file_name
            os.rename(the_real_download_location, new_file_name)
            await bot.edit_message_text(text=Translation.UPLOAD_START,
                                        chat_id=update.chat.id,
                                        message_id=a.message_id)
            logger.info(the_real_download_location)
            thumb_image_path = Config.DOWNLOAD_LOCATION + "/" + str(
                update.from_user.id) + ".jpg"
            if not os.path.exists(thumb_image_path):
                mes = await thumb(update.from_user.id)
                if mes != None:
                    m = await bot.get_messages(update.chat.id, mes.msg_id)
                    await m.download(file_name=thumb_image_path)
                    thumb_image_path = thumb_image_path
                else:
                    thumb_image_path = None
            else:
                width = 0
                height = 0
                metadata = extractMetadata(createParser(thumb_image_path))
                if metadata.has("width"):
                    width = metadata.get("width")
                if metadata.has("height"):
                    height = metadata.get("height")
                # resize image
                # ref: https://t.me/PyrogramChat/44663
                # https://stackoverflow.com/a/21669827/4723940
                Image.open(thumb_image_path).convert("RGB").save(
                    thumb_image_path)
                img = Image.open(thumb_image_path)
                # https://stackoverflow.com/a/37631799/4723940
                # img.thumbnail((90, 90))
                img.resize((320, height))
                img.save(thumb_image_path, "JPEG")
                # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails
            c_time = time.time()
            await bot.send_document(
                chat_id=update.chat.id,
                document=new_file_name,
                thumb=thumb_image_path,
                caption=f"<b>{file_name}</b>",
                # reply_markup=reply_markup,
                reply_to_message_id=update.reply_to_message.message_id,
                progress=progress_for_pyrogram,
                progress_args=(Translation.UPLOAD_START, a, c_time))
            try:
                os.remove(new_file_name)
                os.remove(thumb_image_path)
            except:
                pass
            await bot.edit_message_text(
                text=Translation.AFTER_SUCCESSFUL_UPLOAD_MSG,
                chat_id=update.chat.id,
                message_id=a.message_id,
                disable_web_page_preview=True)
    update_channel = Config.UPDATE_CHANNEL
    if update_channel:
        try:
            user = await bot.get_chat_member(update_channel, update.chat.id)
            if user.status == "kicked":
                await update.reply_text(" Sorry, You are **B A N N E D**")
                return
        except UserNotParticipant:
            #await update.reply_text(f"Join @{update_channel} To Use Me")
            await update.reply_text(
                text="**Please Join My Update Channel Before Using Me..**",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(text="Join My Updates Channel",
                                         url=f"https://t.me/{update_channel}")
                ]]))
            return
        else:
            await bot.send_message(
                chat_id=update.chat.id,
                text=Translation.REPLY_TO_DOC_FOR_RENAME_FILE,
                reply_to_message_id=update.message_id)
Пример #20
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
Пример #21
0
def default_markup():
    buttons = InlineKeyboardMarkup([[
        InlineKeyboardButton(text="⏩ Skip", callback_data="skip"),
        InlineKeyboardButton(text="🗒 Queue", callback_data="queue")
    ]])
    return buttons
Пример #22
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)
Пример #23
0
async def _login(c, m):

    await m.reply_chat_action("typing")
    await m.reply_text(text=tr.LOGIN_MSG[1],
                       disable_web_page_preview=True,
                       reply_markup=InlineKeyboardMarkup(map_btns(1)))
Пример #24
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()
Пример #25
0
async def yardim_bilgisi(client:Client, callback_query:CallbackQuery):
    await callback_query.edit_message_text(
        "__Ana Komutlarım Şunlar:__\n\n`.yardim`\n`.destek`\n`.logsalla`\n\n**Diğer komutlarım için /eklentilist'e bakabilirsin..**",
        reply_markup=InlineKeyboardMarkup(yardim_butonu)
    )
Пример #26
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")
Пример #27
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()
Пример #28
0
async def jiosaavn(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 group 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 @DaisyXmusic 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(
            "<i> helper Userbot not in this channel, Ask channel admin to send /play command for first time or add assistant manually</i>"
        )
        return
    requested_by = message_.from_user.first_name
    chat_id = message_.chat.id
    text = message_.text.split(" ", 1)
    query = text[1]
    res = lel
    await res.edit(f"Searching 👀👀👀 for `{query}` on jio saavn")
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(
                f"https://jiosaavnapi.bhadoo.uk/result/?query={query}"
            ) as resp:
                r = json.loads(await resp.text())
        sname = r[0]["song"]
        slink = r[0]["media_url"]
        ssingers = r[0]["singers"]
        sthumb = r[0]["image"]
        sduration = int(r[0]["duration"])
    except Exception as e:
        await res.edit("Found Literally Nothing!, You Should Work On Your English.")
        print(str(e))
        return
    keyboard = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton("📖 Playlist", callback_data="cplaylist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="cmenu"),
            ],
            [
                InlineKeyboardButton(
                    text="Join Updates Channel", url=f"{updateschannel}"
                )
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="ccls")],
        ]
    )
    file_path = await convert(wget.download(slink))
    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 = sname
        r_by = message_.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await res.delete()
        m = await client.send_photo(
            chat_id=message_.chat.id,
            reply_markup=keyboard,
            photo="final.png",
            caption=f"✯{bn}✯=#️⃣ Queued at position {position}",
        )

    else:
        await res.edit_text(f"{bn}=▶️ Playing.....")
        que[chat_id] = []
        qeue = que.get(chat_id)
        s_name = sname
        r_by = message_.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(chat_id, file_path)
    await res.edit("Generating Thumbnail.")
    await generate_cover(requested_by, sname, ssingers, sduration, sthumb)
    await res.delete()
    m = await client.send_photo(
        chat_id=message_.chat.id,
        reply_markup=keyboard,
        photo="final.png",
        caption=f"Playing {sname} Via Jiosaavn in linked channel",
    )
    os.remove("final.png")
Пример #29
0
def _start(client, message):
    update_channel = UPDATES_CHANNEL
    if update_channel:
        try:
            user = client.get_chat_member(update_channel, message.chat.id)
            if user.status == "kicked":
                client.send_message(
                    chat_id=message.chat.id,
                    text=
                    "Sorry Sir, You are Banned to use me. Contact me [Support Group](https://t.me/sunilroy007).",
                    parse_mode="markdown",
                    disable_web_page_preview=True)
                return
        except UserNotParticipant:
            client.send_message(
                chat_id=message.chat.id,
                text="**Please Join My Updates Channel to use this Bot!**",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton("Join Updates Channel",
                                         url=f"https://t.me/{update_channel}")
                ]]),
                parse_mode="markdown")
            return
        except Exception:
            client.send_message(
                message.chat.id,
                text=tr.START_MSG.format(message.from_user.first_name,
                                         message.from_user.id),
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            "Join Updates Channel",
                            url="https://t.me/sunils_mirror_leech"),
                        InlineKeyboardButton(
                            "Support Group",
                            url="https://t.me/sunils_mirror_leech")
                    ],
                     [
                         InlineKeyboardButton("🧑‍💻Devloper🧑‍💻",
                                              url="https://t.me/sunilroy007")
                     ]]),
                parse_mode="markdown",
                reply_to_message_id=message.message_id)
            return
    client.send_message(
        message.chat.id,
        text=tr.START_MSG.format(message.from_user.first_name,
                                 message.from_user.id),
        reply_markup=InlineKeyboardMarkup(
            [[
                InlineKeyboardButton("Join Updates Channel",
                                     url="https://t.me/sunils_mirror_leech"),
                InlineKeyboardButton("Support Group",
                                     url="https://t.me/sunils_mirror_leech")
            ],
             [
                 InlineKeyboardButton("🧑‍💻Devloper🧑‍💻",
                                      url="https://t.me/sunilroy007")
             ]]),
        parse_mode="markdown",
        reply_to_message_id=message.message_id)
Пример #30
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")
             ]]))