コード例 #1
0
ファイル: spam.py プロジェクト: BruceWayne175/VirtualUserbot
def banchecker(user_id):
    try:
        casurl = "https://api.cas.chat/check?user_id={}".format(user_id)
        data = get(casurl).json()
    except Exception as e:
        LOGS.info(e)
        data = None
    return bool(data and data["ok"])
コード例 #2
0
ファイル: aria2.py プロジェクト: Kaveesha-Induwara/userbot
async def amagnet_download(event):
    uri = [event.pattern_match.group(1)]
    try:  # URL'yi kuyruğa ekler.
        download = aria2.add_uris(uri, options=None, position=None)
    except Exception as e:
        LOGS.info(str(e))
        await event.edit("Hata :\n`{}`".format(str(e)))
        return
    gid = download.gid
    await check_progress_for_dl(gid=gid, event=event, previous=None)
    file = aria2.get_download(gid)
    if file.followed_by_ids:
        new_gid = await check_metadata(gid)
        await progress_status(gid=new_gid, event=event, previous=None)
コード例 #3
0
ファイル: aria2.py プロジェクト: Kaveesha-Induwara/userbot
async def magnet_download(event):
    magnet_uri = event.pattern_match.group(1)
    # Magnet URI'ı kuyruğa ekler.
    try:
        download = aria2.add_magnet(magnet_uri)
    except Exception as e:
        LOGS.info(str(e))
        await event.edit("Hata:\n`" + str(e) + "`")
        return
    gid = download.gid
    await check_progress_for_dl(gid=gid, event=event, previous=None)
    await sleep(5)
    new_gid = await check_metadata(gid)
    await check_progress_for_dl(gid=new_gid, event=event, previous=None)
コード例 #4
0
ファイル: aria2.py プロジェクト: 00gimsara00/Cat-Userbot
async def check_progress_for_dl(gid, event, previous):
    complete = None
    while not complete:
        file = aria2.get_download(gid)
        complete = file.is_complete
        try:
            if not complete and not file.error_message:
                msg = f"\nİndirilen dosya: `{file.name}`"
                msg += f"\nHız: {file.download_speed_string()}"
                msg += f"\nİşlem: {file.progress_string()}"
                msg += f"\nToplam Boyut: {file.total_length_string()}"
                msg += f"\nDurum: {file.status}"
                msg += f"\nTahmini bitiş: {file.eta_string()}"
                if msg != previous:
                    await event.edit(msg)
                    msg = previous
            else:
                LOGS.info(str(file.error_message))
                await event.edit(f"`{msg}`")
            await sleep(5)
            await check_progress_for_dl(gid, event, previous)
            file = aria2.get_download(gid)
            complete = file.is_complete
            if complete:
                await event.edit(f"Dosya başarıyla indirdi: `{file.name}`")
                return False
        except Exception as e:
            if " not found" in str(e) or "'file'" in str(e):
                await event.edit("İndirme iptal edildi :\n`{}`".format(file.name))
                await sleep(2.5)
                await event.delete()
                return
            elif " depth exceeded" in str(e):
                file.remove(force=True)
                await event.edit(
                    "İndirme otomatik olarak iptal edildi:\n`{}`\nTorrent ya da link ölü.".format(
                        file.name
                    )
                )
コード例 #5
0
async def download(target_file):
    """ For .dl command, download files to the fridaybot's server. """
    friday = await edit_or_reply(target_file, "`Processing ...`")
    await friday.edit("Processing using fridaybot server ( ◜‿◝ )♡")
    input_str = target_file.pattern_match.group(1)
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
    if "|" in input_str:
        url, file_name = input_str.split("|")
        url = url.strip()
        # https://stackoverflow.com/a/761825/4723940
        file_name = file_name.strip()
        head, tail = os.path.split(file_name)
        if head:
            if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)):
                os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head))
                file_name = os.path.join(head, tail)
        downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name
        downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
        downloader.start(blocking=False)
        c_time = time.time()
        display_message = None
        while not downloader.isFinished():
            status = downloader.get_status().capitalize()
            total_length = downloader.filesize if downloader.filesize else None
            downloaded = downloader.get_dl_size()
            now = time.time()
            diff = now - c_time
            percentage = downloader.get_progress() * 100
            downloader.get_speed()
            round(diff) * 1000
            progress_str = "[{0}{1}] {2}%".format(
                "".join(["▰" for i in range(math.floor(percentage / 10))]),
                "".join(["▱"
                         for i in range(10 - math.floor(percentage / 10))]),
                round(percentage, 2),
            )
            estimated_total_time = downloader.get_eta(human=True)
            try:
                current_message = f"{status}..\
                \nFOR : F.R.I.D.A.Y™ AND INDIANBOT™\
                \nURL: {url}\
                \nFile Name: {file_name}\
                \n{progress_str}\
                \n{humanbytes(downloaded)} of {humanbytes(total_length)}\
                \nETA: {estimated_total_time}"

                if round(diff %
                         10.00) == 0 and current_message != display_message:
                    await friday.edit(current_message)
                    display_message = current_message
            except Exception as e:
                LOGS.info(str(e))
        if downloader.isSuccessful():
            await friday.edit("Downloaded to `{}` successfully !!".format(
                downloaded_file_name))
        else:
            await friday.edit("Incorrect URL\n{}".format(url))
    elif target_file.reply_to_msg_id:
        try:
            c_time = time.time()
            downloaded_file_name = await target_file.client.download_media(
                await target_file.get_reply_message(),
                TEMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(
                    progress(d, t, target_file, c_time, "Downloading...")),
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await friday.edit(str(e))
        else:
            await friday.edit("Downloaded to `{}` successfully !!".format(
                downloaded_file_name))
    else:
        await friday.edit("Reply to a message to download to my local server.")
コード例 #6
0
async def uploadir(udir_event):
    """ For .uploadir command, allows you to upload everything from a folder in the server"""
    input_str = udir_event.pattern_match.group(1)
    if os.path.exists(input_str):
        await udir_event.edit("Downloading Using Userbot Server....")
        lst_of_files = []
        for r, d, f in os.walk(input_str):
            for file in f:
                lst_of_files.append(os.path.join(r, file))
            for file in d:
                lst_of_files.append(os.path.join(r, file))
        LOGS.info(lst_of_files)
        uploaded = 0
        await udir_event.edit(
            "Found {} files. Uploading will start soon. Please wait!".format(
                len(lst_of_files)))
        for single_file in lst_of_files:
            if os.path.exists(single_file):
                # https://stackoverflow.com/a/678242/4723940
                caption_rts = os.path.basename(single_file)
                c_time = time.time()
                if not caption_rts.lower().endswith(".mp4"):
                    await udir_event.client.send_file(
                        udir_event.chat_id,
                        single_file,
                        caption=caption_rts,
                        force_document=False,
                        allow_cache=False,
                        reply_to=udir_event.message.id,
                        progress_callback=lambda d, t: asyncio.get_event_loop(
                        ).create_task(
                            progress(
                                d,
                                t,
                                udir_event,
                                c_time,
                                "Uploading in Progress.......",
                                single_file,
                            )),
                    )
                else:
                    thumb_image = os.path.join(input_str, "thumb.jpg")
                    c_time = time.time()
                    metadata = extractMetadata(createParser(single_file))
                    duration = 0
                    width = 0
                    height = 0
                    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")
                    await udir_event.client.send_file(
                        udir_event.chat_id,
                        single_file,
                        caption=caption_rts,
                        thumb=thumb_image,
                        force_document=False,
                        allow_cache=False,
                        reply_to=udir_event.message.id,
                        attributes=[
                            DocumentAttributeVideo(
                                duration=duration,
                                w=width,
                                h=height,
                                round_message=False,
                                supports_streaming=True,
                            )
                        ],
                        progress_callback=lambda d, t: asyncio.get_event_loop(
                        ).create_task(
                            progress(d, t, udir_event, c_time, "Uploading...",
                                     single_file)),
                    )
                os.remove(single_file)
                uploaded = uploaded + 1
        await udir_event.edit(
            "Uploaded {} files successfully !!".format(uploaded))
    else:
        await udir_event.edit("404: Directory Not Found")
コード例 #7
0
async def mega_downloader(megadl):
    await megadl.edit("`Collecting information...`")
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
    msg_link = await megadl.get_reply_message()
    link = megadl.pattern_match.group(1)
    if link:
        pass
    elif msg_link:
        link = msg_link.text
    else:
        return await megadl.edit("Usage: `.mega` **<MEGA.nz link>**")
    try:
        link = re.findall(r"\bhttps?://.*mega.*\.nz\S+", link)[0]
        # - Mega changed their URL again -
        if "file" in link:
            link = link.replace("#", "!").replace("file/", "#!")
        elif "folder" in link or "#F" in link or "#N" in link:
            await megadl.edit("`folder download support are removed...`")
            return
    except IndexError:
        await megadl.edit("`MEGA.nz link not found...`")
        return None
    cmd = f"./DOWNLOADS -q -m {link}"
    result = await subprocess_run(megadl, cmd)
    try:
        data = json.loads(result[0])
    except json.JSONDecodeError:
        await megadl.edit("**JSONDecodeError**: `failed to extract link...`")
        return None
    except (IndexError, TypeError):
        return
    file_name = data["file_name"]
    file_url = data["url"]
    hex_key = data["hex_key"]
    hex_raw_key = data["hex_raw_key"]
    temp_file_name = file_name + ".temp"
    temp_file_path = os.path.join(TEMP_DOWNLOAD_DIRECTORY, temp_file_name)
    file_path = os.path.join(TEMP_DOWNLOAD_DIRECTORY, file_name)
    if os.path.isfile(file_path):
        try:
            raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST),
                                  file_path)
        except FileExistsError as e:
            await megadl.edit(f"`{str(e)}`")
            return None
    downloader = SmartDL(file_url, temp_file_path, progress_bar=False)
    display_message = None
    try:
        downloader.start(blocking=False)
    except HTTPError as e:
        await megadl.edit(f"**HTTPError**: `{str(e)}`")
        return None
    start = time.time()
    while not downloader.isFinished():
        status = downloader.get_status().capitalize()
        total_length = downloader.filesize if downloader.filesize else None
        downloaded = downloader.get_dl_size()
        percentage = int(downloader.get_progress() * 100)
        speed = downloader.get_speed(human=True)
        estimated_total_time = round(downloader.get_eta())
        progress_str = "`{0}` | [{1}{2}] `{3}%`".format(
            status,
            "".join(["⬤" for i in range(math.floor(percentage / 10))]),
            "".join(["◯" for i in range(10 - math.floor(percentage / 10))]),
            round(percentage, 2),
        )
        diff = time.time() - start
        try:
            current_message = (
                f"**➥file name : **`{file_name}`\n\n"
                "**➥Status**\n"
                f"{progress_str}\n"
                f"`{humanbytes(downloaded)}` of `{humanbytes(total_length)}`"
                f" @ `{speed}`\n"
                f"**➥ETA -> **`{time_formatter(estimated_total_time)}`\n"
                f"**➥ Duration -> **`{time_formatter(round(diff))}`")
            if round(diff % 15.00) == 0 and (display_message != current_message
                                             or total_length == downloaded):
                await megadl.edit(current_message)
                await asyncio.sleep(0.2)
                display_message = current_message
        except Exception:
            pass
        finally:
            if status == "Combining":
                wait = round(downloader.get_eta())
                await asyncio.sleep(wait)
    if downloader.isSuccessful():
        download_time = round(downloader.get_dl_time() + wait)
        try:
            P = multiprocessing.Process(
                target=await decrypt_file(megadl, file_path, temp_file_path,
                                          hex_key, hex_raw_key),
                name="Decrypt_File",
            )
            P.start()
            P.join()
        except FileNotFoundError as e:
            await megadl.edit(f"`{str(e)}`")
            return None
        else:
            await megadl.edit(
                f"**➥ file name : **`{file_name}`\n\n"
                f"**➥ Successfully downloaded in : ** `{file_path}`.\n"
                f"**➥ Download took :** {time_formatter(download_time)}.")
            return None
    else:
        await megadl.edit("`Failed to download, "
                          "check heroku Logs for more details.`")
        for e in downloader.get_errors():
            LOGS.info(str(e))
    return
コード例 #8
0
ファイル: spam.py プロジェクト: BruceWayne175/VirtualUserbot
 async def anti_spambot(event):
     if not event.user_joined and not event.user_added:
         return
     chat = event.chat_id
     user = await event.get_user()
     catadmin = await is_admin(bot, chat, bot.uid)
     if not catadmin:
         return
     catbanned = None
     adder = None
     ignore = None
     if event.user_added:
         try:
             adder = event.action_message.sender_id
         except AttributeError:
             return
     async for admin in event.client.iter_participants(
             event.chat_id, filter=ChannelParticipantsAdmins):
         if admin.id == adder:
             ignore = True
             break
     if ignore:
         return
     if is_gbanned(user.id):
         catgban = get_gbanuser(user.id)
         if catgban.reason:
             hmm = await event.reply(
                 f"[{user.first_name}](tg://user?id={user.id}) was gbanned by you for the reason `{catgban.reason}`"
             )
         else:
             hmm = await event.reply(
                 f"[{user.first_name}](tg://user?id={user.id}) was gbanned by you"
             )
         try:
             await bot.edit_permissions(chat, user.id, view_messages=False)
             catbanned = True
         except Exception as e:
             LOGS.info(e)
     if spamwatch and not catbanned:
         ban = spamwatch.get_ban(user.id)
         if ban:
             hmm = await event.reply(
                 f"[{user.first_name}](tg://user?id={user.id}) was banned by spamwatch for the reason `{ban.reason}`"
             )
             try:
                 await bot.edit_permissions(chat,
                                            user.id,
                                            view_messages=False)
                 catbanned = True
             except Exception as e:
                 LOGS.info(e)
     if not catbanned:
         try:
             casurl = "https://api.cas.chat/check?user_id={}".format(
                 user.id)
             data = get(casurl).json()
         except Exception as e:
             LOGS.info(e)
             data = None
         if data and data["ok"]:
             reason = (
                 f"[Banned by Combot Anti Spam](https://cas.chat/query?u={user.id})"
             )
             hmm = await event.reply(
                 f"[{user.first_name}](tg://user?id={user.id}) was banned by Combat anti-spam service(CAS) for the reason check {reason}"
             )
             try:
                 await bot.edit_permissions(chat,
                                            user.id,
                                            view_messages=False)
                 catbanned = True
             except Exception as e:
                 LOGS.info(e)
     if BOTLOG and catbanned:
         await event.client.send_message(
             BOTLOG_CHATID,
             "#ANTISPAMBOT\n"
             f"**User :** [{user.first_name}](tg://user?id={user.id})\n"
             f"**Chat :** {event.chat.title} (`{event.chat_id}`)\n"
             f"**Reason :** {hmm.text}",
         )
コード例 #9
0
ファイル: aria2.py プロジェクト: Kaveesha-Induwara/userbot
async def check_metadata(gid):
    file = aria2.get_download(gid)
    new_gid = file.followed_by_ids[0]
    LOGS.info("GID " + gid + " şu değerden şu değere değiştiriliyor:" +
              new_gid)
    return new_gid