Exemplo n.º 1
0
        def _message(func):
            try:
                if can_disable:
                    self._dispatcher.add_handler(
                        DisableAbleMessageHandler(pattern,
                                                  func,
                                                  friendly=friendly,
                                                  run_async=run_async), group)
                else:
                    self._dispatcher.add_handler(
                        MessageHandler(pattern, func, run_async=run_async),
                        group)
                log.info(
                    f"[KIGMSG] Loaded filter pattern {pattern} for function {func.__name__} in group {group}"
                )
            except TypeError:
                if can_disable:
                    self._dispatcher.add_handler(
                        DisableAbleMessageHandler(pattern,
                                                  func,
                                                  friendly=friendly,
                                                  run_async=run_async))
                else:
                    self._dispatcher.add_handler(
                        MessageHandler(pattern, func, run_async=run_async))
                log.info(
                    f"[KIGMSG] Loaded filter pattern {pattern} for function {func.__name__}"
                )

            return func
Exemplo n.º 2
0
def shell(update: Update, context: CallbackContext):
    message = update.effective_message
    cmd = message.text.split(" ", 1)
    if len(cmd) == 1:
        message.reply_text("No command to execute was given.")
        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)
Exemplo n.º 3
0
def main():
    """#TODO"""

    test_handler = CommandHandler("test", test, run_async=True)
    start_handler = CommandHandler("start",
                                   start,
                                   pass_args=True,
                                   run_async=True)

    help_handler = CommandHandler("help", get_help, run_async=True)
    help_callback_handler = CallbackQueryHandler(help_button,
                                                 pattern=r"help_",
                                                 run_async=True)

    settings_handler = CommandHandler("settings", get_settings, run_async=True)
    settings_callback_handler = CallbackQueryHandler(settings_button,
                                                     pattern=r"stngs_",
                                                     run_async=True)

    donate_handler = DisableAbleCommandHandler("donate",
                                               donate,
                                               run_async=True)
    migrate_handler = MessageHandler(Filters.status_update.migrate,
                                     migrate_chats,
                                     run_async=True)

    # dispatcher.add_handler(test_handler)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(settings_handler)
    dispatcher.add_handler(help_callback_handler)
    dispatcher.add_handler(settings_callback_handler)
    dispatcher.add_handler(migrate_handler)
    dispatcher.add_handler(donate_handler)
    dispatcher.add_error_handler(error_callback)
    # dispatcher.add_error_handler(error_handler)

    if WEBHOOK:
        log.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:
        log.info(
            f"Yuii started, Using long polling. | BOT: [@{dispatcher.bot.username}]"
        )
        updater.start_polling(allowed_updates=Update.ALL_TYPES,
                              timeout=15,
                              read_latency=4,
                              drop_pending_updates=True)
    if len(argv) not in (1, 3, 4):
        telethn.disconnect()
    else:
        telethn.run_until_disconnected()
    updater.idle()
Exemplo n.º 4
0
def main():
    dispatcher.add_error_handler(error_callback)
    # dispatcher.add_error_handler(error_handler)

    if WEBHOOK:
        log.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:
        log.info(
            f"Tedeza started, Using long polling. | BOT: [@{dispatcher.bot.username}]"
        )
        KigyoINIT.bot_id = dispatcher.bot.id
        KigyoINIT.bot_username = dispatcher.bot.username
        KigyoINIT.bot_name = dispatcher.bot.first_name
        updater.start_polling(timeout=15,
                              read_latency=4,
                              drop_pending_updates=True)
    if len(argv) not in (1, 3, 4):
        telethn.disconnect()
    else:
        telethn.run_until_disconnected()
    updater.idle()
Exemplo n.º 5
0
def main():
    test_handler = CommandHandler("test", test, run_async=True)
    start_handler = CommandHandler("start", start, pass_args=True, run_async=True)

    help_handler = CommandHandler("help", get_help, run_async=True)
    help_callback_handler = CallbackQueryHandler(
        help_button, pattern=r"help_", run_async=True
    )

    settings_handler = CommandHandler("settings", get_settings, run_async=True)
    settings_callback_handler = CallbackQueryHandler(
        settings_button, pattern=r"stngs_", run_async=True
    )

    donate_handler = DisableAbleCommandHandler("donate", donate, run_async=True)
    migrate_handler = MessageHandler(
        Filters.status_update.migrate, migrate_chats, run_async=True
    )

    # dispatcher.add_handler(test_handler)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(settings_handler)
    dispatcher.add_handler(help_callback_handler)
    dispatcher.add_handler(settings_callback_handler)
    dispatcher.add_handler(migrate_handler)
    dispatcher.add_handler(donate_handler)
    dispatcher.add_error_handler(error_callback)
    _message_queue = messagequeue.MessageQueue(autostart=False)
    # dispatcher.add_error_handler(error_handler)

    if WEBHOOK:
        log.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:
        log.info("Using long polling.")
        _message_queue.start()
        updater.start_polling(timeout=15, read_latency=4, clean=True)
    if len(argv) not in (1, 3, 4):
        telethn.disconnect()
    else:
        telethn.run_until_disconnected()
    updater.idle()
    _message_queue.stop()
    def start_updater(poll_interval, timeout):
        self.updater.start_polling(poll_interval=poll_interval, timeout=timeout)
        self.updater.idle()

    args = (0.1, 10)
    self.updater_thread = threading.Thread(target=start_updater, args=args)
    self.updater_thread.daemon = True
    self.updater_thread.start()
    while(True):
        pass
Exemplo n.º 6
0
def migrate_chats(update: Update, context: CallbackContext):
    """#TODO

    Params:
        update: Update           -
        context: CallbackContext -
    """

    msg = update.effective_message  # type: Optional[Message]
    if msg.migrate_to_chat_id:
        old_chat = update.effective_chat.id
        new_chat = msg.migrate_to_chat_id
    elif msg.migrate_from_chat_id:
        old_chat = msg.migrate_from_chat_id
        new_chat = update.effective_chat.id
    else:
        return

    log.info("Migrating from %s, to %s", str(old_chat), str(new_chat))
    for mod in MIGRATEABLE:
        try:
            mod.__migrate__(old_chat, new_chat)
        except:
            pass

    log.info("Successfully migrated!")
    raise DispatcherHandlerStop
Exemplo n.º 7
0
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")
    ]

    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):
                log.error("Invalid loadorder names. Quitting.")
                quit(1)

            all_modules = sorted(set(all_modules) - set(to_load))
            to_load = list(all_modules) + to_load

        else:
            to_load = all_modules

        if NO_LOAD:
            log.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
Exemplo n.º 8
0
def check_and_ban(update, user_id, should_message=True):
    from tg_bot import SPB_MODE
    chat = update.effective_chat  # type: Optional[Chat]
    if SPB_MODE:
        try:
            apst = requests.get(
                f'https://api.intellivoid.net/spamprotection/v1/lookup?query={update.effective_user.id}')
            api_status = apst.status_code
            if api_status == 200:
                try:
                    status = client.raw_output(int(user_id))
                    try:
                        bl_check = (status["results"]["attributes"]["is_blacklisted"])
                    except:
                        bl_check = False

                    if bl_check:
                        bl_res = (status["results"]["attributes"]["blacklist_reason"])
                        update.effective_chat.kick_member(user_id)
                        if should_message:
                            update.effective_message.reply_text(
                                f"This person was blacklisted on @SpamProtectionBot and has been removed!\nReason: <code>{bl_res}</code>",
                                parse_mode=ParseMode.HTML,
                            )
                except HostDownError:
                    log.warning("Spam Protection API is unreachable.")
        except BaseException as e:
            log.info(f'SpamProtection was disabled due to {e}')
    try:
        sw_ban = sw.get_ban(int(user_id))
    except AttributeError:
        sw_ban = None
    except (SpamWatchError, Error, UnauthorizedError, NotFoundError, Forbidden, TooManyRequests) as e:
        log.warning(f" SpamWatch Error: {e}")
        sw_ban = None

    if sw_ban:
        update.effective_chat.kick_member(user_id)
        if should_message:
            update.effective_message.reply_text(
                f"This person has been detected as a spammer by @SpamWatch and has been removed!\nReason: <code>{sw_ban.reason}</code>",
                parse_mode=ParseMode.HTML,
            )
        return

    if sql.is_user_gbanned(user_id):
        update.effective_chat.kick_member(user_id)
        if should_message:
            text = (
                f"<b>Alert</b>: this user is globally banned.\n"
                f"<code>*bans them from here*</code>.\n"
                f"<b>Appeal chat</b>: @zerounions\n"
                f"<b>User ID</b>: <code>{user_id}</code>"
            )
            user = sql.get_gbanned_user(user_id)
            if user.reason:
                text += f"\n<b>Ban Reason:</b> <code>{html.escape(user.reason)}</code>"
            update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
Exemplo n.º 9
0
 def _callbackquery(func):
     self._dispatcher.add_handler(
         CallbackQueryHandler(pattern=pattern,
                              callback=func,
                              run_async=run_async))
     log.info(
         f'[KIGCALLBACK] Loaded callbackquery handler with pattern {pattern} for function {func.__name__}'
     )
     return func
Exemplo n.º 10
0
 def _inlinequery(func):
     self._dispatcher.add_handler(
         InlineQueryHandler(pattern=pattern,
                            callback=func,
                            run_async=run_async,
                            pass_user_data=pass_user_data,
                            pass_chat_data=pass_chat_data,
                            chat_types=chat_types))
     log.info(
         f'[KIGINLINE] Loaded inlinequery handler with pattern {pattern} for function {func.__name__} | PASSES USER DATA: {pass_user_data} | PASSES CHAT DATA: {pass_chat_data} | CHAT TYPES: {chat_types}'
     )
     return func
Exemplo n.º 11
0
def send(msg, bot, update):
    if len(str(msg)) > 2000:
        with io.BytesIO(str.encode(msg)) as out_file:
            out_file.name = "output.txt"
            bot.send_document(chat_id=update.effective_chat.id,
                              document=out_file)
    else:
        LOGGER.info(f"OUT: '{msg}'")
        bot.send_message(
            chat_id=update.effective_chat.id,
            text=f"`{msg}`",
            parse_mode=ParseMode.MARKDOWN,
        )
Exemplo n.º 12
0
        def _command(func):
            try:
                if can_disable:
                    self._dispatcher.add_handler(
                        DisableAbleCommandHandler(command,
                                                  func,
                                                  filters=filters,
                                                  run_async=run_async,
                                                  pass_args=pass_args,
                                                  admin_ok=admin_ok), group)
                else:
                    self._dispatcher.add_handler(
                        CommandHandler(command,
                                       func,
                                       filters=filters,
                                       run_async=run_async,
                                       pass_args=pass_args), group)
                log.info(
                    f"[KIGCMD] Loaded handler {command} for function {func.__name__} in group {group}"
                )
            except TypeError:
                if can_disable:
                    self._dispatcher.add_handler(
                        DisableAbleCommandHandler(
                            command,
                            func,
                            filters=filters,
                            run_async=run_async,
                            pass_args=pass_args,
                            admin_ok=admin_ok,
                            pass_chat_data=pass_chat_data))
                else:
                    self._dispatcher.add_handler(
                        CommandHandler(command,
                                       func,
                                       filters=filters,
                                       run_async=run_async,
                                       pass_args=pass_args,
                                       pass_chat_data=pass_chat_data))
                log.info(
                    f"[KIGCMD] Loaded handler {command} for function {func.__name__}"
                )

            return func
Exemplo n.º 13
0
def start() -> scoped_session:
    engine = create_engine(DB_URI, client_encoding="utf8")
    log.info("[PostgreSQL] Connecting to database......")
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=False))
Exemplo n.º 14
0
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

from tg_bot import DB_URI, log


def start() -> scoped_session:
    engine = create_engine(DB_URI, client_encoding="utf8")
    log.info("[PostgreSQL] Connecting to database......")
    BASE.metadata.bind = engine
    BASE.metadata.create_all(engine)
    return scoped_session(sessionmaker(bind=engine, autoflush=False))


BASE = declarative_base()
SESSION = start()
log.info("[PostgreSQL] Connection successful, session started.")
Exemplo n.º 15
0
def inlineinfo(query: str, update: Update, context: CallbackContext) -> None:
    """Handle the inline query."""
    bot = context.bot
    query = update.inline_query.query
    log.info(query)
    user_id = update.effective_user.id

    try:
        search = query.split(" ", 1)[1]
    except IndexError:
        search = user_id

    try:
        user = bot.get_chat(int(search))
    except (BadRequest, ValueError):
        user = bot.get_chat(user_id)

    chat = update.effective_chat
    sql.update_user(user.id, user.username)

    text = (f"<b>Information:</b>\n"
            f"• ID: <code>{user.id}</code>\n"
            f"• First Name: {html.escape(user.first_name)}")

    if user.last_name:
        text += f"\n• Last Name: {html.escape(user.last_name)}"

    if user.username:
        text += f"\n• Username: @{html.escape(user.username)}"

    text += f"\n• Permanent user link: {mention_html(user.id, 'link')}"

    nation_level_present = False

    if user.id == OWNER_ID:
        text += f"\n\nThis person is my owner"
        nation_level_present = True
    elif user.id in DEV_USERS:
        text += f"\n\nThis Person is a part of Eagle Union"
        nation_level_present = True
    elif user.id in SUDO_USERS:
        text += f"\n\nThe Nation level of this person is Royal"
        nation_level_present = True
    elif user.id in SUPPORT_USERS:
        text += f"\n\nThe Nation level of this person is Sakura"
        nation_level_present = True
    elif user.id in SARDEGNA_USERS:
        text += f"\n\nThe Nation level of this person is Sardegna"
        nation_level_present = True
    elif user.id in WHITELIST_USERS:
        text += f"\n\nThe Nation level of this person is Neptunia"
        nation_level_present = True

    if nation_level_present:
        text += ' [<a href="https://t.me/{}?start=nations">?</a>]'.format(
            bot.username)

    try:
        spamwtc = sw.get_ban(int(user.id))
        if spamwtc:
            text += "<b>\n\n• SpamWatched:\n</b> Yes"
            text += f"\n• Reason: <pre>{spamwtc.reason}</pre>"
            text += "\n• Appeal at @SpamWatchSupport"
        else:
            text += "<b>\n\n• SpamWatched:</b> No"
    except:
        pass  # don't crash if api is down somehow...

    num_chats = sql.get_user_num_chats(user.id)
    text += f"\n• <b>Chat count</b>: <code>{num_chats}</code>"

    kb = InlineKeyboardMarkup([
        [
            InlineKeyboardButton(
                text="Report Error",
                url=f"https://t.me/YorktownEagleUnion",
            ),
            InlineKeyboardButton(
                text="Search again",
                switch_inline_query_current_chat=".info ",
            ),
        ],
    ])

    results = [
        InlineQueryResultArticle(
            id=str(uuid4()),
            title=f"User info of {html.escape(user.first_name)}",
            input_message_content=InputTextMessageContent(
                text, parse_mode=ParseMode.HTML,
                disable_web_page_preview=True),
            reply_markup=kb),
    ]

    update.inline_query.answer(results, cache_time=5)
Exemplo n.º 16
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})")
Exemplo n.º 17
0
        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):
                log.error("[NOBARA] Invalid loadorder names. Quitting.")
                quit(1)

            all_modules = sorted(set(all_modules) - set(to_load))
            to_load = list(all_modules) + to_load

        else:
            to_load = all_modules

        if NO_LOAD:
            log.info("[NOBARA] 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 = __list_all_modules()
log.info("[NOBARA] Modules to load: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]
Exemplo n.º 18
0
def inlineinfo(query: str, update: Update, context: CallbackContext) -> None:
    """Handle the inline query."""
    bot = context.bot
    query = update.inline_query.query
    log.info(query)
    user_id = update.effective_user.id

    try:
        search = query.split(" ", 1)[1]
    except IndexError:
        search = user_id

    try:
        user = bot.get_chat(int(search))
    except (BadRequest, ValueError):
        user = bot.get_chat(user_id)

    chat = update.effective_chat
    sql.update_user(user.id, user.username)

    text = (f"<b>Information:</b>\n"
            f"• ID: <code>{user.id}</code>\n"
            f"• First Name: {html.escape(user.first_name)}")

    if user.last_name:
        text += f"\n• Last Name: {html.escape(user.last_name)}"

    if user.username:
        text += f"\n• Username: @{html.escape(user.username)}"

    text += f"\n• Permanent user link: {mention_html(user.id, 'link')}"

    nation_level_present = False

    if user.id == OWNER_ID:
        text += f"\n\nThis person is my owner"
        nation_level_present = True
    elif user.id in DEV_USERS:
        text += f"\n\nThis Person is a part of Eagle Union"
        nation_level_present = True
    elif user.id in SUDO_USERS:
        text += f"\n\nThe Nation level of this person is Royal"
        nation_level_present = True
    elif user.id in SUPPORT_USERS:
        text += f"\n\nThe Nation level of this person is Sakura"
        nation_level_present = True
    elif user.id in SARDEGNA_USERS:
        text += f"\n\nThe Nation level of this person is Sardegna"
        nation_level_present = True
    elif user.id in WHITELIST_USERS:
        text += f"\n\nThe Nation level of this person is Neptunia"
        nation_level_present = True

    if nation_level_present:
        text += ' [<a href="https://t.me/{}?start=nations">?</a>]'.format(
            bot.username)

    try:
        spamwtc = sw.get_ban(int(user.id))
        if spamwtc:
            text += "<b>\n\n• SpamWatched:\n</b> Yes"
            text += f"\n• Reason: <pre>{spamwtc.reason}</pre>"
            text += "\n• Appeal at @SpamWatchSupport"
        else:
            text += "<b>\n\n• SpamWatched:</b> No"
    except:
        pass  # don't crash if api is down somehow...

    apst = requests.get(
        f'https://api.intellivoid.net/spamprotection/v1/lookup?query={context.bot.username}'
    )
    api_status = apst.status_code
    if (api_status == 200):
        try:
            status = client.raw_output(int(user.id))
            # ptid = status["results"]["private_telegram_id"]
            op = status["results"]["attributes"]["is_operator"]
            ag = status["results"]["attributes"]["is_agent"]
            wl = status["results"]["attributes"]["is_whitelisted"]
            ps = status["results"]["attributes"]["is_potential_spammer"]
            sp = status["results"]["spam_prediction"]["spam_prediction"]
            hamp = status["results"]["spam_prediction"]["ham_prediction"]
            blc = status["results"]["attributes"]["is_blacklisted"]
            if blc:
                blres = status["results"]["attributes"]["blacklist_reason"]
            else:
                blres = None
            text += "\n\n<b>SpamProtection:</b>"
            # text += f"<b>\n• Private Telegram ID:</b> <code>{ptid}</code>\n"
            text += f"<b>\n• Operator:</b> <code>{op}</code>\n"
            text += f"<b>• Agent:</b> <code>{ag}</code>\n"
            text += f"<b>• Whitelisted:</b> <code>{wl}</code>\n"
            text += f"<b>• Spam/Ham Prediction:</b> <code>{round((sp/hamp*100), 3)}%</code>\n"
            text += f"<b>• Potential Spammer:</b> <code>{ps}</code>\n"
            text += f"<b>• Blacklisted:</b> <code>{blc}</code>\n"
            text += f"<b>• Blacklist Reason:</b> <code>{blres}</code>\n"
        except HostDownError:
            text += "\n\n<b>SpamProtection:</b>"
            text += "\nCan't connect to Intellivoid SpamProtection API\n"
    else:
        text += "\n\n<b>SpamProtection:</b>"
        text += f"\n<code>API RETURNED: {api_status}</code>\n"

    num_chats = sql.get_user_num_chats(user.id)
    text += f"\n• Chat count: <code>{num_chats}</code>"

    kb = InlineKeyboardMarkup([
        [
            InlineKeyboardButton(
                text="Report Error",
                url=f"https://t.me/YorktownEagleUnion",
            ),
            InlineKeyboardButton(
                text="Search again",
                switch_inline_query_current_chat=".info ",
            ),
        ],
    ])

    results = [
        InlineQueryResultArticle(
            id=str(uuid4()),
            title=f"User info of {html.escape(user.first_name)}",
            input_message_content=InputTextMessageContent(
                text, parse_mode=ParseMode.HTML,
                disable_web_page_preview=True),
            reply_markup=kb),
    ]

    update.inline_query.answer(results, cache_time=5)
Exemplo n.º 19
0
    if WEBHOOK:
        log.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:
        log.info(
            f"Nobara started, Using long polling. | BOT: [@{dispatcher.bot.username}]"
        )
        updater.start_polling(timeout=15,
                              read_latency=4,
                              drop_pending_updates=True)
    if len(argv) not in (1, 3, 4):
        telethn.disconnect()
    else:
        telethn.run_until_disconnected()
    updater.idle()


if __name__ == "__main__":
    kp.start()
    log.info("[KUGISAKI] Successfully loaded modules: " + str(ALL_MODULES))
    telethn.start(bot_token=TOKEN)
    main()
    idle()
Exemplo n.º 20
0
        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):
                log.error("Invalid loadorder names. Quitting.")
                quit(1)

            all_modules = sorted(set(all_modules) - set(to_load))
            to_load = list(all_modules) + to_load

        else:
            to_load = all_modules

        if NO_LOAD:
            log.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 = __list_all_modules()
log.info("Modules to load: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]
Exemplo n.º 21
0
def inlineinfo(query: str, update: Update, context: CallbackContext) -> None:
    """Handle the inline query."""
    bot = context.bot
    query = update.inline_query.query
    log.info(query)
    user_id = update.effective_user.id

    try:
        search = query.split(" ", 1)[1]
    except IndexError:
        search = user_id

    try:
        user = bot.get_chat(int(search))
    except (BadRequest, ValueError):
        user = bot.get_chat(user_id)

    chat = update.effective_chat
    sql.update_user(user.id, user.username)

    text = (f"<b>General:</b>\n"
            f"ID: <code>{user.id}</code>\n"
            f"First Name: {html.escape(user.first_name)}")

    if user.last_name:
        text += f"\nLast Name: {html.escape(user.last_name)}"

    if user.username:
        text += f"\nUsername: @{html.escape(user.username)}"

    text += f"\nPermanent user link: {mention_html(user.id, 'link')}"

    try:
        spamwtc = sw.get_ban(int(user.id))
        if spamwtc:
            text += "<b>\n\nSpamWatch:\n</b>"
            text += "<b>This person is banned in Spamwatch!</b>"
            text += f"\nReason: <pre>{spamwtc.reason}</pre>"
            text += "\nAppeal at @SpamWatchSupport"
        else:
            text += "<b>\n\nSpamWatch:</b>\n Not banned"
    except:
        pass  # don't crash if api is down somehow...

    try:
        status = client.raw_output(int(user.id))
        ptid = status["results"]["private_telegram_id"]
        op = status["results"]["attributes"]["is_operator"]
        ag = status["results"]["attributes"]["is_agent"]
        wl = status["results"]["attributes"]["is_whitelisted"]
        ps = status["results"]["attributes"]["is_potential_spammer"]
        sp = status["results"]["spam_prediction"]["spam_prediction"]
        hamp = status["results"]["spam_prediction"]["ham_prediction"]
        blc = status["results"]["attributes"]["is_blacklisted"]
        if blc:
            blres = status["results"]["attributes"]["blacklist_reason"]
        else:
            blres = None
        text += "\n\n<b>SpamProtection:</b>"
        text += f"<b>\nPrivate Telegram ID:</b> <code>{ptid}</code>\n"
        text += f"<b>Operator:</b> <code>{op}</code>\n"
        text += f"<b>Agent:</b> <code>{ag}</code>\n"
        text += f"<b>Whitelisted:</b> <code>{wl}</code>\n"
        text += f"<b>Spam Prediction:</b> <code>{sp}</code>\n"
        text += f"<b>Ham Prediction:</b> <code>{hamp}</code>\n"
        text += f"<b>Potential Spammer:</b> <code>{ps}</code>\n"
        text += f"<b>Blacklisted:</b> <code>{blc}</code>\n"
        text += f"<b>Blacklist Reason:</b> <code>{blres}</code>\n"
    except HostDownError:
        text += "\n\n<b>SpamProtection:</b>"
        text += "\nCan't connect to Intellivoid SpamProtection API\n"

    nation_level_present = False

    num_chats = sql.get_user_num_chats(user.id)
    text += f"\nChat count: <code>{num_chats}</code>"

    if user.id == OWNER_ID:
        text += f"\nThis person is my owner"
        nation_level_present = True
    elif user.id in DEV_USERS:
        text += f"\nThis Person is a part of Eagle Union"
        nation_level_present = True
    elif user.id in SUDO_USERS:
        text += f"\nThe Nation level of this person is Royal"
        nation_level_present = True
    elif user.id in SUPPORT_USERS:
        text += f"\nThe Nation level of this person is Sakura"
        nation_level_present = True
    elif user.id in SARDEGNA_USERS:
        text += f"\nThe Nation level of this person is Sardegna"
        nation_level_present = True
    elif user.id in WHITELIST_USERS:
        text += f"\nThe Nation level of this person is Neptunia"
        nation_level_present = True

    if nation_level_present:
        text += ' [<a href="https://t.me/{}?start=nations">?</a>]'.format(
            bot.username)

    results = [
        InlineQueryResultArticle(
            id=str(uuid4()),
            title=f"User info of {html.escape(user.first_name)}",
            input_message_content=InputTextMessageContent(
                text, parse_mode=ParseMode.HTML,
                disable_web_page_preview=True),
        ),
    ]

    update.inline_query.answer(results, cache_time=5)
Exemplo n.º 22
0
    if WEBHOOK:
        log.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:
        log.info(
            f"Kigyo started, Using long polling. | BOT: [@{dispatcher.bot.username}]"
        )
        updater.start_polling(timeout=15,
                              read_latency=4,
                              drop_pending_updates=True)
    if len(argv) not in (1, 3, 4):
        telethn.disconnect()
    else:
        telethn.run_until_disconnected()
    updater.idle()


if __name__ == "__main__":
    kp.start()
    log.info("[KIGYO] Successfully loaded modules: " + str(ALL_MODULES))
    telethn.start(bot_token=TOKEN)
    main()
    idle()
Exemplo n.º 23
0
    ]

    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
            ):
                log.error("[KIGYO] Invalid loadorder names. Quitting.")
                quit(1)

            all_modules = sorted(set(all_modules) - set(to_load))
            to_load = list(all_modules) + to_load

        else:
            to_load = all_modules

        if NO_LOAD:
            log.info("[KIGYO] 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 = __list_all_modules()
log.info("[KIGYO] Modules to load: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]