コード例 #1
0
    else:
        dl.download().cancel_download()
    sleep(1)  # Wait a Second For Aria2 To free Resources.
    clean_download(f'{DOWNLOAD_DIR}{mirror_message.message_id}/')


def cancel_all(update, context):
    with download_dict_lock:
        count = 0
        for dlDetails in list(download_dict.values()):
            if dlDetails.status() == MirrorStatus.STATUS_DOWNLOADING \
                    or dlDetails.status() == MirrorStatus.STATUS_WAITING:
                dlDetails.download().cancel_download()
                count += 1
    delete_all_messages()
    sendMessage(f'Cancelled {count} downloads!', context.bot, update)


cancel_mirror_handler = CommandHandler(
    BotCommands.CancelMirror,
    cancel_mirror,
    filters=(CustomFilters.authorized_chat | CustomFilters.authorized_user)
    & CustomFilters.mirror_owner_filter,
    run_async=True)
cancel_all_handler = CommandHandler(BotCommands.CancelAllCommand,
                                    cancel_all,
                                    filters=CustomFilters.owner_filter,
                                    run_async=True)
dispatcher.add_handler(cancel_all_handler)
dispatcher.add_handler(cancel_mirror_handler)
コード例 #2
0
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}', qual,
                           name)).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))


def watchTar(update, context):
    _watch(context.bot, update, True)


def watch(update, context):
    _watch(context.bot, update)


mirror_handler = CommandHandler(BotCommands.WatchCommand,
                                watch,
                                filters=CustomFilters.authorized_chat
                                | CustomFilters.authorized_user,
                                run_async=True)
tar_mirror_handler = CommandHandler(BotCommands.TarWatchCommand,
                                    watchTar,
                                    filters=CustomFilters.authorized_chat
                                    | CustomFilters.authorized_user,
                                    run_async=True)
dispatcher.add_handler(mirror_handler)
dispatcher.add_handler(tar_mirror_handler)
コード例 #3
0
            if download.status() == MirrorStatus.STATUS_DOWNLOADING:
                if 'KiB/s' in speedy:
                    dlspeed_bytes += float(speedy.split('K')[0]) * 1024
                elif 'MiB/s' in speedy:
                    dlspeed_bytes += float(speedy.split('M')[0]) * 1048576
            if download.status() == MirrorStatus.STATUS_UPLOADING:
                if 'KB/s' in speedy:
                    uldl_bytes += float(speedy.split('K')[0]) * 1024
                elif 'MB/s' in speedy:
                    uldl_bytes += float(speedy.split('M')[0]) * 1048576
        dlspeed = get_readable_file_size(dlspeed_bytes)
        ulspeed = get_readable_file_size(uldl_bytes)
        progress += f"\n<b>USED:</b> {used} | <b>FREE:</b> {free}\n<b>DL:</b> {dlspeed}ps 🔻 | <b>UL:</b> {ulspeed}ps 🔺\n"
    with status_reply_dict_lock:
        if msg.message.chat.id in list(status_reply_dict.keys()):
            try:
                message = status_reply_dict[msg.message.chat.id]
                deleteMessage(bot, message)
                del status_reply_dict[msg.message.chat.id]
            except Exception as e:
                LOGGER.error(str(e))
                del status_reply_dict[msg.message.chat.id]
        message = sendMessage(progress, bot, msg)
        status_reply_dict[msg.message.chat.id] = message


dispatcher.add_handler(
    CallbackQueryHandler(refresh, pattern='^' + str(ONE) + '$'))
dispatcher.add_handler(
    CallbackQueryHandler(close, pattern='^' + str(TWO) + '$'))
コード例 #4
0
from pmb.helper.telegram_helper.message_utils import *
from pmb.helper.telegram_helper.filters import CustomFilters
from pmb.helper.telegram_helper.bot_commands import BotCommands
from pmb.helper.ext_utils.bot_utils import new_thread
from pmb import dispatcher


def cloneNode(update,context):
    args = update.message.text.split(" ",maxsplit=1)
    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\n👤 𝗖𝗹𝗼𝗻𝗲𝗱 𝗕𝘆 : {uname}'
    if len(args) > 1:
        link = args[1]
        msg = sendMessage(f"📚 Cloning: <code>{link}</code>",context.bot,update)
        gd = GoogleDriveHelper()
        result, button = gd.clone(link)
        deleteMessage(context.bot,msg)
        if button == "":
            sendMessage(result,context.bot,update)
        else:
            sendMarkup(result + cc,context.bot,update,button)
    else:
        sendMessage("Provide G-Drive Shareable Link to Clone.",context.bot,update)

clone_handler = CommandHandler(BotCommands.CloneCommand,cloneNode,filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
dispatcher.add_handler(clone_handler)
コード例 #5
0
<b>🏬 ISP:</b> <code>{result['client']['isp']}</code>
'''
    ed_msg.delete()
    try:
        update.effective_message.reply_photo(path,
                                             string_speed,
                                             parse_mode=ParseMode.HTML)
    except:
        update.effective_message.reply_text(string_speed,
                                            parse_mode=ParseMode.HTML)


def speed_convert(size):
    """Hi human, you can't read bytes?"""
    power = 2**10
    zero = 0
    units = {0: "", 1: "Kb/s", 2: "MB/s", 3: "Gb/s", 4: "Tb/s"}
    while size > power:
        size /= power
        zero += 1
    return f"{round(size, 2)} {units[zero]}"


SPEED_HANDLER = CommandHandler(BotCommands.SpeedCommand,
                               speedtest,
                               filters=CustomFilters.authorized_chat
                               | CustomFilters.authorized_user,
                               run_async=True)

dispatcher.add_handler(SPEED_HANDLER)
コード例 #6
0
                buttons.pop(0)
            if current_page == pages:
                buttons.pop()
        if ttl_ended or current_page != og_current_page:
            await callback_query.edit_message_text(
                text, reply_markup=InlineKeyboardMarkup([buttons]))
        message_info[
            message_identifier] = user_id, ttl, query, current_page, pages, sukebei
        if ttl_ended:
            ignore.add(message_identifier)
    await callback_query.answer()


def searchhelp(update, context):
    help_string = '''
• /ts <i>[search query]</i>
• /nyaa <i>[search query]</i>
• /nyaasi <i>[search query]</i>

• /sts <i>[search query]</i>
• /sukebei <i>[search query]</i>
'''
    update.effective_message.reply_photo(
        "https://telegra.ph/file/9f79dea91ab7cda63dc46.jpg",
        help_string,
        parse_mode=ParseMode.HTML)


SEARCHHELP_HANDLER = CommandHandler("tshelp", searchhelp)
dispatcher.add_handler(SEARCHHELP_HANDLER)
コード例 #7
0
        return
    cmd = cmd[1]
    process = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               shell=True)
    stdout, stderr = process.communicate()
    reply = ''
    stderr = stderr.decode()
    stdout = stdout.decode()
    if stdout:
        reply += f"*Stdout*\n`{stdout}`\n"
        LOGGER.info(f"Shell - {cmd} - {stdout}")
    if stderr:
        reply += f"*Stderr*\n`{stderr}`\n"
        LOGGER.error(f"Shell - {cmd} - {stderr}")
    if len(reply) > 3000:
        with open('shell_output.txt', 'w') as file:
            file.write(reply)
        with open('shell_output.txt', 'rb') as doc:
            context.bot.send_document(document=doc,
                                      filename=doc.name,
                                      reply_to_message_id=message.message_id,
                                      chat_id=message.chat_id)
    else:
        message.reply_text(reply, parse_mode=ParseMode.MARKDOWN)


SHELL_HANDLER = CommandHandler(['sh', 'shell', 'term', 'terminal'], shell)
dispatcher.add_handler(SHELL_HANDLER)
コード例 #8
0
        )
    else:
        msg.reply_text(
            "Failed to create sticker pack. Possibly due to blek mejik.")


@run_async
def stickhelp(update, context):
    help_string = '''
• `/stickerid`*:* Reply to a Sticker to me to tell you its file ID.
• `/getsticker`*:* Reply to a Sticker to me to upload its raw PNG file.
• `/kang`*:* Reply to a Sticker to add it to your pack.
• `/remove`*:* Replay to a Sticker to remove Sticker from an existing pack.
'''
    update.effective_message.reply_photo(IMAGE_URL,
                                         help_string,
                                         parse_mode=ParseMode.MARKDOWN)


STICKERID_HANDLER = CommandHandler("stickerid", stickerid)
GETSTICKER_HANDLER = CommandHandler("getsticker", getsticker)
KANG_HANDLER = CommandHandler("kang", kang)
DEL_HANDLER = CommandHandler("remove", delsticker)
STICKHELP_HANDLER = CommandHandler("stickerhelp", stickhelp)

dispatcher.add_handler(STICKERID_HANDLER)
dispatcher.add_handler(GETSTICKER_HANDLER)
dispatcher.add_handler(KANG_HANDLER)
dispatcher.add_handler(DEL_HANDLER)
dispatcher.add_handler(STICKHELP_HANDLER)
コード例 #9
0
                result = f'{value}'
            else:
                try:
                    result = f'{repr(eval(body, env))}'
                except:
                    pass
        else:
            result = f'{value}{func_return}'
        if result:
            return result


@dev_plus
def clear(update: Update, context: CallbackContext):
    bot = context.bot
    log_input(update)
    global namespaces
    if update.message.chat_id in namespaces:
        del namespaces[update.message.chat_id]
    send("Cleared locals.", bot, update)


EVAL_HANDLER = CommandHandler(('e', 'ev', 'eva', 'eval'), evaluate)
EXEC_HANDLER = CommandHandler(('x', 'ex', 'exe', 'exec', 'py'), execute)
CLEAR_HANDLER = CommandHandler('clearlocals', clear)

dispatcher.add_handler(EVAL_HANDLER)
dispatcher.add_handler(EXEC_HANDLER)
dispatcher.add_handler(CLEAR_HANDLER)

コード例 #10
0
            """App Quota."""
            Apps = result["apps"]
            for apps in Apps:
                if apps.get("app_uuid") == app.id:
                    AppQuotaUsed = apps.get("quota_used") / 60
                    AppPercent = math.floor(
                        apps.get("quota_used") * 100 / quota)
                    break
            else:
                AppQuotaUsed = 0
                AppPercent = 0

            AppHours = math.floor(AppQuotaUsed / 60)
            AppMinutes = math.floor(AppQuotaUsed % 60)

            sendMessage(
                f"<b>📈 Dyno Usage for</b> <code>{app.name}</code> :\n"
                f"• <code>{AppHours}</code> <b>Hours and</b> <code>{AppMinutes}</code> <b>Minutes - {AppPercent}%</b>\n\n"
                "<b>⌛ Dyno Remaining this month :</b>\n"
                f"• <code>{hours}</code> <b>Hours and</b> <code>{minutes}</code> <b>Minutes - {quota_percent}%</b>",
                context.bot, update)
            return True


usage_handler = CommandHandler(command=BotCommands.UsageCommand,
                               callback=usage,
                               filters=CustomFilters.owner_filter,
                               run_async=True)

dispatcher.add_handler(usage_handler)
コード例 #11
0
from telegram.ext import CommandHandler
from pmb import dispatcher, status_reply_dict, DOWNLOAD_STATUS_UPDATE_INTERVAL, status_reply_dict_lock
from pmb.helper.telegram_helper.message_utils import *
from time import sleep
from pmb.helper.ext_utils.bot_utils import get_readable_message
from telegram.error import BadRequest
from pmb.helper.telegram_helper.filters import CustomFilters
from pmb.helper.telegram_helper.bot_commands import BotCommands
import threading

def mirror_status(update,context):
    message = get_readable_message()
    if len(message) == 0:
        message = "No active downloads"
        reply_message = sendMessage(message, context.bot, update)
        threading.Thread(target=auto_delete_message, args=(bot, update.message, reply_message)).start()
        return
    index = update.effective_chat.id
    with status_reply_dict_lock:
        if index in status_reply_dict.keys():
            deleteMessage(bot, status_reply_dict[index])
            del status_reply_dict[index]
    sendStatusMessage(update,context.bot)
    deleteMessage(context.bot,update.message)


mirror_status_handler = CommandHandler(BotCommands.StatusCommand, mirror_status,
                                       filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
dispatcher.add_handler(mirror_status_handler)
コード例 #12
0
send_auth_handler = CommandHandler(command=BotCommands.AuthorizedUsersCommand,
                                   callback=sendAuthChats,
                                   filters=CustomFilters.owner_filter
                                   | CustomFilters.sudo_user,
                                   run_async=True)
authorize_handler = CommandHandler(command=BotCommands.AuthorizeCommand,
                                   callback=authorize,
                                   filters=CustomFilters.owner_filter
                                   | CustomFilters.sudo_user,
                                   run_async=True)
unauthorize_handler = CommandHandler(command=BotCommands.UnAuthorizeCommand,
                                     callback=unauthorize,
                                     filters=CustomFilters.owner_filter
                                     | CustomFilters.sudo_user,
                                     run_async=True)
addsudo_handler = CommandHandler(command=BotCommands.AddSudoCommand,
                                 callback=addSudo,
                                 filters=CustomFilters.owner_filter,
                                 run_async=True)
removesudo_handler = CommandHandler(command=BotCommands.RmSudoCommand,
                                    callback=removeSudo,
                                    filters=CustomFilters.owner_filter,
                                    run_async=True)

dispatcher.add_handler(send_auth_handler)
dispatcher.add_handler(authorize_handler)
dispatcher.add_handler(unauthorize_handler)
dispatcher.add_handler(addsudo_handler)
dispatcher.add_handler(removesudo_handler)
コード例 #13
0
def main():
    fs_utils.start_cleanup()
    # Check if the bot is restarting
    if path.exists('restart_msg.txt'):
        restart_msg_dat = open('restart_msg.txt', 'rt').read().split(' ')
        bot.editMessageText(text='Sync Completed!\nRestarted Successfully!',
                            chat_id=restart_msg_dat[0],
                            message_id=restart_msg_dat[1])
        LOGGER.info('Restarted Successfully!')
        remove('restart_msg.txt')
    bot.set_my_commands(botcmds)

    start_handler = CommandHandler(BotCommands.StartCommand,
                                   start,
                                   filters=CustomFilters.authorized_chat
                                   | CustomFilters.authorized_user,
                                   run_async=True)
    ping_handler = CommandHandler(BotCommands.PingCommand,
                                  ping,
                                  filters=CustomFilters.authorized_chat
                                  | CustomFilters.authorized_user,
                                  run_async=True)
    restart_handler = CommandHandler(BotCommands.RestartCommand,
                                     restart,
                                     filters=CustomFilters.owner_filter,
                                     run_async=True)
    help_handler = CommandHandler(BotCommands.HelpCommand,
                                  bot_help,
                                  filters=CustomFilters.authorized_chat
                                  | CustomFilters.authorized_user,
                                  run_async=True)
    stats_handler = CommandHandler(BotCommands.StatsCommand,
                                   stats,
                                   filters=CustomFilters.authorized_chat
                                   | CustomFilters.authorized_user,
                                   run_async=True)
    log_handler = CommandHandler(BotCommands.LogCommand,
                                 log,
                                 filters=CustomFilters.owner_filter,
                                 run_async=True)
    repo_handler = CommandHandler(BotCommands.RepoCommand,
                                  repo,
                                  filters=CustomFilters.authorized_chat
                                  | CustomFilters.authorized_user,
                                  run_async=True)
    owner_handler = CommandHandler(BotCommands.OwnerCommand,
                                   owner,
                                   filters=CustomFilters.authorized_chat
                                   | CustomFilters.authorized_user,
                                   run_async=True)
    config_handler = editor.handler
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(ping_handler)
    dispatcher.add_handler(restart_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(stats_handler)
    dispatcher.add_handler(log_handler)
    dispatcher.add_handler(repo_handler)
    dispatcher.add_handler(owner_handler)
    dispatcher.add_handler(config_handler)
    updater.start_polling()
    LOGGER.info("Bot Started!")
    signal.signal(signal.SIGINT, fs_utils.exit_clean_up)
コード例 #14
0
from pmb.helper.telegram_helper.bot_commands import BotCommands
from pmb.helper.mirror_utils.upload_utils import gdriveTools


def deletefile(update, context):
    msg_args = update.message.text.split(None, 1)
    msg = ''
    try:
        link = msg_args[1]
        LOGGER.info(msg_args[1])
    except IndexError:
        msg = 'Send a link along with command'

    if msg == '':
        drive = gdriveTools.GoogleDriveHelper()
        msg = drive.deletefile(link)
    LOGGER.info(f"DeleteFileCmd : {msg}")
    reply_message = sendMessage(msg, context.bot, update)

    threading.Thread(target=auto_delete_message,
                     args=(context.bot, update.message,
                           reply_message)).start()


delete_handler = CommandHandler(command=BotCommands.DeleteCommand,
                                callback=deletefile,
                                filters=CustomFilters.owner_filter
                                | CustomFilters.sudo_user,
                                run_async=True)
dispatcher.add_handler(delete_handler)
コード例 #15
0
            msg = '❎ Chat unauthorized'
        else:
            msg = '❎ Already unauthorized chat'
    else:
        # Trying to authorize someone in specific
        user_id = reply_message.from_user.id
        if user_id in AUTHORIZED_CHATS:
            AUTHORIZED_CHATS.remove(user_id)
            msg = '❎ Person unauthorized to use the bot!'
        else:
            msg = '❎ Person already unauthorized!'
    with open('authorized_chats.txt', 'a') as file:
        file.truncate(0)
        for i in AUTHORIZED_CHATS:
            file.write(f'{i}\n')
    sendMessage(msg, context.bot, update)


authorize_handler = CommandHandler(command=BotCommands.AuthorizeCommand,
                                   callback=authorize,
                                   filters=CustomFilters.owner_filter
                                   & Filters.group,
                                   run_async=True)
unauthorize_handler = CommandHandler(command=BotCommands.UnAuthorizeCommand,
                                     callback=unauthorize,
                                     filters=CustomFilters.owner_filter
                                     & Filters.group,
                                     run_async=True)
dispatcher.add_handler(authorize_handler)
dispatcher.add_handler(unauthorize_handler)
コード例 #16
0
from pmb.helper.telegram_helper.filters import CustomFilters
import threading
from pmb.helper.telegram_helper.bot_commands import BotCommands


def list_drive(update, context):
    try:
        search = update.message.text.split(' ', maxsplit=1)[1]
        LOGGER.info(f"Searching: {search}")
        reply = sendMessage('🔍 Searching..... ✋ Please Wait!', context.bot,
                            update)
        gdrive = GoogleDriveHelper(None)
        msg, button = gdrive.drive_list(search)

        if button:
            editMessage(msg, reply, button)
        else:
            editMessage('🚫 No results found', reply)

    except IndexError:
        sendMessage('Send a search key along with command', context.bot,
                    update)


list_handler = CommandHandler(BotCommands.ListCommand,
                              list_drive,
                              filters=CustomFilters.authorized_chat
                              | CustomFilters.authorized_user,
                              run_async=True)
dispatcher.add_handler(list_handler)
コード例 #17
0
def main():
    fs_utils.start_cleanup()
    # Check if the bot is restarting
    if os.path.isfile(".restartmsg"):
        with open(".restartmsg") as f:
            chat_id, msg_id = map(int, f)
        bot.edit_message_text("Restarted successfully!", chat_id, msg_id)
        os.remove(".restartmsg")
    bot.set_my_commands(botcmds)
        
    start_handler = CommandHandler(BotCommands.StartCommand, start,
                                   filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    ping_handler = CommandHandler(BotCommands.PingCommand, ping,
                                  filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    restart_handler = CommandHandler(BotCommands.RestartCommand, restart,
                                     filters=CustomFilters.owner_filter, run_async=True)
    help_handler = CommandHandler(BotCommands.HelpCommand,
                                  bot_help, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    stats_handler = CommandHandler(BotCommands.StatsCommand,
                                   stats, filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    log_handler = CommandHandler(BotCommands.LogCommand, log, filters=CustomFilters.owner_filter, run_async=True)
    repo_handler = CommandHandler(BotCommands.RepoCommand, repo,
                                  filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    owner_handler = CommandHandler(BotCommands.OwnerCommand, owner,
                                   filters=CustomFilters.authorized_chat | CustomFilters.authorized_user, run_async=True)
    authlist_handler = CommandHandler(BotCommands.AuthListCommand, chat_list, filters=CustomFilters.owner_filter, run_async=True)
    config_handler = editor.handler
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(ping_handler)
    dispatcher.add_handler(restart_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(stats_handler)
    dispatcher.add_handler(log_handler)
    dispatcher.add_handler(repo_handler)
    dispatcher.add_handler(owner_handler)
    dispatcher.add_handler(authlist_handler)
    dispatcher.add_handler(config_handler)
    updater.start_polling()
    LOGGER.info("Bot Started!")
    signal.signal(signal.SIGINT, fs_utils.exit_clean_up)
コード例 #18
0
                    parse_mode=ParseMode.MARKDOWN,
                    reply_markup=InlineKeyboardMarkup(buttons))
        else:
            update.effective_message.reply_text(
                msg,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(buttons))


def weebhelp(update, context):
    help_string = '''
• `/anime`*:* search anime
• `/character`*:* search character
• `/manga`*:* search manga
'''
    update.effective_message.reply_photo(
        "https://telegra.ph/file/9f79dea91ab7cda63dc46.jpg",
        help_string,
        parse_mode=ParseMode.MARKDOWN)


ANIME_HANDLER = CommandHandler("anime", anime)
CHARACTER_HANDLER = CommandHandler("character", character)
MANGA_HANDLER = CommandHandler("manga", manga)
WEEBHELP_HANDLER = CommandHandler("weebhelp", weebhelp)

dispatcher.add_handler(ANIME_HANDLER)
dispatcher.add_handler(CHARACTER_HANDLER)
dispatcher.add_handler(MANGA_HANDLER)
dispatcher.add_handler(WEEBHELP_HANDLER)