Пример #1
0
def add_to_privileges(username, level):
    if InsertDB.insert_new_user(db_conn=get_memory_db(), username=username):
        if InsertDB.insert_new_permission(db_conn=get_memory_db(),
                                          username=username,
                                          permission_level=int(level)):
            return True
    return False
Пример #2
0
def set_privileges(username, level, sender):
    all_user_data = GetDB.get_all_user_data(get_memory_db().cursor())
    user_names_list = [x[0] for x in all_user_data]
    if username in user_names_list:
        for user in all_user_data:
            if user[0] == username and username == sender:
                dprint(
                    f"This user: [{username}] tried to modify their own user privileges. Modification denied.",
                    origin=L_USER_PRIV)
                log(WARNING,
                    f"This user: [{username}] tried to modify their own user privileges, the modification was denied.",
                    origin=L_USER_PRIV)
                return False
            if user[0] == username and privileges_check(sender) <= user[1]:
                dprint(
                    f"This user: [{sender['name']}] tried to modify privileges for a user with equal/higher privileges: [{username}]",
                    origin=L_USER_PRIV)
                log(WARNING,
                    f"This user: [{sender['name']}] tried to modify privileges for a user with equal/higher privileges: [{username}]",
                    origin=L_USER_PRIV)
                return False
    if UpdateDB.update_user_privileges(db_conn=get_memory_db(),
                                       user_name=username,
                                       level=int(level)):
        return True
    return False
Пример #3
0
def privileges_check(user):
    # Print and log a critical database access error if the database has not been initialized.
    if not GS.mumble_db_string:
        dprint(
            f"The JJMumbleBot database has not been initialized, but a user privilege check is trying to access it!\nTrying to initialize database..."
        )
        log(CRITICAL,
            f"The JJMumbleBot database has not been initialized, but a user privilege check is trying to access it!\nTrying to initalize database...",
            origin=L_DATABASE)
        return -1
    # Retrieve the user information in the database.
    user_data = GetDB.get_user_data(db_cursor=get_memory_db().cursor(),
                                    user_name=user['name'])
    # Create a new user entry if the user does not already exist in the database.
    if not user_data:
        InsertDB.insert_new_user(db_conn=get_memory_db(),
                                 username=user['name'])
        InsertDB.insert_new_permission(
            db_conn=get_memory_db(),
            username=user['name'],
            permission_level=Privileges.DEFAULT.value)
        # save_memory_db_to_file(get_memory_db())

        # Retrieve the user information in the database.
        user_data = GetDB.get_user_data(db_cursor=get_memory_db().cursor(),
                                        user_name=user['name'])
        return int(user_data['level'])
    return int(user_data['level'])
Пример #4
0
def add_to_privileges(username, level):
    if InsertDB.insert_new_user(db_conn=get_memory_db(), username=username):
        if InsertDB.insert_new_permission(db_conn=get_memory_db(), username=username,
                                          permission_level=int(level)):
            log(INFO,
                f"A new user: [{username}] has been added to the user privileges.",
                origin=L_USER_PRIV, print_mode=PrintMode.VERBOSE_PRINT.value)
            return True
    return False
Пример #5
0
def remove_from_blacklist(username):
    all_user_data = GetDB.get_all_user_data(get_memory_db().cursor())
    user_names_list = [x[0] for x in all_user_data]
    if username in user_names_list:
        for user in all_user_data:
            if user[0] == username and user[1] == Privileges.BLACKLIST.value:
                if UpdateDB.update_user_privileges(db_conn=get_memory_db(), user_name=username, level=int(Privileges.DEFAULT.value)):
                    return True
    return False
Пример #6
0
    def initialize_plugins():
        import sys
        import os

        # Import global aliases into the database.
        UtilityDB.import_aliases_to_db(db_conn=get_memory_db(),
                                       csv_path=f'{dir_utils.get_main_dir()}/cfg/global_aliases.csv')

        global_settings.bot_plugins = {}
        # Load Core Plugins
        rprint("######### Initializing Core Plugins #########")
        sys.path.insert(0, f'{dir_utils.get_main_dir()}/plugins/core')
        all_imports = [name for name in os.listdir(f'{dir_utils.get_main_dir()}/plugins/core') if
                       os.path.isdir(os.path.join(f'{dir_utils.get_main_dir()}/plugins/core',
                                                  name)) and name != "__pycache__"]
        for p_file in all_imports:
            if not os.path.exists(os.path.join(f'{dir_utils.get_main_dir()}/plugins/core',
                                               p_file)):
                rprint(f"{p_file} plugin does not contain a metadata.ini file. Skipping initialization...")
                log(WARNING, f"{p_file} plugin does not contain a metadata.ini file. Skipping initialization...")
                continue
            # Import the core plugin.
            global_settings.bot_plugins[p_file] = __import__(f'{p_file}.{p_file}', fromlist=['*']).Plugin()
            # Import core plugin into the database.
            InsertDB.insert_new_plugin(db_conn=get_memory_db(), plugin_name=p_file, ignore_file_save=True)
            # Import core plugin user privileges into the database.
            UtilityDB.import_privileges_to_db(db_conn=get_memory_db(), csv_path=f'{dir_utils.get_main_dir()}/plugins/core/{p_file}/privileges.csv')
            # Import plugin aliases into the database.
            UtilityDB.import_aliases_to_db(db_conn=get_memory_db(), csv_path=f'{dir_utils.get_main_dir()}/plugins/core/{p_file}/aliases.csv')
            # Import plugin help into the database.
            UtilityDB.import_help_to_db(db_conn=get_memory_db(), html_path=f'{dir_utils.get_main_dir()}/plugins/core/{p_file}/help.html')
        sys.path.pop(0)
        rprint("######### Core Plugins Initialized #########")
        # Load Extension Plugins
        rprint("######### Initializing Extension Plugins #########")
        sys.path.insert(0, f'{dir_utils.get_main_dir()}/plugins/extensions')
        all_imports = [name for name in os.listdir(f'{dir_utils.get_main_dir()}/plugins/extensions') if
                       os.path.isdir(
                           os.path.join(f'{dir_utils.get_main_dir()}/plugins/extensions',
                                        name)) and name != "__pycache__"]
        for p_file in all_imports:
            if not os.path.exists(os.path.join(f'{dir_utils.get_main_dir()}/plugins/extensions',
                                               p_file)):
                rprint(f"{p_file} plugin does not contain a metadata.ini file. Skipping initialization...")
                log(WARNING, f"{p_file} plugin does not contain a metadata.ini file. Skipping initialization...")
                continue
            # Import the core plugin.
            global_settings.bot_plugins[p_file] = __import__(f'{p_file}.{p_file}', fromlist=['*']).Plugin()
            # Import core plugin into the database.
            InsertDB.insert_new_plugin(db_conn=get_memory_db(), plugin_name=p_file, ignore_file_save=True)
            # Import core plugin user privileges into the database.
            UtilityDB.import_privileges_to_db(db_conn=get_memory_db(), csv_path=f'{dir_utils.get_main_dir()}/plugins/extensions/{p_file}/privileges.csv')
            # Import plugin aliases into the database.
            UtilityDB.import_aliases_to_db(db_conn=get_memory_db(), csv_path=f'{dir_utils.get_main_dir()}/plugins/extensions/{p_file}/aliases.csv')
            # Import plugin help into the database.
            UtilityDB.import_help_to_db(db_conn=get_memory_db(), html_path=f'{dir_utils.get_main_dir()}/plugins/extensions/{p_file}/help.html')
        save_memory_db_to_file()
        sys.path.pop(0)
        rprint("######### Extension Plugins Initialized #########")
Пример #7
0
def add_to_blacklist(username):
    all_user_data = GetDB.get_all_user_data(get_memory_db().cursor())
    user_names_list = [x[0] for x in all_user_data]
    if username in user_names_list:
        for user in all_user_data:
            if user[0] == username and user[1] == Privileges.BLACKLIST.value:
                rprint(f"The user: {username} is already in the blacklist.", origin=L_USER_PRIV)
                log(INFO, f"The user: {username} is already in the blacklist.", origin=L_USER_PRIV)
                return False
        if UpdateDB.update_user_privileges(db_conn=get_memory_db(), user_name=username, level=int(Privileges.BLACKLIST.value)):
            return True
    return False
Пример #8
0
def add_to_blacklist(username):
    all_user_data = GetDB.get_all_user_data(get_memory_db().cursor())
    user_names_list = [x[0] for x in all_user_data]
    if username in user_names_list:
        for user in all_user_data:
            if user[0] == username and user[1] == Privileges.BLACKLIST.value:
                log(WARNING,
                    f"Could not add the user: {username} to the blacklist since the user is already in the blacklist.",
                    origin=L_USER_PRIV, error_type=GEN_PROCESS_WARN, print_mode=PrintMode.VERBOSE_PRINT.value)
                return False
        if UpdateDB.update_user_privileges(db_conn=get_memory_db(), user_name=username, level=int(Privileges.BLACKLIST.value)):
            return True
    return False
Пример #9
0
def import_aliases() -> bool:
    from JJMumbleBot.lib.utils.dir_utils import get_main_dir
    from JJMumbleBot.lib.resources.strings import T_TEMP_ALIASES
    from csv import DictReader, Error
    try:
        with open(f"{get_main_dir()}/cfg/downloads/{T_TEMP_ALIASES}.csv", mode='r') as csv_file:
            csvr = DictReader(csv_file)
            for i, row in enumerate(csvr):
                UpdateDB.update_alias(get_memory_db(),
                                      alias_name=row['alias'].strip(),
                                      commands=row['command'].strip(),
                                      ignore_file_save=True)
            save_memory_db_to_file()
        log(INFO, f"Updated aliases from the imported aliases file!",
            origin=L_DATABASE, print_mode=PrintMode.REG_PRINT.value)
        return True
    except FileNotFoundError:
        log(ERROR, f"Could not import aliases because the downloaded file is not found!",
            origin=L_DATABASE, print_mode=PrintMode.VERBOSE_PRINT.value)
        return False
    except Error:
        log(ERROR, f"Encountered a problem reading the imported aliases file! "
                   f"Please make sure the file is correctly formatted with headers: alias, command",
            origin=L_DATABASE, print_mode=PrintMode.VERBOSE_PRINT.value)
        return False
    except KeyError:
        log(ERROR, f"Encountered a problem reading the imported aliases file! "
                   f"Please make sure the file is correctly formatted with headers: alias, command",
            origin=L_DATABASE, print_mode=PrintMode.VERBOSE_PRINT.value)
        return False
Пример #10
0
    def __init__(self):
        super().__init__()
        if gs.safe_mode is True:
            log(INFO, "The web_server plugin cannot be started in safe mode. Skipping initialization...",
                origin=L_WEB_INTERFACE, print_mode=PrintMode.REG_PRINT.value)
            return

        from os import path
        from json import loads
        self.plugin_name = path.basename(__file__).rsplit('.')[0]
        self.metadata = gs.web_cfg
        self.plugin_cmds = loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
        ws_settings.plugin_name = self.plugin_name
        self.is_running = True
        log(INFO, "######### Configuring Web Interface #########",
            origin=L_WEB_INTERFACE, print_mode=PrintMode.VERBOSE_PRINT.value)
        from JJMumbleBot.lib.database import InsertDB
        from JJMumbleBot.lib.utils.database_management_utils import get_memory_db
        from JJMumbleBot.lib.privileges import Privileges
        if InsertDB.insert_new_user(db_conn=get_memory_db(),
                                    username=gs.cfg[C_CONNECTION_SETTINGS][P_USER_ID]):
            InsertDB.insert_new_permission(db_conn=get_memory_db(),
                                           username=gs.cfg[C_CONNECTION_SETTINGS][P_USER_ID],
                                           permission_level=int(Privileges.SUPERUSER.value))
        if self.metadata.getboolean(C_PLUGIN_SET, P_HTTPS_ENABLE, fallback=False):
            if self.metadata.getboolean(C_PLUGIN_SET, P_SSL_GENERATE, fallback=False):
                if not generate_cert():
                    log(
                        INFO,
                        f"Error generating web interface SSL certificate!",
                        origin=L_WEB_INTERFACE,
                        print_mode=PrintMode.REG_PRINT.value
                    )

        log(INFO, "######### Configured Web Interface #########",
            origin=L_WEB_INTERFACE, print_mode=PrintMode.VERBOSE_PRINT.value)
        if self.metadata.getboolean(C_PLUGIN_SET, P_WEB_ENABLE, fallback=False):
            self.init_server()
        log(
            INFO,
            f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized.",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value
        )
Пример #11
0
def get_all_aliases():
    alias_list = database_utils.GetDB.get_all_aliases(
        db_cursor=get_memory_db().cursor())
    if alias_list is not None:
        return alias_list
    dprint('Could not retrieve all the aliases from registered aliases.')
    log(INFO,
        "Could not retrieve all the aliases from registered aliases.",
        origin=L_ALIASES)
    return []
Пример #12
0
def get_all_aliases():
    alias_list = database_utils.GetDB.get_all_aliases(
        db_cursor=get_memory_db().cursor())
    if alias_list is not None:
        return alias_list
    log(INFO,
        "Could not retrieve all the aliases from registered aliases.",
        origin=L_ALIASES,
        print_mode=PrintMode.VERBOSE_PRINT.value)
    return []
Пример #13
0
def get_blacklist():
    blklist_txt = f"<font color='{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}'>Blacklisted Users:</font>"
    counter = 0
    all_user_data = GetDB.get_all_user_data(get_memory_db().cursor())
    for i, user in enumerate(all_user_data):
        if int(user[1]) == int(Privileges.BLACKLIST.value):
            blklist_txt += f"<br><font color='{GS.cfg[C_PGUI_SETTINGS][P_TXT_IND_COL]}'>[{counter}]</font> - {user[0]}"
            counter += 1
    if counter == 0:
        blklist_txt += " The blacklist is empty!"
    return blklist_txt
Пример #14
0
def clear_aliases():
    if database_utils.DeleteDB.delete_all_aliases(db_conn=get_memory_db()):
        dprint("All aliases were removed from the registered aliases.")
        log(INFO,
            "All aliases were removed from the registered aliases.",
            origin=L_ALIASES)
        return True
    dprint('Could not remove all aliases from registered aliases.')
    log(INFO,
        "Could not remove all aliases from registered aliases.",
        origin=L_ALIASES)
    return False
Пример #15
0
def clear_aliases():
    if database_utils.DeleteDB.delete_all_aliases(db_conn=get_memory_db()):
        log(INFO,
            "All aliases were removed from the registered aliases.",
            origin=L_ALIASES,
            print_mode=PrintMode.VERBOSE_PRINT.value)
        return True
    log(INFO,
        "Could not remove all aliases from registered aliases.",
        origin=L_ALIASES,
        print_mode=PrintMode.VERBOSE_PRINT.value)
    return False
Пример #16
0
def remove_from_aliases(alias):
    if database_utils.DeleteDB.delete_alias(db_conn=get_memory_db(),
                                            alias_name=alias):
        dprint(f"Removed [{alias}] from registered aliases.")
        log(INFO,
            f"Removed [{alias}] from registered aliases.",
            origin=L_ALIASES)
        return True
    dprint(f'Could not remove [{alias}] from registered aliases.')
    log(INFO,
        f"Could not remove [{alias}] from registered aliases.",
        origin=L_ALIASES)
    return False
Пример #17
0
def remove_from_aliases(alias):
    if database_utils.DeleteDB.delete_alias(db_conn=get_memory_db(),
                                            alias_name=alias):
        log(INFO,
            f"Removed [{alias}] from registered aliases.",
            origin=L_ALIASES,
            print_mode=PrintMode.VERBOSE_PRINT.value)
        return True
    log(INFO,
        f"Could not remove [{alias}] from registered aliases.",
        origin=L_ALIASES,
        print_mode=PrintMode.VERBOSE_PRINT.value)
    return False
Пример #18
0
def add_to_aliases(alias, commands):
    if database_utils.InsertDB.insert_new_alias(db_conn=get_memory_db(),
                                                alias_name=alias,
                                                commands=commands):
        dprint(f"Registered new alias: [{alias}] - [{commands}]")
        log(INFO,
            f"Registered new alias: [{alias}] - [{commands}]",
            origin=L_ALIASES)
        return True
    dprint(f'Could not add [{alias}] to registered aliases.')
    log(INFO,
        f"Could not add [{alias}] to registered aliases.",
        origin=L_ALIASES)
    return False
Пример #19
0
def set_alias(alias, commands) -> bool:
    if database_utils.UpdateDB.update_alias(db_conn=get_memory_db(),
                                            alias_name=alias,
                                            commands=commands):
        dprint(f"Registered alias: [{alias}] - [{commands}]")
        log(INFO,
            f"Registered alias: [{alias}] - [{commands}]",
            origin=L_ALIASES)
        return True
    dprint(f'Could not register [{alias}] to the registered aliases.')
    log(INFO,
        f"Could not register [{alias}] to the registered aliases.",
        origin=L_ALIASES)
    return False
Пример #20
0
def set_alias(alias, commands) -> bool:
    if database_utils.UpdateDB.update_alias(db_conn=get_memory_db(),
                                            alias_name=alias,
                                            commands=commands):
        log(INFO,
            f"Registered alias: [{alias}] - [{commands}]",
            origin=L_ALIASES,
            print_mode=PrintMode.VERBOSE_PRINT.value)
        return True
    log(INFO,
        f"Could not register [{alias}] to the registered aliases.",
        origin=L_ALIASES,
        print_mode=PrintMode.VERBOSE_PRINT.value)
    return False
Пример #21
0
def add_to_aliases(alias, commands):
    if database_utils.InsertDB.insert_new_alias(db_conn=get_memory_db(),
                                                alias_name=alias,
                                                commands=commands):
        log(INFO,
            f"Registered new alias: [{alias}] - [{commands}]",
            origin=L_ALIASES,
            print_mode=PrintMode.VERBOSE_PRINT.value)
        return True
    log(INFO,
        f"Could not add [{alias}] to registered aliases.",
        origin=L_ALIASES,
        print_mode=PrintMode.VERBOSE_PRINT.value)
    return False
Пример #22
0
def plugin_privileges_check(command, plugin_name):
    if not gs.mumble_db_string:
        log(CRITICAL,
            f"The JJMumbleBot database has not been initialized, but a user privilege check is trying to access it!",
            origin=L_DATABASE, error_type=GEN_PROCESS_ERR, print_mode=PrintMode.VERBOSE_PRINT.value)
        return -1
    # Retrieve the command information in the database.
    command_data = GetDB.get_plugin_data(db_cursor=get_memory_db().cursor(), plugin_name=plugin_name)
    # Return the command permission level if available.
    if command_data is not None:
        for item in command_data:
            if item[0] == command:
                return int(item[1])
    # Return -1 if the command is not found.
    return -1
Пример #23
0
def plugin_privileges_check(command, plugin_name):
    if not GS.mumble_db_string:
        dprint(
            f"The JJMumbleBot database has not been initialized, but a user privilege check is trying to access it!\nTrying to initialize database...")
        log(CRITICAL,
            f"The JJMumbleBot database has not been initialized, but a user privilege check is trying to access it!\nTrying to initalize database...",
            origin=L_DATABASE)
        return -1
    # Retrieve the command information in the database.
    command_data = GetDB.get_plugin_data(db_cursor=get_memory_db().cursor(), plugin_name=plugin_name)
    # Return the command permission level if available.
    if command_data is not None:
        for item in command_data:
            if item[0] == command:
                return int(item[1])
    # Return -1 if the command is not found.
    return -1
Пример #24
0
    def check_database_metadata(db_conn, version: str,
                                plugins_checksum: str) -> bool:
        # Check database metadata for changes.
        # If the version is different, or plugin checksum is modified,
        # clear plugins, plugins_help, and commands tables on launch.

        # Retrieve the metadata information in the database.
        command_data = GetDB.get_metadata(db_cursor=get_memory_db().cursor())
        if command_data is not None:
            # Database integrity violated if version doesn't match or plugin checksum doesn't match.
            if version != command_data[
                    'version'] or plugins_checksum != command_data['checksum']:
                UpdateDB.update_metadata(db_conn,
                                         version=version,
                                         checksum=plugins_checksum)
                return False
        return True
Пример #25
0
    def cmd_cmdsearch(self, data):
        all_data = data.message.strip().split(' ', 1)
        if len(all_data) != 2:
            log(ERROR,
                CMD_INVALID_CMD_SEARCH,
                origin=L_COMMAND,
                error_type=CMD_INVALID_ERR,
                print_mode=PrintMode.VERBOSE_PRINT.value)
            gs.gui_service.quick_gui(
                CMD_INVALID_CMD_SEARCH,
                text_type='header',
                box_align='left',
                user=gs.mumble_inst.users[data.actor]['name'],
                ignore_whisper=True)
            return
        search_query = all_data[1].strip()
        all_cmds = GetDB.get_all_commands(db_cursor=get_memory_db().cursor())
        if not all_cmds:
            gs.gui_service.quick_gui(ERR_DATABASE_CMD,
                                     text_type='header',
                                     text_align='left',
                                     box_align='left')
            return
        cmd_list = [f"{cmd_item[0]}" for cmd_item in all_cmds]
        cmd_ratios = process.extract(search_query, cmd_list)
        match_list = []
        for cmd_item in cmd_ratios:
            if cmd_item[1] > 80 and len(match_list) < 10:
                match_list.append(cmd_item[0])

        match_str = f"Command Search Results for <font color={gs.cfg[C_PGUI_SETTINGS][P_TXT_SUBHEAD_COL]}>{search_query}</font>: "
        if len(match_list) > 0:
            for i, clip in enumerate(match_list):
                match_str += f"<br><font color={gs.cfg[C_PGUI_SETTINGS][P_TXT_IND_COL]}>[{i + 1}]</font> - {clip}"
        else:
            match_str += "None"
        gs.gui_service.quick_gui(match_str,
                                 text_type='header',
                                 text_align='left',
                                 box_align='left')
        log(INFO,
            INFO_DISPLAYED_CMD_SEARCH,
            origin=L_COMMAND,
            print_mode=PrintMode.VERBOSE_PRINT.value)
Пример #26
0
 def cmd_refreshaliases(self, data):
     from JJMumbleBot.lib.utils.database_utils import UtilityDB
     from JJMumbleBot.lib.utils.dir_utils import get_main_dir
     UtilityDB.import_aliases_to_db(
         db_conn=get_memory_db(),
         csv_path=f'{get_main_dir()}/cfg/custom_aliases.csv',
         update_if_exists=True,
         ignore_file_save=False)
     log(INFO,
         "Refreshed custom aliases and updated the database.",
         origin=L_COMMAND,
         error_type=CMD_INVALID_ERR,
         print_mode=PrintMode.VERBOSE_PRINT.value)
     GS.gui_service.quick_gui(
         "Refreshed custom aliases and updated the database.",
         text_type='header',
         text_align='left',
         box_align='left',
         ignore_whisper=True,
         user=GS.mumble_inst.users[data.actor]['name'])
Пример #27
0
 def import_aliases_to_db(db_conn,
                          csv_path,
                          update_if_exists=False,
                          ignore_file_save=True):
     file_name = csv_path.split('/')[-2]
     with open(csv_path, mode='r') as csv_file:
         csvr = DictReader(csv_file)
         for i, row in enumerate(csvr):
             try:
                 # Skip alias import if already present in the database.
                 if GetDB.get_alias(
                         db_cursor=get_memory_db().cursor(),
                         alias_name=row['alias'].strip()) is not None:
                     log(INFO,
                         f"The alias '{row['alias'].strip()}' already exists in the database. Skipping alias import...",
                         origin=L_DATABASE,
                         print_mode=PrintMode.VERBOSE_PRINT.value)
                     # Update alias if it exists and the flag is set.
                     if update_if_exists:
                         UpdateDB.update_alias(
                             db_conn=db_conn,
                             alias_name=row['alias'].strip(),
                             commands=row['command'].strip(),
                             ignore_file_save=ignore_file_save)
                         log(INFO,
                             f"The alias '{row['alias'].strip()}' has been updated in the database.",
                             origin=L_DATABASE,
                             print_mode=PrintMode.VERBOSE_PRINT.value)
                     continue
                 # Insert new alias if it is not already present in the database.
                 InsertDB.insert_new_alias(
                     db_conn,
                     alias_name=row['alias'].strip(),
                     commands=row['command'].strip(),
                     ignore_file_save=ignore_file_save)
             except Error:
                 log(ERROR,
                     f"Encountered an error while importing a plugin alias from {file_name} plugin into the database.",
                     origin=L_DATABASE,
                     print_mode=PrintMode.VERBOSE_PRINT.value)
                 continue
Пример #28
0
    def cmd_cmdsearch(self, data):
        all_data = data.message.strip().split(' ', 1)
        if len(all_data) != 2:
            rprint(
                f"Incorrect format! Format: {rutils.get_command_token()}cmdsearch 'command'"
            )
            gs.gui_service.quick_gui(
                f"Incorrect format! Format: {rutils.get_command_token()}cmdsearch 'command'",
                text_type='header',
                box_align='left',
                user=gs.mumble_inst.users[data.actor]['name'],
                ignore_whisper=True)
            return
        search_query = all_data[1].strip()

        all_cmds = GetDB.get_all_commands(db_cursor=get_memory_db().cursor())
        if not all_cmds:
            gs.gui_service.quick_gui(
                "There was an error retrieving the commands from the database.",
                text_type='header',
                text_align='left',
                box_align='left')
            return
        cmd_list = [f"{cmd_item[0]}" for cmd_item in all_cmds]
        file_ratios = process.extract(search_query, cmd_list)
        match_list = []
        for file_item in file_ratios:
            if file_item[1] > 80 and len(match_list) < 10:
                match_list.append(file_item[0])

        match_str = f"Search Results for <font color={gs.cfg[C_PGUI_SETTINGS][P_TXT_SUBHEAD_COL]}>{search_query}</font>: "
        if len(match_list) > 0:
            for i, clip in enumerate(match_list):
                match_str += f"<br><font color={gs.cfg[C_PGUI_SETTINGS][P_TXT_IND_COL]}>[{i + 1}]</font> - {clip}"
        else:
            match_str += "None"
        gs.gui_service.quick_gui(match_str,
                                 text_type='header',
                                 text_align='left',
                                 box_align='left')
Пример #29
0
    def cmd_help(self, data):
        all_data = data.message.strip().split()
        if len(all_data) < 2:
            all_plugin_names = [plugin for plugin in list(GS.bot_plugins)]
            all_plugin_metadata = [{
                "name":
                plugin_name,
                "metadata":
                GS.bot_plugins[plugin_name].metadata
            } for plugin_name in all_plugin_names]
            all_core_plugin_names = [
                (plugin_info["name"],
                 plugin_info["metadata"][C_PLUGIN_INFO][P_PLUGIN_NAME])
                for plugin_info in all_plugin_metadata
                if plugin_info["metadata"].getboolean(C_PLUGIN_TYPE,
                                                      P_CORE_PLUGIN)
            ]
            all_extension_plugin_names = [
                (plugin_info["name"],
                 plugin_info["metadata"][C_PLUGIN_INFO][P_PLUGIN_NAME])
                for plugin_info in all_plugin_metadata
                if plugin_info["metadata"].getboolean(C_PLUGIN_TYPE,
                                                      P_EXT_PLUGIN)
            ]

            GS.gui_service.open_box()
            content = GS.gui_service.make_content(
                f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}">##### </font>'
                f'<b>{rutils.get_bot_name()} General Help Commands</b>'
                f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}"> #####</font>'
            )
            GS.gui_service.append_row(content)

            content = GS.gui_service.make_content(
                f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}">##### </font>'
                f'<b>Core Plugins</b>'
                f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}"> #####</font>'
            )
            GS.gui_service.append_row(content)
            for x, plugin_info in enumerate(all_core_plugin_names):
                content = GS.gui_service.make_content(
                    f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_SUBHEAD_COL]}">!help {plugin_info[0].strip()}</font> - Displays help information for the <font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_IND_COL]}">{plugin_info[1]}</font> plugin.',
                    text_type='header',
                    text_align="left")
                GS.gui_service.append_row(content)

            content = GS.gui_service.make_content(
                f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}">##### </font>'
                f'<b>Extension Plugins</b>'
                f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}"> #####</font>'
            )
            GS.gui_service.append_row(content)
            for x, plugin_info in enumerate(all_extension_plugin_names):
                content = GS.gui_service.make_content(
                    f'<font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_SUBHEAD_COL]}">!help {plugin_info[0].strip()}</font> - Displays help information for the <font color="{GS.cfg[C_PGUI_SETTINGS][P_TXT_IND_COL]}">{plugin_info[1].strip()}</font> plugin.',
                    text_type='header',
                    text_align="left")
                GS.gui_service.append_row(content)

            GS.gui_service.close_box()
            GS.gui_service.display_box(channel=rutils.get_my_channel())
            log(INFO,
                f"Displayed general help screen in the channel.",
                origin=L_COMMAND,
                print_mode=PrintMode.VERBOSE_PRINT.value)
            return

        plugin_name = all_data[1]
        plugin_help_data = PluginUtilityService.process_help(
            db_cursor=get_memory_db().cursor(), plugin_name=plugin_name)
        if plugin_help_data:
            plugin_metadata = GS.bot_plugins[plugin_name].metadata

            GS.gui_service.open_box()
            all_help_lines = [
                msg.strip() for msg in plugin_help_data.split('<br>')
            ]
            content = GS.gui_service.make_content(
                f'<font color="red">##### </font>'
                f'<b>{rutils.get_bot_name()} Help Commands - [{plugin_name}]</b>'
                f'<font color="red"> #####</font>')
            GS.gui_service.append_row(content)
            content = GS.gui_service.make_content(
                f'Plugin Version: {plugin_metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]}<br>',
                text_color='cyan')
            GS.gui_service.append_row(content)
            for x, help_item in enumerate(all_help_lines):
                item_parts = help_item.rsplit(':', 1)
                if len(item_parts) > 1:
                    content = GS.gui_service.make_content(
                        f'<font color="yellow">{item_parts[0]}</font>:{item_parts[1]}',
                        text_type='header',
                        text_align="left")
                else:
                    content = GS.gui_service.make_content(f'{help_item}',
                                                          text_type='header',
                                                          text_align="left")
                GS.gui_service.append_row(content)
            GS.gui_service.close_box()
            GS.gui_service.display_box(channel=rutils.get_my_channel())
            log(INFO,
                f"Displayed help screen for {plugin_name} in the channel.",
                origin=L_COMMAND,
                print_mode=PrintMode.VERBOSE_PRINT.value)
Пример #30
0
def get_all_privileges():
    priv_text = f"<font color='{GS.cfg[C_PGUI_SETTINGS][P_TXT_HEAD_COL]}'>All User Privileges:</font>"
    for i, user in enumerate(GetDB.get_all_user_data(get_memory_db().cursor())):
        priv_text += f"<br><font color='{GS.cfg[C_PGUI_SETTINGS][P_TXT_IND_COL]}'>[{user[0]}]</font> - {user[1]}"
    return priv_text