示例#1
0
def __list_all_modules():
    from os.path import dirname, basename, isfile
    import glob

    # This generates a list of helper_funcs 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")
    ]

    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.")
                sys.exit(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
示例#2
0
async def shutdown(event: NewMessage.Event) -> None:
    """Shutdown the userbot script."""
    await event.answer("`Disconnecting the client and exiting. Ciao!`")
    client.reconnect = False
    print()
    LOGGER.info("Disconnecting the client and exiting the main script.")
    await client.disconnect()
示例#3
0
async def shutdown(update):
    await update.edit("`Shutting down...`")
    LOGGER.info("Bot shutting down...")
    try:
        await update.client.disconnect()
    except:
        pass
示例#4
0
async def git_repo(event: NewMessage.Event) -> None:
    """Get the repo url."""
    try:
        repo = git.Repo('.')
        remote_url = repo.remote().url.replace(".git", '/')
        if remote_url[-1] != '/':
            remote_url = remote_url + '/'
        repo.__del__()
    except Exception as e:
        LOGGER.info("Couldnt fetch the repo link.")
        LOGGER.debug(e)
        remote_url = "https://github.com/kandnub/TG-UserBot/"
    await event.answer(f"[TG-UserBot]({remote_url})")
示例#5
0
async def git_repo(event: NewMessage.Event) -> None:
    """Get the repo url."""
    try:
        repo = git.Repo('.')
        remote_url = repo.remote().url.replace(".git", '/')
        if remote_url[-1] != '/':
            remote_url = remote_url + '/'
        repo.__del__()
    except Exception as e:
        LOGGER.info("Couldnt fetch the repo link.")
        LOGGER.debug(e)
        remote_url = "https://github.com/AvinashReddy3108/PaperplaneRemix.git"
    await event.answer(
        f"Click [here]({remote_url}) to check out my userbot's source code.")
示例#6
0
async def download(update):
    global is_downloading
    path = "/tmp/{}".format(os.getpid())
    if not os.path.exists(path):
        os.mkdir(path)
    args = get_args(update)
    if len(args) < 1:
        await update.edit("`Usage: .spotdl <link>`")
        return
    link = args[0]
    if not "track" in link:
        await update.edit("`Invalid link. Please note that playlist links won't work!`")
        return
    if is_downloading:
        await update.edit("`Already downloading a song, please wait.`")
        return
    else:
        is_downloading = True
        try:
            await update.edit("`Downloading song, please wait...`")
            LOGGER.info("Starting download of " + link + ".")
            fetch = await create_subprocess_exec(
                "spotdl",
                "--ignore-ffmpeg-version", # TODO: Change this - It is required in order to run on Leap 15.2 Arm
                link,
                "--output",
                path,
                stdout=PIPE,
                stderr=PIPE,
            )

            stdout, stderr = await fetch.communicate()
            result = str(stdout.decode().strip()) \
                + str(stderr.decode().strip())
            
            directory = os.fsencode(path)
            for file in os.listdir(directory):
                filename = os.fsdecode(file)
                if filename.endswith(".mp3"):
                    await update.edit("`Sucessfully downloaded " + filename.replace(".mp3", "") + "`")
                    LOGGER.info("Serving " + filename.replace(".mp3", "") + "...")
                    await update.client.send_file(update.chat_id, path + "/" + filename)
                    LOGGER.info("Serving " + filename.replace(".mp3", "") + " - Done.")
                    LOGGER.debug("Deleting old files...")
                    os.remove(path + "/" + filename)
                    LOGGER.debug("Done deleting old files.")
                
        except FileNotFoundError:
            await update.edit("`Spotify-downloader is not installed.`")
        is_downloading = False
示例#7
0
                sys.exit(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"]

pattern = ""


def register(**args):
    """ Register a new event. """
    global pattern
    pattern = args.get('pattern', None)
    disable_edited = args.get('disable_edited', False)
    ignore_unsafe = args.get('ignore_unsafe', False)
    unsafe_pattern = r'^[^/!#@\$A-Za-z]'
    group_only = args.get('group_only', False)
    disable_errors = args.get('disable_errors', False)
    insecure = args.get('insecure', False)
示例#8
0
async def shutdown(event):
    """Shutdown userbot."""
    await event.edit("`Disconnecting the client and exiting. Ciao!`")
    print()
    LOGGER.info("Disconnecting the client and exiting the main script.")
    await event.client.disconnect()
示例#9
0
async def progress(current, total):
    """ Logs the upload progress """
    LOGGER.info(
        f"Uploaded {current} of {total}\nCompleted: {(current / total) * 100:.2f}%"
    )
示例#10
0
def get_text():
    return "test"

@register(outgoing=True, pattern="^.help")
async def help(update):
    args = get_args(update)
    if len(args) >= 1:
        module = ""
        for arg in args:
            if arg == ".help":
                pass
            else:
                if module == "":
                    module = arg.lower()
                else:
                    module = module + " " + arg.lower()
        if module in HELPS:
            await update.edit(f"Below is the help for the `{module}` module.\n\n" + HELPABLE[module].__help__)
        else: await update.edit("I can not find that module! Please check for typos and make sure the module is loaded.")
    else:
        string = ""
        for i in HELPABLE.values():
            string += f"`{str(i.__mod_name__)}`, "
        string = string[:-2]
        await update.edit("Please specify which module you want help for!\n\n"
                         f"{string}")
    
LOGGER.info("Bot is alive! Test it by typing .alive on any chat.")
bot.run_until_disconnected()