Ejemplo n.º 1
0
 def cmd_toggleloginsounds(self, data):
     data_actor = gs.mumble_inst.users[data.actor]
     current_status = not self.metadata.getboolean(
         C_PLUGIN_SET, P_PLAY_AUDIO_CLIP_ON_USER_JOIN, fallback=False)
     self.metadata[C_PLUGIN_SET][
         P_PLAY_AUDIO_CLIP_ON_USER_JOIN] = f"{'True' if current_status else 'False'}"
     try:
         with open(
                 f'{dir_utils.get_core_plugin_dir()}/{self.plugin_name}/metadata.ini',
                 'w') as metadata_file:
             self.metadata.write(metadata_file)
         self.metadata = PluginUtilityService.process_metadata(
             f'plugins/core/{self.plugin_name}')
         log(INFO,
             f"{'Enabled' if current_status else 'Disabled'} user connection sounds in the server_tools metadata.ini file.",
             origin=L_COMMAND,
             print_mode=PrintMode.VERBOSE_PRINT.value)
         gs.gui_service.quick_gui(
             f"{'Enabled' if current_status else 'Disabled'} user connection sounds in "
             f"the server_tools metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
     except IOError:
         log(ERROR,
             f"There was an error saving the {self.plugin_name} metadata to the metadata.ini file.",
             origin=L_COMMAND,
             error_type=CMD_PROCESS_ERR,
             print_mode=PrintMode.VERBOSE_PRINT.value)
         gs.gui_service.quick_gui(
             f"There was an error saving the {self.plugin_name} metadata to the metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
         return
Ejemplo n.º 2
0
 def cmd_toggleuserconnectionsound(self, data):
     data_actor = gs.mumble_inst.users[data.actor]
     current_status = not self.metadata.getboolean(
         C_PLUGIN_SET, P_PLAY_AUDIO_CLIP_ON_USER_JOIN, fallback=False)
     self.metadata[C_PLUGIN_SET][
         P_PLAY_AUDIO_CLIP_ON_USER_JOIN] = f"{'True' if current_status else 'False'}"
     try:
         with open(
                 f'{dir_utils.get_main_dir()}/plugins/extensions/{self.plugin_name}/metadata.ini',
                 'w') as metadata_file:
             self.metadata.write(metadata_file)
         self.metadata = PluginUtilityService.process_metadata(
             f'plugins/extensions/{self.plugin_name}')
         gs.gui_service.quick_gui(
             f"{'Enabled' if current_status else 'Disabled'} user connection sounds in "
             f"the server_tools metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
     except IOError:
         gs.gui_service.quick_gui(
             f"There was an error saving the {self.plugin_name} metadata to the metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
         return
Ejemplo n.º 3
0
 def cmd_setdefaultloginsound(self, data):
     all_data = data.message.strip().split(' ', 1)
     data_actor = gs.mumble_inst.users[data.actor]
     if len(all_data) != 2:
         log(ERROR,
             CMD_INVALID_SET_USER_DEFAULT_CONNECTION,
             origin=L_COMMAND,
             error_type=CMD_PROCESS_ERR,
             print_mode=PrintMode.VERBOSE_PRINT.value)
         gs.gui_service.quick_gui(CMD_INVALID_SET_USER_DEFAULT_CONNECTION,
                                  text_type='header',
                                  box_align='left',
                                  user=data_actor['name'])
         return
     audio_clip_name = all_data[1]
     if not find_file(audio_clip_name):
         log(ERROR,
             f"{audio_clip_name} is not one of the available files in the sound board permanent directory.",
             origin=L_COMMAND,
             error_type=CMD_PROCESS_ERR,
             print_mode=PrintMode.VERBOSE_PRINT.value)
         gs.gui_service.quick_gui(
             f"{audio_clip_name} is not one of the available files in the sound board permanent directory.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
         return
     self.metadata[C_PLUGIN_SET][
         P_GENERIC_CLIP_TO_PLAY_ON_USER_JOIN] = audio_clip_name
     try:
         with open(
                 f'{dir_utils.get_core_plugin_dir()}/{self.plugin_name}/metadata.ini',
                 'w') as metadata_file:
             self.metadata.write(metadata_file)
         self.metadata = PluginUtilityService.process_metadata(
             f'plugins/core/{self.plugin_name}')
         log(INFO,
             f"Updated the default user connection sound and saved the {self.plugin_name} metadata to the metadata.ini file.",
             origin=L_COMMAND,
             print_mode=PrintMode.VERBOSE_PRINT.value)
         gs.gui_service.quick_gui(
             f"Updated the default user connection sound and saved the {self.plugin_name} metadata to the metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
     except IOError:
         log(ERROR,
             f"There was an error saving the {self.plugin_name} metadata to the metadata.ini file.",
             origin=L_COMMAND,
             error_type=CMD_PROCESS_ERR,
             print_mode=PrintMode.VERBOSE_PRINT.value)
         gs.gui_service.quick_gui(
             f"There was an error saving the {self.plugin_name} metadata to the metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
         return
Ejemplo n.º 4
0
 def __init__(self):
     super().__init__()
     from os import path
     from json import loads
     self.plugin_name = path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(f'plugins/core/{self.plugin_name}')
     self.plugin_cmds = loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     rprint(
         f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized.")
Ejemplo n.º 5
0
 def __init__(self):
     super().__init__()
     import os
     import json
     self.plugin_name = os.path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = json.loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     # Add any custom initialization code here...
     # ...
     # ...
     rprint(
         f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized.")
Ejemplo n.º 6
0
 def __init__(self):
     super().__init__()
     from json import loads
     self.plugin_name = os.path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(
         f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(
         self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     self.is_running = True
     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)
Ejemplo n.º 7
0
 def __init__(self):
     super().__init__()
     from json import loads
     self.plugin_name = os.path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(
         f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(
         self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     dir_utils.make_directory(
         f'{gs.cfg[C_MEDIA_SETTINGS][P_PERM_MEDIA_DIR]}/{self.plugin_name}/'
     )
     rprint(
         f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized."
     )
 def __init__(self):
     super().__init__()
     from os import path
     from json import loads
     self.plugin_name = path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     self.osrs_wiki_url = self.metadata[C_PLUGIN_SET][P_WIKI_URL]
     self.osrs_user_agent = self.metadata[C_PLUGIN_SET][P_USER_AGENT]
     rprint(
         f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized.")
     try:
         self.osrs_wiki = MediaWiki(url=self.osrs_wiki_url, user_agent=self.osrs_user_agent)
     except Exception:
         rprint(f"{self.plugin_name} Plugin could not be initialized.")
Ejemplo n.º 9
0
 def __init__(self):
     super().__init__()
     from json import loads
     self.plugin_name = os.path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     dir_utils.make_directory(f'{GS.cfg[C_MEDIA_DIR][P_TEMP_MED_DIR]}/{self.plugin_name}/')
     warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
     YH.yt_metadata = self.metadata
     YH.volume = float(self.metadata[C_PLUGIN_SETTINGS][P_YT_DEF_VOL])
     YH.max_queue_size = int(self.metadata[C_PLUGIN_SETTINGS][P_YT_MAX_QUE_LEN])
     YH.max_track_duration = int(self.metadata[C_PLUGIN_SETTINGS][P_YT_MAX_VID_LEN])
     YH.autoplay = self.metadata.getboolean(C_PLUGIN_SETTINGS, P_YT_AUTO_PLAY, fallback=True)
     YH.queue_instance = qh.QueueHandler(YH.max_queue_size)
     rprint(
         f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized.")
Ejemplo n.º 10
0
 def __init__(self):
     super().__init__()
     from json import loads
     self.plugin_name = os.path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     self.is_running = True
     dir_utils.make_directory(f'{gs.cfg[C_MEDIA_SETTINGS][P_TEMP_MED_DIR]}/{self.plugin_name}/')
     dir_utils.clear_directory(f'{dir_utils.get_temp_med_dir()}/{self.plugin_name}')
     warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
     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
     )
Ejemplo n.º 11
0
 def __init__(self):
     super().__init__()
     from json import loads
     self.plugin_name = path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     self.is_running = True
     dir_utils.make_directory(f'{gs.cfg[C_MEDIA_SETTINGS][P_PERM_MEDIA_DIR]}/{self.plugin_name}/')
     dir_utils.make_directory(f'{gs.cfg[C_MEDIA_SETTINGS][P_TEMP_MED_DIR]}/{self.plugin_name}/')
     sbu_settings.sound_board_metadata = self.metadata
     sbu_settings.plugin_name = self.plugin_name
     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
     )
Ejemplo n.º 12
0
 def __init__(self):
     from json import loads
     super().__init__()
     self.plugin_name = os.path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(
         f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(
         self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     dir_utils.make_directory(
         f'{GS.cfg[C_MEDIA_DIR][P_PERM_MEDIA_DIR]}/{self.plugin_name}/')
     dir_utils.make_directory(
         f'{GS.cfg[C_MEDIA_DIR][P_TEMP_MED_DIR]}/{self.plugin_name}/')
     tts_settings.tts_metadata = self.metadata
     tts_settings.voice_list = loads(
         self.metadata.get(C_PLUGIN_SETTINGS, P_TTS_ALL_VOICE))
     rprint(
         f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized."
     )
Ejemplo n.º 13
0
 def __init__(self):
     super().__init__()
     from json import loads
     self.plugin_name = os.path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(
         f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(
         self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     dir_utils.make_directory(
         f'{gs.cfg[C_MEDIA_SETTINGS][P_TEMP_MED_DIR]}/{self.plugin_name}/')
     dir_utils.clear_directory(
         f'{dir_utils.get_temp_med_dir()}/{self.plugin_name}')
     warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
     md_settings.youtube_metadata = self.metadata
     md_settings.plugin_name = self.plugin_name
     self.register_callbacks()
     rprint(
         f"{self.metadata[C_PLUGIN_INFO][P_PLUGIN_NAME]} v{self.metadata[C_PLUGIN_INFO][P_PLUGIN_VERS]} Plugin Initialized."
     )
Ejemplo n.º 14
0
 def __init__(self):
     super().__init__()
     from json import loads
     self.plugin_name = path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(f'plugins/core/{self.plugin_name}')
     self.plugin_cmds = loads(self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     dir_utils.make_directory(f'{gs.cfg[C_MEDIA_SETTINGS][P_PERM_MEDIA_DIR]}/{self.plugin_name}/')
     dir_utils.make_directory(f'{gs.cfg[C_MEDIA_SETTINGS][P_TEMP_MED_DIR]}/{self.plugin_name}/')
     self.is_running = True
     st_settings.server_tools_metadata = self.metadata
     st_settings.plugin_name = self.plugin_name
     if not st_utility.create_empty_user_connections():
         self.quit()
     self.register_callbacks()
     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
     )
Ejemplo n.º 15
0
 def __init__(self):
     super().__init__()
     from os import path, makedirs
     from json import loads
     import shutil
     import errno
     self.plugin_name = path.basename(__file__).rsplit('.')[0]
     self.metadata = PluginUtilityService.process_metadata(
         f'plugins/extensions/{self.plugin_name}')
     self.plugin_cmds = loads(
         self.metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
     # Copy over monster_images directory to the permanent media directory.
     try:
         if not path.exists(
                 path.join(dir_utils.get_perm_med_dir(), 'mhw_wiki')):
             makedirs(path.join(dir_utils.get_perm_med_dir(), 'mhw_wiki'))
     except FileExistsError:
         pass
     try:
         shutil.copytree(
             path.join(path.dirname(__file__), 'resources/monster_images'),
             path.join(dir_utils.get_perm_med_dir(), 'mhw_wiki'))
     except OSError as e:
         if e.errno == errno.EEXIST:
             from distutils.dir_util import copy_tree
             copy_tree(
                 path.join(path.dirname(__file__),
                           'resources/monster_images'),
                 path.join(dir_utils.get_perm_med_dir(), 'mhw_wiki'))
     # Initialize database definitions
     self.mhw_db = sqlite3.connect(
         path.join(path.dirname(__file__), 'resources/mhw.db'))
     self.img_path = path.join(path.dirname(__file__),
                               'resources/monster_images')
     self.mhw_cursor = self.mhw_db.cursor()
     self.monster_definitions = define_all_monsters(self.mhw_cursor,
                                                    self.img_path)
     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)
Ejemplo n.º 16
0
 def cmd_setdefaultconnectionsound(self, data):
     all_data = data.message.strip().split(' ', 1)
     data_actor = gs.mumble_inst.users[data.actor]
     if len(all_data) != 2:
         gs.gui_service.quick_gui(
             f"Incorrect Formatting!"
             f"<br>Format: {get_command_token()}setdefaultconnectionsound 'audio_clip_name'",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
         return
     audio_clip_name = all_data[1]
     if not find_file(audio_clip_name):
         gs.gui_service.quick_gui(
             f"{audio_clip_name} is not one of the available files in the sound board permanent directory.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
         return
     self.metadata[C_PLUGIN_SET][
         P_GENERIC_CLIP_TO_PLAY_ON_USER_JOIN] = audio_clip_name
     try:
         with open(
                 f'{dir_utils.get_main_dir()}/plugins/extensions/{self.plugin_name}/metadata.ini',
                 'w') as metadata_file:
             self.metadata.write(metadata_file)
         self.metadata = PluginUtilityService.process_metadata(
             f'plugins/extensions/{self.plugin_name}')
         gs.gui_service.quick_gui(
             f"Updated the default user connection sound and saved the {self.plugin_name} metadata to the metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
     except IOError:
         gs.gui_service.quick_gui(
             f"There was an error saving the {self.plugin_name} metadata to the metadata.ini file.",
             text_type='header',
             box_align='left',
             user=data_actor['name'])
         return
Ejemplo n.º 17
0
    def initialize_plugins():
        import sys
        from os import path, listdir
        from json import loads

        # Clear plugins, plugins_help, and commands tables on launch.
        DeleteDB.delete_all_commands(db_conn=get_memory_db())
        DeleteDB.delete_all_plugins_help(db_conn=get_memory_db())
        DeleteDB.delete_all_plugins(db_conn=get_memory_db())

        # 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 listdir(f'{dir_utils.get_main_dir()}/plugins/core')
            if path.isdir(
                path.join(f'{dir_utils.get_main_dir()}/plugins/core', name))
            and name != "__pycache__"
        ]
        for p_file in all_imports:
            if not path.exists(
                    f'{dir_utils.get_main_dir()}/plugins/core/{p_file}/metadata.ini'
            ):
                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 class.
            global_settings.bot_plugins[p_file] = __import__(
                f'{p_file}.{p_file}', fromlist=['*']).Plugin

            # Register plugin command callbacks.
            plugin_metadata = PluginUtilityService.process_metadata(
                f'plugins/core/{p_file}')
            plugin_cmds = loads(
                plugin_metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
            for plugin_command in plugin_cmds:
                global_settings.cmd_callbacks.register_command(
                    f'{plugin_command}', p_file, f'{plugin_command}_clbk')
                global_settings.mtd_callbacks.register_callback(
                    f'{plugin_command}_clbk',
                    getattr(global_settings.bot_plugins[p_file],
                            f'cmd_{plugin_command}', None))
                dprint(
                    f"Registered plugin command: "
                    f"{plugin_command}:{global_settings.cmd_callbacks.get_command(plugin_command)[1]}:cmd_{plugin_command}"
                )
            # Initialize the core plugin class instance.
            global_settings.bot_plugins[p_file] = global_settings.bot_plugins[
                p_file]()

            # 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 listdir(
                f'{dir_utils.get_main_dir()}/plugins/extensions')
            if path.isdir(
                path.join(f'{dir_utils.get_main_dir()}/plugins/extensions',
                          name)) and name != "__pycache__"
        ]
        for p_file in all_imports:
            if not path.exists(
                    f'{dir_utils.get_main_dir()}/plugins/extensions/{p_file}/metadata.ini'
            ):
                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 class.
            global_settings.bot_plugins[p_file] = __import__(
                f'{p_file}.{p_file}', fromlist=['*']).Plugin

            # Register plugin command callbacks.
            plugin_metadata = PluginUtilityService.process_metadata(
                f'plugins/extensions/{p_file}')
            plugin_cmds = loads(
                plugin_metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
            for plugin_command in plugin_cmds:
                global_settings.cmd_callbacks.register_command(
                    f'{plugin_command}', p_file, f'{plugin_command}_clbk')
                global_settings.mtd_callbacks.register_callback(
                    f'{plugin_command}_clbk',
                    getattr(global_settings.bot_plugins[p_file],
                            f'cmd_{plugin_command}', None))
                dprint(
                    f"Registered plugin command: "
                    f"{plugin_command}:{global_settings.cmd_callbacks.get_command(plugin_command)[1]}:cmd_{plugin_command}"
                )
            # Initialize the core plugin class instance.
            global_settings.bot_plugins[p_file] = global_settings.bot_plugins[
                p_file]()
            # 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 #########")
Ejemplo n.º 18
0
    def initialize_plugins_safe():
        import sys
        from os import path, listdir
        from json import loads
        from JJMumbleBot.lib.resources.strings import C_PLUGIN_SETTINGS, P_PLUG_SAFE
        from hashlib import md5
        if not global_settings.cfg:
            from JJMumbleBot.lib.errors import ExitCodes, ConfigError
            from JJMumbleBot.lib.utils import runtime_utils
            runtime_utils.exit_bot_error(ExitCodes.CONFIG_ERROR)
            raise ConfigError(
                'There was an error loading the global config for initializing safe mode plugins.'
            )

        # Check database metadata for changes.
        # If the version is different, or plugin checksum is modified,
        # clear plugins, plugins_help, and commands tables on launch.
        if global_settings.cfg.getboolean(C_MAIN_SETTINGS,
                                          P_DB_INTEGRITY,
                                          fallback=True):
            log(INFO,
                "######### Checking Database Integrity",
                origin=L_STARTUP,
                print_mode=PrintMode.REG_PRINT.value)

            all_core_plugins = [
                name
                for name in listdir(f'{dir_utils.get_main_dir()}/plugins/core')
                if path.isdir(
                    path.join(f'{dir_utils.get_main_dir()}/plugins/core',
                              name)) and name != "__pycache__"
            ]
            all_ext_plugins = [
                name for name in listdir(
                    f'{dir_utils.get_main_dir()}/plugins/extensions')
                if path.isdir(
                    path.join(f'{dir_utils.get_main_dir()}/plugins/extensions',
                              name)) and name != "__pycache__"
            ]

            filenames = []
            for core_plugin in all_core_plugins:
                glob_files = glob.glob(
                    f'{dir_utils.get_main_dir()}/plugins/core/{core_plugin}/**/*',
                    recursive=True)
                glob_files = [
                    f for f in glob_files
                    if path.isfile(f) and "__pycache__" not in f
                ]
                filenames.extend(glob_files)
            for ext_plugin in all_ext_plugins:
                glob_files = glob.glob(
                    f'{dir_utils.get_main_dir()}/plugins/extensions/{ext_plugin}/**/*',
                    recursive=True)
                glob_files = [
                    f for f in glob_files
                    if path.isfile(f) and "__pycache__" not in f
                ]
                filenames.extend(glob_files)

            hash_func = md5()  # nosec
            for fn in filenames:
                if path.isfile(fn):
                    hash_func.update(open(fn, "rb").read())
            plugins_checksum = hash_func.hexdigest()

            integrity_check = UtilityDB.check_database_metadata(
                db_conn=get_memory_db(),
                version=META_VERSION,
                plugins_checksum=plugins_checksum)
            if integrity_check is False:
                log(WARNING,
                    "Database integrity mismatch identified! Creating database backup and rebuilding database...",
                    origin=L_STARTUP,
                    print_mode=PrintMode.REG_PRINT.value)
                db_backup = BotServiceHelper.backup_database()
                if db_backup:
                    log(INFO,
                        f"Created internal database backup @ {db_backup}",
                        origin=L_DATABASE,
                        print_mode=PrintMode.REG_PRINT.value)
                DeleteDB.delete_all_commands(db_conn=get_memory_db())
                DeleteDB.delete_all_plugins_help(db_conn=get_memory_db())
                DeleteDB.delete_all_plugins(db_conn=get_memory_db())

            log(INFO,
                "######### Database Integrity Verified",
                origin=L_STARTUP,
                print_mode=PrintMode.REG_PRINT.value)

        # Import custom aliases into the database.
        log(INFO,
            "######### Importing Custom Aliases",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)
        UtilityDB.import_aliases_to_db(
            db_conn=get_memory_db(),
            csv_path=f'{dir_utils.get_main_dir()}/cfg/custom_aliases.csv',
            update_if_exists=False)
        log(INFO,
            "######### Imported Custom Aliases",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)

        # Import custom command permissions into the database.
        log(INFO,
            "######### Importing Custom Command Permissions",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)
        UtilityDB.import_privileges_to_db(
            db_conn=get_memory_db(),
            csv_path=f'{dir_utils.get_main_dir()}/cfg/custom_permissions.csv',
            update_if_exists=False)
        log(INFO,
            "######### Imported Custom Command Permissions",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)

        # Import custom user privileges into the database.
        log(INFO,
            "######### Importing Custom User Privileges",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)
        UtilityDB.import_user_privileges_to_db(
            db_conn=get_memory_db(),
            csv_path=
            f'{dir_utils.get_main_dir()}/cfg/custom_user_privileges.csv',
            update_if_exists=False)
        log(INFO,
            "######### Imported Custom User Privileges",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)

        global_settings.bot_plugins = {}
        safe_mode_plugins = loads(
            global_settings.cfg.get(C_PLUGIN_SETTINGS, P_PLUG_SAFE))

        # Load Core Plugins
        log(INFO,
            "######### Initializing Core Plugins - Safe Mode",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)
        sys.path.insert(0, f'{dir_utils.get_main_dir()}/plugins/core')
        all_imports = [
            name
            for name in listdir(f'{dir_utils.get_main_dir()}/plugins/core')
            if path.isdir(
                path.join(f'{dir_utils.get_main_dir()}/plugins/core', name))
            and name != "__pycache__"
        ]
        for p_file in all_imports:
            if p_file in safe_mode_plugins:
                if not path.exists(
                        f'{dir_utils.get_main_dir()}/plugins/core/{p_file}/metadata.ini'
                ):
                    log(WARNING,
                        f"{p_file} plugin does not contain a metadata.ini file. Skipping initialization...",
                        origin=L_STARTUP,
                        print_mode=PrintMode.REG_PRINT.value)
                    continue
                # Import the core plugin class.
                global_settings.bot_plugins[p_file] = __import__(
                    f'{p_file}.{p_file}', fromlist=['*']).Plugin

                # Register plugin command callbacks.
                plugin_metadata = PluginUtilityService.process_metadata(
                    f'plugins/core/{p_file}')
                plugin_cmds = loads(
                    plugin_metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
                for plugin_command in plugin_cmds:
                    global_settings.cmd_callbacks.register_command(
                        f'{plugin_command}', p_file, f'{plugin_command}_clbk')
                    global_settings.mtd_callbacks.register_callback(
                        f'{plugin_command}_clbk',
                        getattr(global_settings.bot_plugins[p_file],
                                f'cmd_{plugin_command}', None))
                    log(INFO,
                        f"Registered plugin command: {plugin_command}:{global_settings.cmd_callbacks.get_command(plugin_command)[1]}:cmd_{plugin_command}",
                        origin=L_STARTUP,
                        print_mode=PrintMode.VERBOSE_PRINT.value)
                # Initialize the core plugin class instance.
                global_settings.bot_plugins[
                    p_file] = global_settings.bot_plugins[p_file]()
                # 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'
                )
                # Create directory for user modifiable plugin-specific data and configs.
                dir_utils.make_directory(
                    f'{dir_utils.get_plugin_data_dir()}/{p_file}')
        sys.path.pop(0)
        log(INFO,
            "######### Core Plugins Initialized - Safe Mode",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)

        # Load Extension Plugins
        log(INFO,
            "######### Initializing Extension Plugins - Safe Mode",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)
        sys.path.insert(0, f'{dir_utils.get_main_dir()}/plugins/extensions')
        all_imports = [
            name for name in listdir(
                f'{dir_utils.get_main_dir()}/plugins/extensions')
            if path.isdir(
                path.join(f'{dir_utils.get_main_dir()}/plugins/extensions',
                          name)) and name != "__pycache__"
        ]
        for p_file in all_imports:
            if p_file in safe_mode_plugins:
                if not path.exists(
                        f'{dir_utils.get_main_dir()}/plugins/extensions/{p_file}/metadata.ini'
                ):
                    log(WARNING,
                        f"{p_file} plugin does not contain a metadata.ini file. Skipping initialization...",
                        origin=L_STARTUP,
                        print_mode=PrintMode.REG_PRINT.value)
                    continue
                # Import the core plugin class.
                global_settings.bot_plugins[p_file] = __import__(
                    f'{p_file}.{p_file}', fromlist=['*']).Plugin

                # Register plugin command callbacks.
                plugin_metadata = PluginUtilityService.process_metadata(
                    f'plugins/extensions/{p_file}')
                plugin_cmds = loads(
                    plugin_metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
                for plugin_command in plugin_cmds:
                    global_settings.cmd_callbacks.register_command(
                        f'{plugin_command}', p_file, f'{plugin_command}_clbk')
                    global_settings.mtd_callbacks.register_callback(
                        f'{plugin_command}_clbk',
                        getattr(global_settings.bot_plugins[p_file],
                                f'cmd_{plugin_command}', None))
                    log(INFO,
                        f"Registered plugin command: {plugin_command}:{global_settings.cmd_callbacks.get_command(plugin_command)[1]}:cmd_{plugin_command}",
                        origin=L_STARTUP,
                        print_mode=PrintMode.VERBOSE_PRINT.value)
                # Initialize the core plugin class instance.
                global_settings.bot_plugins[
                    p_file] = global_settings.bot_plugins[p_file]()
                # 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'
                )
                # Create directory for user modifiable plugin-specific data and configs.
                dir_utils.make_directory(
                    f'{dir_utils.get_plugin_data_dir()}/{p_file}')
        save_memory_db_to_file()
        sys.path.pop(0)
        log(INFO,
            "######### Extension Plugins Initialized - Safe Mode",
            origin=L_STARTUP,
            print_mode=PrintMode.REG_PRINT.value)
Ejemplo n.º 19
0
    def initialize_plugins_safe():
        import sys
        from os import path, listdir
        from json import loads
        from JJMumbleBot.lib.resources.strings import C_PLUGIN_SETTINGS, P_PLUG_SAFE
        if not global_settings.cfg:
            from JJMumbleBot.lib.errors import ExitCodes, ConfigError
            from JJMumbleBot.lib.utils import runtime_utils
            runtime_utils.exit_bot_error(ExitCodes.CONFIG_ERROR)
            raise ConfigError(
                'There was an error loading the global config for initializing safe mode plugins.'
            )

        # 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 = {}
        safe_mode_plugins = loads(
            global_settings.cfg.get(C_PLUGIN_SETTINGS, P_PLUG_SAFE))
        # Load Core Plugins
        rprint("######### Initializing Core Plugins - Safe Mode #########")
        sys.path.insert(0, f'{dir_utils.get_main_dir()}/plugins/core')
        all_imports = [
            name
            for name in listdir(f'{dir_utils.get_main_dir()}/plugins/core')
            if path.isdir(
                path.join(f'{dir_utils.get_main_dir()}/plugins/core', name))
            and name != "__pycache__"
        ]
        for p_file in all_imports:
            if p_file in safe_mode_plugins:
                if not path.exists(
                        f'{dir_utils.get_main_dir()}/plugins/core/{p_file}/metadata.ini'
                ):
                    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 class.
                global_settings.bot_plugins[p_file] = __import__(
                    f'{p_file}.{p_file}', fromlist=['*']).Plugin

                # Register plugin command callbacks.
                plugin_metadata = PluginUtilityService.process_metadata(
                    f'plugins/core/{p_file}')
                plugin_cmds = loads(
                    plugin_metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
                for plugin_command in plugin_cmds:
                    global_settings.cmd_callbacks.register_command(
                        f'{plugin_command}', p_file, f'{plugin_command}_clbk')
                    global_settings.mtd_callbacks.register_callback(
                        f'{plugin_command}_clbk',
                        getattr(global_settings.bot_plugins[p_file],
                                f'cmd_{plugin_command}', None))
                    dprint(
                        f"Registered plugin command: "
                        f"{plugin_command}:{global_settings.cmd_callbacks.get_command(plugin_command)[1]}:cmd_{plugin_command}"
                    )
                # Initialize the core plugin class instance.
                global_settings.bot_plugins[
                    p_file] = global_settings.bot_plugins[p_file]()
                # 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'
                )
        # help_plugin = __import__('help.help')
        # self.bot_plugins['help'] = help_plugin.help.Plugin(self.bot_plugins)
        sys.path.pop(0)
        rprint("######### Core Plugins Initialized - Safe Mode #########")
        # Load Extension Plugins
        rprint(
            "######### Initializing Extension Plugins - Safe Mode #########")
        sys.path.insert(0, f'{dir_utils.get_main_dir()}/plugins/extensions')
        all_imports = [
            name for name in listdir(
                f'{dir_utils.get_main_dir()}/plugins/extensions')
            if path.isdir(
                path.join(f'{dir_utils.get_main_dir()}/plugins/extensions',
                          name)) and name != "__pycache__"
        ]
        for p_file in all_imports:
            if p_file in safe_mode_plugins:
                if not path.exists(
                        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 class.
                global_settings.bot_plugins[p_file] = __import__(
                    f'{p_file}.{p_file}', fromlist=['*']).Plugin

                # Register plugin command callbacks.
                plugin_metadata = PluginUtilityService.process_metadata(
                    f'plugins/core/{p_file}')
                plugin_cmds = loads(
                    plugin_metadata.get(C_PLUGIN_INFO, P_PLUGIN_CMDS))
                for plugin_command in plugin_cmds:
                    global_settings.cmd_callbacks.register_command(
                        f'{plugin_command}', p_file, f'{plugin_command}_clbk')
                    global_settings.mtd_callbacks.register_callback(
                        f'{plugin_command}_clbk',
                        getattr(global_settings.bot_plugins[p_file],
                                f'cmd_{plugin_command}', None))
                    dprint(
                        f"Registered plugin command: "
                        f"{plugin_command}:{global_settings.cmd_callbacks.get_command(plugin_command)[1]}:cmd_{plugin_command}"
                    )
                # Initialize the core plugin class instance.
                global_settings.bot_plugins[
                    p_file] = global_settings.bot_plugins[p_file]()
                # 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 - Safe Mode #########")