Skip to content

Instantly share code, notes, and snippets.

@Cheaterman
Created January 5, 2022 21:20
Show Gist options
  • Save Cheaterman/ce4bb09df34bcb46de194a40f760a38d to your computer and use it in GitHub Desktop.
Save Cheaterman/ce4bb09df34bcb46de194a40f760a38d to your computer and use it in GitHub Desktop.
__init__.py
import importlib
import traceback
from samp import SendClientMessage
from .cmdparser import cmd, handle_command
from .callbacks import names
from .tms import admin_level
_loaded_modules = {}
_unloaded_modules = {}
def _handle_load_error(module_name, exception, playerid=None):
if playerid is not None:
SendClientMessage(
playerid,
0xFF0000FF,
f'ERROR: Unable to load module {module_name}: {exception!r}.'
)
print(f'Error loading module {module_name}:\n {traceback.format_exc()}')
def pyload(module_name, playerid=None):
if module_name not in _unloaded_modules:
try:
module = importlib.import_module(f'{__name__}.{module_name}')
except Exception as exception:
_handle_load_error(module_name, exception, playerid)
return
else:
module = _unloaded_modules[module_name]
try:
importlib.reload(module)
except Exception as exception:
_handle_load_error(module_name, exception, playerid)
return
else:
del _unloaded_modules[module_name]
_loaded_modules[module_name] = module
if hasattr(module, 'OnGameModeInit'):
getattr(module, 'OnGameModeInit')()
def pyunload(module_name):
_unloaded_modules[module_name] = module = _loaded_modules[module_name]
del _loaded_modules[module_name]
if hasattr(module, 'OnGameModeExit'):
getattr(module, 'OnGameModeExit')()
@cmd('pyload', requires=admin_level(6))
def cmd_pyload(playerid, module_name):
if module_name in _loaded_modules:
SendClientMessage(
playerid,
0xFF0000FF,
f'ERROR: Module {module_name} is already loaded.'
)
return
pyload(module_name, playerid)
SendClientMessage(
playerid,
0x00FFFFFF,
f'Module {module_name} successfully loaded.'
)
@cmd('pyunload', requires=admin_level(6))
def cmd_pyunload(playerid, module_name):
if module_name not in _loaded_modules:
SendClientMessage(
playerid,
0xFF0000FF,
f'ERROR: Module {module_name} is not currently loaded.'
)
return
pyunload(module_name)
SendClientMessage(
playerid,
0x00FFFFFF,
f'Module {module_name} successfully unloaded.'
)
@cmd('pyreload', requires=admin_level(6))
def cmd_pyreload(playerid, module_name):
cmd_pyunload(playerid, module_name)
cmd_pyload(playerid, module_name)
def OnGameModeInit():
# Load your own modules here using pyload('mymodule')
# instead of the usual import mymodule
...
for callback in names:
exec(f'''
def {callback}(*args, **kwargs):
for module in _loaded_modules.values():
if hasattr(module, '{callback}'):
getattr(module, '{callback}')(*args, **kwargs)
''')
def OnPlayerCommandText(playerid, text):
return handle_command(playerid, text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment