Support hooking functions in modules with @Utils.hook
This commit is contained in:
parent
f3d8d35083
commit
b8aca72861
3 changed files with 29 additions and 4 deletions
|
@ -1,5 +1,7 @@
|
|||
import glob, imp, inspect, os, sys, uuid
|
||||
|
||||
BITBOT_HOOKS_MAGIC = "__bitbot_hooks"
|
||||
|
||||
class ModuleManager(object):
|
||||
def __init__(self, bot, events, exports, directory="modules"):
|
||||
self.bot = bot
|
||||
|
@ -51,10 +53,22 @@ class ModuleManager(object):
|
|||
raise ImportError("module '%s' has a Module attribute but it is not a class.")
|
||||
|
||||
context = str(uuid.uuid4())
|
||||
module_object = module.Module(self.bot, self.events.new_context(
|
||||
context), self.exports.new_context(context))
|
||||
context_events = self.events.new_context(context)
|
||||
context_exports = self.exports.new_context(context)
|
||||
module_object = module.Module(self.bot, context_events,
|
||||
context_exports)
|
||||
|
||||
if not hasattr(module_object, "_name"):
|
||||
module_object._name = name.title()
|
||||
for attribute_name in dir(module_object):
|
||||
attribute = getattr(module_object, attribute_name)
|
||||
if inspect.ismethod(attribute) and hasattr(attribute,
|
||||
BITBOT_HOOKS_MAGIC):
|
||||
hooks = getattr(attribute, BITBOT_HOOKS_MAGIC)
|
||||
for hook in hooks:
|
||||
context_events.on(hook["event"]).hook(attribute,
|
||||
**hook["kwargs"])
|
||||
|
||||
module_object._context = context
|
||||
module_object._import_name = name
|
||||
|
||||
|
|
10
Utils.py
10
Utils.py
|
@ -1,6 +1,7 @@
|
|||
import json, re, traceback, urllib.request, urllib.parse, urllib.error, ssl
|
||||
import string
|
||||
import bs4
|
||||
import ModuleManager
|
||||
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
|
||||
|
@ -275,3 +276,12 @@ def get_closest_setting(event, setting, default=None):
|
|||
|
||||
def prevent_highlight(nickname):
|
||||
return nickname[0]+"\u200d"+nickname[1:]
|
||||
|
||||
def hook(event, **kwargs):
|
||||
def _hook_func(func):
|
||||
if not hasattr(func, ModuleManager.BITBOT_HOOKS_MAGIC):
|
||||
setattr(func, ModuleManager.BITBOT_HOOKS_MAGIC, [])
|
||||
getattr(func, ModuleManager.BITBOT_HOOKS_MAGIC).append(
|
||||
{"event": event, "kwargs": kwargs})
|
||||
return func
|
||||
return _hook_func
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
|
||||
import Utils
|
||||
|
||||
class Module(object):
|
||||
def __init__(self, bot, events, exports):
|
||||
events.on("received.command.ping").hook(self.pong, help="Ping pong!")
|
||||
pass
|
||||
|
||||
@Utils.hook("received.command.ping", help="Ping pong!")
|
||||
def pong(self, event):
|
||||
event["stdout"].write("Pong!")
|
||||
|
|
Loading…
Reference in a new issue