Example #1
0
 def cancel_download(self):
     LOGGER.info(f"Cancelling Download: {self.name()}")
     self.client.torrents_pause(torrent_hashes=self.__hash)
     sleep(0.3)
     self.listener.onDownloadError('Download stopped by user!')
     self.client.torrents_delete(torrent_hashes=self.__hash)
Example #2
0
    dispatcher.add_handler(source_handler)
    dispatcher.add_handler(M_CONNECT_BTN_HANDLER)
    dispatcher.add_handler(IMDB_HANDLER)
    dispatcher.add_handler(IMDB_SEARCHDATAHANDLER)
    

    # dispatcher.add_error_handler(error_callback)

    if WEBHOOK:
        LOGGER.info("Using webhooks.")
        updater.start_webhook(listen="127.0.0.1",
                              port=PORT,
                              url_path=TOKEN)

        if CERT_PATH:
            updater.bot.set_webhook(url=URL + TOKEN,
                                    certificate=open(CERT_PATH, 'rb'))
        else:
            updater.bot.set_webhook(url=URL + TOKEN)

    else:
        LOGGER.info("bot running...")
        updater.start_polling(timeout=15, read_latency=4)

    updater.idle()

    
if __name__ == '__main__':
    LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES))
    main()
Example #3
0
from bot import LOGGER
from ..filetocloud import CloudBot
from .upload import server_upload
from ..helpers import download_media
from pyrogram.types import CallbackQuery

logger = LOGGER(__name__)


async def upload_handler(client: CloudBot, message: CallbackQuery,
                         file_name: str, file_size: str, callback_data: str):

    try:
        FILE_PATH = await download_media(client, message)
    except Exception as e:
        logger.error(f"{e}")
        await client.edit_message_text(
            chat_id=message.from_user.id,
            message_id=message.message.message_id,
            text=f"**File downloading error:** `{e}`",
        )
        return
    try:
        if callback_data.startswith('transfersh'):
            await client.edit_message_text(
                chat_id=message.message.chat.id,
                text="Temporarily down",
                message_id=message.message.message_id,
            )
            return
Example #4
0
    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [
        basename(f)[:-3] for f in mod_paths
        if isfile(f) and f.endswith(".py") and not f.endswith('__init__.py')
    ]

    if LOAD or NO_LOAD:
        to_load = LOAD
        if to_load:
            if not all(
                    any(mod == module_name for module_name in all_modules)
                    for mod in to_load):
                LOGGER.error("Invalid loadorder names. Quitting.")
                quit(1)

        else:
            to_load = all_modules

        if NO_LOAD:
            LOGGER.info("Not loading: {}".format(NO_LOAD))
            return [item for item in to_load if item not in NO_LOAD]

        return to_load

    return all_modules


ALL_MODULES = sorted(__list_all_modules())
LOGGER.info("Modules to load: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]
Example #5
0
def deleteMessage(bot, message: Message):
    try:
        bot.delete_message(chat_id=message.chat.id,
                           message_id=message.message_id)
    except Exception as e:
        LOGGER.error(str(e))
Example #6
0
def extract_user_and_text(message: Message,
                          args: List[str]) -> (Optional[int], Optional[str]):
    prev_message = message.reply_to_message
    split_text = message.text.split(None, 1)

    if len(split_text) < 2:
        return id_from_reply(message)  # only option possible

    text_to_parse = split_text[1]

    text = ""

    entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
    if len(entities) > 0:
        ent = entities[0]
    else:
        ent = None

    # if entity offset matches (command end/text start) then all good
    if entities and ent and ent.offset == len(
            message.text) - len(text_to_parse):
        ent = entities[0]
        user_id = ent.user.id
        text = message.text[ent.offset + ent.length:]

    elif len(args) >= 1 and args[0][0] == '@':
        user = args[0]
        user_id = get_user_id(user)
        if not user_id:
            message.reply_text(
                "No idea who this user is. You'll be able to interact with them if "
                "you reply to that person's message instead, or forward one of that user's messages."
            )
            return None, None

        else:
            user_id = user_id
            res = message.text.split(None, 2)
            if len(res) >= 3:
                text = res[2]

    elif len(args) >= 1 and args[0].isdigit():
        user_id = int(args[0])
        res = message.text.split(None, 2)
        if len(res) >= 3:
            text = res[2]

    elif prev_message:
        user_id, text = id_from_reply(message)

    else:
        return None, None

    try:
        message.bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message in ("User_id_invalid", "Chat not found"):
            message.reply_text(
                "I don't seem to have interacted with this user before - please forward a message from "
                "them to give me control! (like a voodoo doll, I need a piece of them to be able "
                "to execute certain commands...)")
        else:
            LOGGER.exception("Exception %s on user %s", excp.message, user_id)

        return None, None

    return user_id, text
Example #7
0
def del_blackliststicker(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user
    to_match = message.sticker
    if not to_match:
        return

    getmode, value = sql.get_blacklist_setting(chat.id)

    chat_filters = sql.get_chat_stickers(chat.id)
    for trigger in chat_filters:
        if to_match.set_name.lower() == trigger.lower():
            try:
                if getmode == 0:
                    return
                elif getmode == 1:
                    message.delete()
                elif getmode == 2:
                    message.delete()
                    warn(update.effective_user,
                         chat,
                         "Using sticker '{}' which in blacklist stickers".
                         format(trigger),
                         message,
                         update.effective_user,
                         conn=False)
                    return
                elif getmode == 3:
                    message.delete()
                    bot.restrict_chat_member(chat.id,
                                             update.effective_user.id,
                                             can_send_messages=False)
                    bot.sendMessage(
                        chat.id,
                        "{} muted because using '{}' which in blacklist stickers"
                        .format(mention_markdown(user.id, user.first_name),
                                trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 4:
                    message.delete()
                    res = chat.unban_member(update.effective_user.id)
                    if res:
                        bot.sendMessage(
                            chat.id,
                            "{} kicked because using '{}' which in blacklist stickers"
                            .format(mention_markdown(user.id, user.first_name),
                                    trigger),
                            parse_mode="markdown")
                    return
                elif getmode == 5:
                    message.delete()
                    chat.kick_member(user.id)
                    bot.sendMessage(
                        chat.id,
                        "{} banned because using '{}' which in blacklist stickers"
                        .format(mention_markdown(user.id, user.first_name),
                                trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 6:
                    message.delete()
                    bantime = extract_time(message, value)
                    chat.kick_member(user.id, until_date=bantime)
                    bot.sendMessage(
                        chat.id,
                        "{} banned for {} because using '{}' which in blacklist stickers"
                        .format(mention_markdown(user.id, user.first_name),
                                value, trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 7:
                    message.delete()
                    mutetime = extract_time(message, value)
                    bot.restrict_chat_member(chat.id,
                                             user.id,
                                             until_date=mutetime,
                                             can_send_messages=False)
                    bot.sendMessage(
                        chat.id,
                        "{} muted for {} because using '{}' which in blacklist stickers"
                        .format(mention_markdown(user.id, user.first_name),
                                value, trigger),
                        parse_mode="markdown")
                    return
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception("Error while deleting blacklist message.")
                break
Example #8
0
def _mirror(bot, update, isZip=False, extract=False):
    mesg = update.message.text.split("\n")
    message_args = mesg[0].split(" ")
    name_args = mesg[0].split("|")
    try:
        link = message_args[1]
        print(link)
        if link.startswith("|") or link.startswith("pswd: "):
            link = ""
    except IndexError:
        link = ""
    try:
        name = name_args[1]
        name = name.strip()
        if name.startswith("pswd: "):
            name = ""
    except IndexError:
        name = ""
    try:
        ussr = urllib.parse.quote(mesg[1], safe="")
        pssw = urllib.parse.quote(mesg[2], safe="")
    except:
        ussr = ""
        pssw = ""
    if ussr != "" and pssw != "":
        link = link.split("://", maxsplit=1)
        link = f"{link[0]}://{ussr}:{pssw}@{link[1]}"
    pswd = re.search("(?<=pswd: )(.*)", update.message.text)
    if pswd is not None:
        pswd = pswd.groups()
        pswd = " ".join(pswd)
    LOGGER.info(link)
    link = link.strip()
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        file = None
        tag = reply_to.from_user.username
        media_array = [reply_to.document, reply_to.video, reply_to.audio]
        for i in media_array:
            if i is not None:
                file = i
                break

        if (not bot_utils.is_url(link) and not bot_utils.is_magnet(link)
                or len(link) == 0) and file is not None:
            if file.mime_type != "application/x-bittorrent":
                listener = MirrorListener(bot, update, pswd, isZip, tag,
                                          extract)
                tg_downloader = TelegramDownloadHelper(listener)
                tg_downloader.add_download(reply_to,
                                           f"{DOWNLOAD_DIR}{listener.uid}/",
                                           name)
                sendStatusMessage(update, bot)
                if len(Interval) == 0:
                    Interval.append(
                        setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                                    update_all_messages))
                return
            else:
                link = file.get_file().file_path
    else:
        tag = None
    if not bot_utils.is_url(link) and not bot_utils.is_magnet(link):
        sendMessage("No download source provided", bot, update)
        return

    try:
        link = direct_link_generator(link)
    except DirectDownloadLinkException as e:
        LOGGER.info(f"{link}: {e}")
    listener = MirrorListener(bot, update, pswd, isZip, tag, extract)
    if bot_utils.is_gdrive_link(link):
        if not isZip and not extract:
            sendMessage(f"Use /{BotCommands.CloneCommand} To Copy File/Folder",
                        bot, update)
            return
        res, size, name = gdriveTools.GoogleDriveHelper().clonehelper(link)
        if res != "":
            sendMessage(res, bot, update)
            return
        LOGGER.info(f"Download Name : {name}")
        drive = gdriveTools.GoogleDriveHelper(name, listener)
        gid = "".join(random.SystemRandom().choices(string.ascii_letters +
                                                    string.digits,
                                                    k=12))
        download_status = DownloadStatus(drive, size, listener, gid)
        with download_dict_lock:
            download_dict[listener.uid] = download_status
        if len(Interval) == 0:
            Interval.append(
                setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                            update_all_messages))
        sendStatusMessage(update, bot)
        drive.download(link)

    elif bot_utils.is_mega_link(
            link) and MEGA_KEY is not None and not BLOCK_MEGA_LINKS:
        mega_dl = MegaDownloader(listener)
        mega_dl.add_download(link, f"{DOWNLOAD_DIR}{listener.uid}/")
        sendStatusMessage(update, bot)
    elif bot_utils.is_mega_link(link) and BLOCK_MEGA_LINKS:
        sendMessage("Mega links are blocked. Dont try to mirror mega links.",
                    bot, update)
    else:
        ariaDlManager.add_download(link, f"{DOWNLOAD_DIR}{listener.uid}/",
                                   listener, name)
        sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Example #9
0
    def onDownloadComplete(self):
        with download_dict_lock:
            LOGGER.info(
                f"Download completed: {download_dict[self.uid].name()}")
            download = download_dict[self.uid]
            name = download.name()
            size = download.size_raw()
            if name is None:  # when pyrogram's media.file_name is of NoneType
                name = os.listdir(f"{DOWNLOAD_DIR}{self.uid}")[0]
            m_path = f"{DOWNLOAD_DIR}{self.uid}/{name}"
        if self.isZip:
            download.is_archiving = True
            try:
                with download_dict_lock:
                    download_dict[self.uid] = ZipStatus(name, m_path, size)
                path = fs_utils.zip(name, m_path)
            except FileNotFoundError:
                LOGGER.info("File to archive not found!")
                self.onUploadError("Internal error occurred!!")
                return
        elif self.extract:
            download.is_extracting = True
            try:
                path = fs_utils.get_base_name(m_path)
                LOGGER.info(f"Extracting : {name} ")
                with download_dict_lock:
                    download_dict[self.uid] = ExtractStatus(name, m_path, size)
                pswd = self.pswd
                if pswd is not None:
                    archive_result = subprocess.run(["pextract", m_path, pswd])
                else:
                    archive_result = subprocess.run(["extract", m_path])
                if archive_result.returncode == 0:
                    threading.Thread(target=os.remove, args=(m_path, )).start()
                    LOGGER.info(f"Deleting archive : {m_path}")
                else:
                    LOGGER.warning(
                        "Unable to extract archive! Uploading anyway")
                    path = f"{DOWNLOAD_DIR}{self.uid}/{name}"
                LOGGER.info(f"got path : {path}")

            except NotSupportedExtractionArchive:
                LOGGER.info("Not any valid archive, uploading file as it is.")
                path = f"{DOWNLOAD_DIR}{self.uid}/{name}"
        else:
            path = f"{DOWNLOAD_DIR}{self.uid}/{name}"
        up_name = pathlib.PurePath(path).name
        if up_name == "None":
            up_name = "".join(os.listdir(f"{DOWNLOAD_DIR}{self.uid}/"))
        up_path = f"{DOWNLOAD_DIR}{self.uid}/{up_name}"
        LOGGER.info(f"Upload Name : {up_name}")
        drive = gdriveTools.GoogleDriveHelper(up_name, self)
        size = fs_utils.get_path_size(up_path)
        upload_status = UploadStatus(drive, size, self)
        with download_dict_lock:
            download_dict[self.uid] = upload_status
        update_all_messages()
        drive.upload(up_name)
Example #10
0
 def add_download(mega_link: str, path: str, listener):
     if MEGA_API_KEY is None:
         raise MegaDownloaderException(
             'Mega API KEY not provided! Cannot mirror Mega links')
     executor = AsyncExecutor()
     api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
     global listeners
     mega_listener = MegaAppListener(executor.continue_event, listener)
     listeners.append(mega_listener)
     api.addListener(mega_listener)
     if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
         executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
     link_type = get_mega_link_type(mega_link)
     if link_type == "file":
         LOGGER.info(
             "File. If your download didn't start, then check your link if it's available to download"
         )
         executor.do(api.getPublicNode, (mega_link, ))
         node = mega_listener.public_node
     else:
         LOGGER.info(
             "Folder. If your download didn't start, then check your link if it's available to download"
         )
         folder_api = MegaApi(MEGA_API_KEY, None, None, 'TgBot')
         folder_api.addListener(mega_listener)
         executor.do(folder_api.loginToFolder, (mega_link, ))
         node = folder_api.authorizeNode(mega_listener.node)
     if mega_listener.error is not None:
         return listener.onDownloadError(str(mega_listener.error))
     if STOP_DUPLICATE_MEGA:
         LOGGER.info(f'Checking File/Folder if already in Drive')
         mname = node.getName()
         if listener.isTar:
             mname = mname + ".tar"
         if listener.extract:
             smsg = None
         else:
             gd = GoogleDriveHelper()
             smsg, button = gd.drive_list(mname)
         if smsg:
             msg1 = "File/Folder is already available in Drive.\nHere are the search results:"
             sendMarkup(msg1, listener.bot, listener.update, button)
             return
     if MEGA_LIMIT is not None or TAR_UNZIP_LIMIT is not None:
         limit = None
         LOGGER.info(f'Checking File/Folder Size')
         if TAR_UNZIP_LIMIT is not None and (listener.isTar
                                             or listener.extract):
             limit = TAR_UNZIP_LIMIT
             msg3 = f'Failed, Tar/Unzip limit is {TAR_UNZIP_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
         if MEGA_LIMIT is not None and limit is None:
             limit = MEGA_LIMIT
             msg3 = f'Failed, Mega limit is {MEGA_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
         if limit is not None:
             limit = limit.split(' ', maxsplit=1)
             limitint = int(limit[0])
             if 'G' in limit[1] or 'g' in limit[1]:
                 if api.getSize(node) > limitint * 1024**3:
                     sendMessage(msg3, listener.bot, listener.update)
                     return
             elif 'T' in limit[1] or 't' in limit[1]:
                 if api.getSize(node) > limitint * 1024**4:
                     sendMessage(msg3, listener.bot, listener.update)
                     return
     with download_dict_lock:
         download_dict[listener.uid] = MegaDownloadStatus(
             mega_listener, listener)
     os.makedirs(path)
     gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                 string.digits,
                                                 k=8))
     mega_listener.setValues(node.getName(), api.getSize(node), gid)
     sendStatusMessage(listener.update, listener.bot)
     executor.do(api.startDownload, (node, path))
Example #11
0
def cloneNode(update, context):
    args = update.message.text.split(" ", maxsplit=1)
    if len(args) > 1:
        link = args[1]
        gd = gdriveTools.GoogleDriveHelper()
        res, clonesize, name, files = gd.clonehelper(link)
        if res != "":
            sendMessage(res, context.bot, update)
            return
        if STOP_DUPLICATE_CLONE:
            LOGGER.info(f"Checking File/Folder if already in Drive...")
            smsg, button = gd.drive_list(name)
            if smsg:
                msg3 = "File/Folder is already available in Drive.\nHere are the search results:"
                sendMarkup(msg3, context.bot, update, button)
                return
        if CLONE_LIMIT is not None:
            LOGGER.info(f"Checking File/Folder Size...")
            limit = CLONE_LIMIT
            limit = limit.split(' ', maxsplit=1)
            limitint = int(limit[0])
            msg2 = f'Failed, Clone limit is {CLONE_LIMIT}.\nYour File/Folder size is {get_readable_file_size(clonesize)}.'
            if 'G' in limit[1] or 'g' in limit[1]:
                if clonesize > limitint * 1024**3:
                    sendMessage(msg2, context.bot, update)
                    return
            elif 'T' in limit[1] or 't' in limit[1]:
                if clonesize > limitint * 1024**4:
                    sendMessage(msg2, context.bot, update)
                    return              
        if files < 15:
            msg = sendMessage(f"Cloning: <code>{link}</code>", context.bot, update)
            result, button = gd.clone(link)
            deleteMessage(context.bot, msg)
        else:
            drive = gdriveTools.GoogleDriveHelper(name)
            gid = ''.join(random.SystemRandom().choices(string.ascii_letters + string.digits, k=12))
            clone_status = CloneStatus(drive, clonesize, update, gid)
            with download_dict_lock:
                download_dict[update.message.message_id] = clone_status
            if len(Interval) == 0:
                Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
            sendStatusMessage(update, context.bot)
            result, button = drive.clone(link)
        if update.message.from_user.username:
            uname = f'@{update.message.from_user.username}'
        else:
            uname = f'<a href="tg://user?id={update.message.from_user.id}">{update.message.from_user.first_name}</a>'
        if uname is not None:
            cc = f'\n\ncc: {uname}'
            men = f'{uname} '
        if button == "cancelled":
            sendMessage(men + result, context.bot, update)
        elif button == "":
            sendMessage(men + result, context.bot, update)
        else:
            sendMarkup(result + cc, context.bot, update, button)
        try:
            with download_dict_lock:
                del download_dict[update.message.message_id]
                count = len(download_dict)
            if count == 0:
                Interval[0].cancel()
                del Interval[0]
                delete_all_messages()
            else:
                update_all_messages()
        except IndexError:
            pass
    else:
        sendMessage('Provide G-Drive Shareable Link to Clone.', context.bot, update)
Example #12
0
def tar(orig_path: str):
    path = pathlib.PurePath(orig_path)
    base = path.name
    root = pathlib.Path(path.parent.as_posix()).absolute().as_posix()
    LOGGER.info(f'Tar: orig_path: {orig_path}, base: {base}, root: {root}')
    return shutil.make_archive(orig_path, 'tar', root, base)
Example #13
0
def _emptyTrash(client, message):
    user_id = message.from_user.id
    LOGGER.info(f'EmptyTrash: {user_id}')
    msg = GoogleDrive(user_id).emptyTrash()
    message.reply_text(msg, quote=True)
Example #14
0
def setup(bot):
    bot.add_cog(RSRole(bot))
    LOGGER.info('RS Role System loaded')
 def onTransferStart(self, api: MegaApi, transfer: MegaTransfer):
     LOGGER.info(f"Transfer Started: {transfer.getFileName()}")
Example #16
0
 def cancel_download(self):
     LOGGER.info(f"Cancelling download on user request: {self.gid}")
     self.__mega_client.cancelDl(self.gid)
Example #17
0
def _restart(client, message):
  shutil.rmtree(DOWNLOAD_DIRECTORY)
  LOGGER.info('Deleted DOWNLOAD_DIRECTORY successfully.')
  message.reply_text('**♻️Restarted Successfully !**', quote=True)
  LOGGER.info(f'{message.from_user.id}: Restarting...')
  execl(executable, executable, "-m", "bot")
Example #18
0
def _mirror(bot, update, isTar=False, extract=False):
    mesg = update.message.text.split('\n')
    message_args = mesg[0].split(' ')
    name_args = mesg[0].split('|')
    try:
        link = message_args[1]
        print(link)
        if link.startswith("|") or link.startswith("pswd: "):
            link = ''
    except IndexError:
        link = ''
    try:
        name = name_args[1]
        name = name.strip()
        if name.startswith("pswd: "):
            name = ''
    except IndexError:
        name = ''
    try:
        ussr = urllib.parse.quote(mesg[1], safe='')
        pssw = urllib.parse.quote(mesg[2], safe='')
    except:
        ussr = ''
        pssw = ''
    if ussr != '' and pssw != '':
        link = link.split("://", maxsplit=1)
        link = f'{link[0]}://{ussr}:{pssw}@{link[1]}'
    pswd = re.search('(?<=pswd: )(.*)', update.message.text)
    if pswd is not None:
        pswd = pswd.groups()
        pswd = " ".join(pswd)
    LOGGER.info(link)
    link = link.strip()
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        file = None
        tag = reply_to.from_user.username
        media_array = [reply_to.document, reply_to.video, reply_to.audio]
        for i in media_array:
            if i is not None:
                file = i
                break

        if not bot_utils.is_url(link) and not bot_utils.is_magnet(link) or len(
                link) == 0:
            if file is not None:
                if file.mime_type != "application/x-bittorrent":
                    listener = MirrorListener(bot, update, pswd, isTar, tag,
                                              extract)
                    tg_downloader = TelegramDownloadHelper(listener)
                    tg_downloader.add_download(
                        reply_to, f'{DOWNLOAD_DIR}{listener.uid}/', name)
                    sendStatusMessage(update, bot)
                    if len(Interval) == 0:
                        Interval.append(
                            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                                        update_all_messages))
                    return
                else:
                    link = file.get_file().file_path
    else:
        tag = None
    if not bot_utils.is_url(link) and not bot_utils.is_magnet(link):
        sendMessage('No download source provided', bot, update)
        return

    try:
        link = direct_link_generator(link)
    except DirectDownloadLinkException as e:
        LOGGER.info(f'{link}: {e}')
    listener = MirrorListener(bot, update, pswd, isTar, tag, extract)
    if bot_utils.is_mega_link(
            link) and MEGA_KEY is not None and not BLOCK_MEGA_LINKS:
        mega_dl = MegaDownloader(listener)
        mega_dl.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/')
        sendStatusMessage(update, bot)
    elif bot_utils.is_mega_link(link) and BLOCK_MEGA_LINKS:
        sendMessage("Mega links are blocked. Dont try to mirror mega links.",
                    bot, update)
    else:
        ariaDlManager.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/',
                                   listener, name)
        sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Example #19
0
def extract_unt_fedban(message: Message,
                       args: List[str]) -> (Optional[int], Optional[str]):
    prev_message = message.reply_to_message
    split_text = message.text.split(None, 1)

    if len(split_text) < 2:
        return id_from_reply(message)  # only option possible

    text_to_parse = split_text[1]

    text = ""

    entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
    if len(entities) > 0:
        ent = entities[0]
    else:
        ent = None

    # if entity offset matches (command end/text start) then all good
    if entities and ent and ent.offset == len(
            message.text) - len(text_to_parse):
        ent = entities[0]
        user_id = ent.user.id
        text = message.text[ent.offset + ent.length:]

    elif len(args) >= 1 and args[0][0] == '@':
        user = args[0]
        user_id = get_user_id(user)
        if not user_id and not isinstance(user_id, int):
            message.reply_text(
                "Saya tidak memiliki pengguna di db saya. Anda akan dapat berinteraksi dengan mereka jika "
                "Anda membalas pesan orang itu, atau meneruskan salah satu dari pesan pengguna itu."
            )
            return None, None

        else:
            user_id = user_id
            res = message.text.split(None, 2)
            if len(res) >= 3:
                text = res[2]

    elif len(args) >= 1 and args[0].isdigit():
        user_id = int(args[0])
        res = message.text.split(None, 2)
        if len(res) >= 3:
            text = res[2]

    elif prev_message:
        user_id, text = id_from_reply(message)

    else:
        return None, None

    try:
        message.bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message in ("User_id_invalid",
                            "Chat not found") and not isinstance(user_id, int):
            message.reply_text(
                "Saya sepertinya tidak pernah berinteraksi dengan pengguna ini "
                "sebelumnya - silakan meneruskan pesan dari mereka untuk memberi saya kontrol! "
                "(Seperti boneka voodoo, saya butuh sepotong untuk bisa"
                "untuk menjalankan perintah tertentu...)")
            return None, None
        elif excp.message != "Chat not found":
            LOGGER.exception("Exception %s on user %s", excp.message, user_id)
            return None, None
        elif not isinstance(user_id, int):
            return None, None

    return user_id, text
Example #20
0
def cloneNode(update, context):
    args = update.message.text.split(" ", maxsplit=1)
    reply_to = update.message.reply_to_message
    link = ''
    if len(args) > 1:
        link = args[1]
        if update.message.from_user.username:
            tag = f"@{update.message.from_user.username}"
        else:
            tag = update.message.from_user.mention_html(
                update.message.from_user.first_name)
    if reply_to is not None:
        if len(link) == 0:
            link = reply_to.text
        if reply_to.from_user.username:
            tag = f"@{reply_to.from_user.username}"
        else:
            tag = reply_to.from_user.mention_html(
                reply_to.from_user.first_name)
    is_gdtot = is_gdtot_link(link)
    if is_gdtot:
        try:
            msg = sendMessage(f"Processing: <code>{link}</code>", context.bot,
                              update)
            link = gdtot(link)
            deleteMessage(context.bot, msg)
        except DirectDownloadLinkException as e:
            deleteMessage(context.bot, msg)
            return sendMessage(str(e), context.bot, update)
    if is_gdrive_link(link):
        gd = GoogleDriveHelper()
        res, size, name, files = gd.helper(link)
        if res != "":
            return sendMessage(res, context.bot, update)
        if STOP_DUPLICATE:
            LOGGER.info('Checking File/Folder if already in Drive...')
            smsg, button = gd.drive_list(name, True, True)
            if smsg:
                msg3 = "File/Folder is already available in Drive.\nHere are the search results:"
                return sendMarkup(msg3, context.bot, update, button)
        if CLONE_LIMIT is not None:
            LOGGER.info('Checking File/Folder Size...')
            if size > CLONE_LIMIT * 1024**3:
                msg2 = f'Failed, Clone limit is {CLONE_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(size)}.'
                return sendMessage(msg2, context.bot, update)
        if files <= 20:
            msg = sendMessage(f"Cloning: <code>{link}</code>", context.bot,
                              update)
            result, button = gd.clone(link)
            deleteMessage(context.bot, msg)
        else:
            drive = GoogleDriveHelper(name)
            gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                        string.digits,
                                                        k=12))
            clone_status = CloneStatus(drive, size, update, gid)
            with download_dict_lock:
                download_dict[update.message.message_id] = clone_status
            sendStatusMessage(update, context.bot)
            result, button = drive.clone(link)
            with download_dict_lock:
                del download_dict[update.message.message_id]
                count = len(download_dict)
            try:
                if count == 0:
                    Interval[0].cancel()
                    del Interval[0]
                    delete_all_messages()
                else:
                    update_all_messages()
            except IndexError:
                pass
        cc = f'\n\n<b>cc: </b>{tag}'
        if button in ["cancelled", ""]:
            sendMessage(f"{tag} {result}", context.bot, update)
        else:
            sendMarkup(result + cc, context.bot, update, button)
        if is_gdtot:
            gd.deletefile(link)
    else:
        sendMessage(
            'Send Gdrive or gdtot link along with command or by replying to the link by command',
            context.bot, update)
Example #21
0
def clean_download(path: str):
    if os.path.exists(path):
        LOGGER.info(f"Cleaning download: {path}")
        shutil.rmtree(path)
Example #22
0
 def upload(self, file_name: str):
     self.__listener.onUploadStarted()
     file_dir = f"{DOWNLOAD_DIR}{self.__listener.message.message_id}"
     file_path = f"{file_dir}/{file_name}"
     LOGGER.info("Uploading File: " + file_path)
     self.start_time = time.time()
     self.updater = setInterval(self.update_interval,
                                self._on_upload_progress)
     if os.path.isfile(file_path):
         try:
             mime_type = get_mime_type(file_path)
             link = self.upload_file(file_path, file_name, mime_type,
                                     parent_id)
             if link is None:
                 raise Exception('Upload has been manually cancelled')
             LOGGER.info("Uploaded To G-Drive: " + file_path)
         except Exception as e:
             LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}")
             LOGGER.error(e.last_attempt.exception())
             self.__listener.onUploadError(e)
             return
         finally:
             self.updater.cancel()
     else:
         try:
             dir_id = self.create_directory(
                 os.path.basename(os.path.abspath(file_name)), parent_id)
             result = self.upload_dir(file_path, dir_id)
             if result is None:
                 raise Exception('Upload has been manually cancelled!')
             LOGGER.info("Uploaded To G-Drive: " + file_name)
             link = f"https://drive.google.com/folderview?id={dir_id}"
         except Exception as e:
             LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}")
             LOGGER.error(e.last_attempt.exception())
             self.__listener.onUploadError(e)
             return
         finally:
             self.updater.cancel()
     LOGGER.info(download_dict)
     self.__listener.onUploadComplete(link)
     LOGGER.info("Deleting downloaded file/folder..")
     return link
Example #23
0
from bot import LOGGER


def __list_all_modules():
    from os.path import dirname, basename, isfile
    import glob
    # This generates a list of modules in this folder
    # for the * in __main__ to work.
    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [
        basename(f)[:-3] for f in mod_paths
        if (isfile(f) and f.endswith(".py") and not f.endswith('__init__.py'))
    ]
    return all_modules


ALL_MODULES = sorted(__list_all_modules())
LOGGER(__name__).info("Modules to load: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]
Example #24
0
def log_input(update):
    user = update.effective_user.id
    chat = update.effective_chat.id
    LOGGER.info(
        f"IN: {update.effective_message.text} (user={user}, chat={chat})")
Example #25
0
    def onDownloadComplete(self):
        with download_dict_lock:
            LOGGER.info(
                f"Download completed: {download_dict[self.uid].name()}")
            download = download_dict[self.uid]
            name = download.name()
            size = download.size_raw()
            m_path = f'{DOWNLOAD_DIR}{self.uid}/{download.name()}'
        if self.isTar:
            download.is_archiving = True
            try:
                with download_dict_lock:
                    download_dict[self.uid] = TarStatus(name, m_path, size)
                path = fs_utils.tar(m_path)
            except FileNotFoundError:
                LOGGER.info('File to archive not found!')
                self.onUploadError('Internal error occurred!!')
                return
        elif self.extract:
            download.is_extracting = True
            try:
                path = fs_utils.get_base_name(m_path)
                LOGGER.info(f"Extracting : {name} ")
                with download_dict_lock:
                    download_dict[self.uid] = ExtractStatus(name, m_path, size)
                archive_result = subprocess.run(["extract", m_path])
                if archive_result.returncode == 0:
                    threading.Thread(target=os.remove, args=(m_path, )).start()
                    LOGGER.info(f"Deleting archive : {m_path}")
                else:
                    LOGGER.warning(
                        'Unable to extract archive! Uploading anyway')
                    path = f'{DOWNLOAD_DIR}{self.uid}/{name}'
                LOGGER.info(f'got path : {path}')

            except NotSupportedExtractionArchive:
                LOGGER.info("Not any valid archive, uploading file as it is.")
                path = f'{DOWNLOAD_DIR}{self.uid}/{name}'
        else:
            path = f'{DOWNLOAD_DIR}{self.uid}/{name}'
        up_name = pathlib.PurePath(path).name
        LOGGER.info(f"Upload Name : {up_name}")
        drive = gdriveTools.GoogleDriveHelper(up_name, self)
        if size == 0:
            size = fs_utils.get_path_size(m_path)
        upload_status = UploadStatus(drive, size, self)
        with download_dict_lock:
            download_dict[self.uid] = upload_status
        update_all_messages()
        drive.upload(up_name)
Example #26
0
 def upload(self, file_name: str):
     _list = get_download_status_list()
     index = get_download_index(_list, get_download(self.__listener.message.message_id).gid)
     self.__listener.onUploadStarted(_list, index)
     file_dir = f"{DOWNLOAD_DIR}{self.__listener.message.message_id}"
     file_path = f"{file_dir}/{file_name}"
     LOGGER.info("Uploading File: " + file_name)
     self.start_time = time.time()
     threading.Thread(target=self._on_upload_progress).start()
     if os.path.isfile(file_path):
         try:
             mime_type = get_mime_type(file_path)
             link = self.upload_file(file_path, file_name, mime_type, parent_id)
             if link is None:
                 raise Exception('Upload has been manually cancelled')
             LOGGER.info("Uploaded To G-Drive: " + file_path)
         except Exception as e:
             LOGGER.error(str(e))
             e_str = str(e).replace('<', '')
             e_str = e_str.replace('>', '')
             self.__listener.onUploadError(e_str, _list, index)
             return
         finally:
             self.is_uploading = False
     else:
         try:
             dir_id = self.create_directory(os.path.basename(os.path.abspath(file_name)), parent_id)
             result = self.upload_dir(file_path, dir_id)
             if result is None:
                 raise Exception('Upload has been manually cancelled!')
             LOGGER.info("Uploaded To G-Drive: " + file_name)
             link = f"https://drive.google.com/folderview?id={dir_id}"
         except Exception as e:
             LOGGER.error(str(e))
             e_str = str(e).replace('<', '')
             e_str = e_str.replace('>', '')
             self.__listener.onUploadError(e_str, _list, index)
             return
         finally:
             self.is_uploading = False
     LOGGER.info(download_dict)
     self.__listener.onUploadComplete(link, _list, index)
     LOGGER.info("Deleting downloaded file/folder..")
     return link
Example #27
0
def settings_button(bot: Bot, update: Update):
    query = update.callback_query
    user = update.effective_user
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = bot.get_chat(chat_id)
            text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title),
                                                                                     CHAT_SETTINGS[
                                                                                         module].__mod_name__) + \
                   CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id)
            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         [[InlineKeyboardButton(text="Back",
                                                                callback_data="stngs_back({})".format(chat_id))]]))

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text("Hi there! There are quite a few settings for {} - go ahead and pick what "
                                     "you're interested in.".format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs",
                                                          chat=chat_id)))

        elif next_match:
            chat_id = next_match.group(1)
            next_page = int(next_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text("Hi there! There are quite a few settings for {} - go ahead and pick what "
                                     "you're interested in.".format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs",
                                                          chat=chat_id)))

        elif back_match:
            chat_id = back_match.group(1)
            chat = bot.get_chat(chat_id)
            query.message.reply_text(text="Hi there! There are quite a few settings for {} - go ahead and pick what "
                                          "you're interested in.".format(escape_markdown(chat.title)),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(paginate_modules(0, CHAT_SETTINGS, "stngs",
                                                                                        chat=chat_id)))

        # ensure no spinny white circle
        bot.answer_callback_query(query.id)
        query.message.delete()
    except BadRequest as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            LOGGER.exception("Exception in settings buttons. %s", str(query.data))
 def onRequestStart(self, api, request):
     LOGGER.info('Request start ({})'.format(request))
Example #29
0
 def cancel_download(self):
     LOGGER.info(f'Cancelling download on user request: {self.gid}')
     self.__is_cancelled = True
Example #30
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        # If we're replying to a message, reply to that message (unless it's an error)
        if message.reply_to_message:
            reply_id = message.reply_to_message.message_id
        else:
            reply_id = message.message_id

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id, from_chat_id=MESSAGE_DUMP, message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text("This message seems to have been lost - I'll remove it "
                                           "from your notes list.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(chat_id=chat_id, from_chat_id=chat_id, message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text("Looks like the original sender of this note has deleted "
                                           "their message - sorry! Get your bot admin to start using a "
                                           "message dump to avoid this. I'll remove this note from "
                                           "your saved notes.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(chat_id, text, reply_to_message_id=reply_id,
                                     parse_mode=parseMode, disable_web_page_preview=True,
                                     reply_markup=keyboard)
                else:
                    ENUM_FUNC_MAP[note.msgtype](chat_id, note.file, caption=text, reply_to_message_id=reply_id,
                                                parse_mode=parseMode, disable_web_page_preview=True,
                                                reply_markup=keyboard)

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text("Looks like you tried to mention someone I've never seen before. If you really "
                                       "want to mention them, forward one of their messages to me, and I'll be able "
                                       "to tag them!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text("This note was an incorrectly imported file from another bot - I can't use "
                                       "it. If you really need it, you'll have to save it again. In "
                                       "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text("This note could not be sent, as it is incorrectly formatted. Ask in "
                                       f"{SUPPORT_CHAT} if you can't figure out why!")
                    LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("This note doesn't exist")