Extract hooks

This commit is contained in:
nemunaire 2015-04-17 08:43:03 +02:00 committed by nemunaire
parent c8d495d508
commit 002f2463a3
9 changed files with 104 additions and 76 deletions

View File

@ -22,8 +22,9 @@ def load(context):
"http://developer.mapquest.com/") "http://developer.mapquest.com/")
return None return None
from nemubot.hooks.messagehook import MessageHook import nemubot.hooks
context.add_hook("cmd_hook", MessageHook(cmd_geocode, "geocode")) context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_geocode, "geocode"))
def help_full(): def help_full():

View File

@ -19,8 +19,8 @@ def load(CONF, add_hook):
else: else:
URL_WHOIS = URL_WHOIS % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"])) URL_WHOIS = URL_WHOIS % (urllib.parse.quote(CONF.getNode("whoisxmlapi")["username"]), urllib.parse.quote(CONF.getNode("whoisxmlapi")["password"]))
from nemubot.hooks.messagehook import MessageHook import nemubot.hooks
add_hook("cmd_hook", MessageHook(cmd_whois, "netwhois")) add_hook("cmd_hook", nemubot.hooks.Message(cmd_whois, "netwhois"))
def extractdate(str): def extractdate(str):

View File

@ -23,8 +23,8 @@ def load(context):
else: else:
URL_TPBAPI = context.config.getNode("tpbapi")["url"] URL_TPBAPI = context.config.getNode("tpbapi")["url"]
from nemubot.hooks.messagehook import MessageHook from nemubot.hooks.message import Message
context.add_hook("cmd_hook", MessageHook(cmd_tpb, "tpb")) context.add_hook("cmd_hook", Message(cmd_tpb, "tpb"))
def cmd_tpb(msg): def cmd_tpb(msg):

View File

@ -28,8 +28,9 @@ def load(context):
else: else:
URL = URL % context.config.getNode("wrapi")["key"] URL = URL % context.config.getNode("wrapi")["key"]
from nemubot.hooks.messagehook import MessageHook import nemubot.hooks
context.add_hook("cmd_hook", MessageHook(cmd_translate, "translate")) context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_translate, "translate"))
def help_full(): def help_full():

View File

@ -29,10 +29,13 @@ def load(context):
"http://developer.forecast.io/") "http://developer.forecast.io/")
return None return None
from nemubot.hooks.messagehook import MessageHook import nemubot.hooks
context.add_hook("cmd_hook", MessageHook(cmd_weather, "météo")) context.add_hook("cmd_hook",
context.add_hook("cmd_hook", MessageHook(cmd_alert, "alert")) nemubot.hooks.Message(cmd_weather, "météo"))
context.add_hook("cmd_hook", MessageHook(cmd_coordinates, "coordinates")) context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_alert, "alert"))
context.add_hook("cmd_hook",
nemubot.hooks.Message(cmd_coordinates, "coordinates"))
def help_full (): def help_full ():

View File

@ -23,7 +23,7 @@ import threading
from nemubot import __version__ from nemubot import __version__
from nemubot.consumer import Consumer, EventConsumer, MessageConsumer from nemubot.consumer import Consumer, EventConsumer, MessageConsumer
from nemubot import datastore from nemubot import datastore
from nemubot.hooks.messagehook import MessageHook import nemubot.hooks
from nemubot.modulecontext import ModuleContext from nemubot.modulecontext import ModuleContext
logger = logging.getLogger("nemubot") logger = logging.getLogger("nemubot")
@ -75,7 +75,7 @@ class Bot(threading.Thread):
def in_ping(msg): def in_ping(msg):
if re.match("^ *(m[' ]?entends?[ -]+tu|h?ear me|do you copy|ping)", msg.message, re.I) is not None: if re.match("^ *(m[' ]?entends?[ -]+tu|h?ear me|do you copy|ping)", msg.message, re.I) is not None:
return msg.respond("pong") return msg.respond("pong")
self.hooks.add_hook(MessageHook(in_ping), "in", "DirectAsk") self.hooks.add_hook(nemubot.hooks.Message(in_ping), "in", "DirectAsk")
def _help_msg(msg): def _help_msg(msg):
"""Parse and response to help messages""" """Parse and response to help messages"""
@ -111,7 +111,7 @@ class Bot(threading.Thread):
" de tous les modules disponibles localement", " de tous les modules disponibles localement",
message=["\x03\x02%s\x03\x02 (%s)" % (im, self.modules[im].__doc__) for im in self.modules if self.modules[im].__doc__]) message=["\x03\x02%s\x03\x02 (%s)" % (im, self.modules[im].__doc__) for im in self.modules if self.modules[im].__doc__])
return res return res
self.hooks.add_hook(MessageHook(_help_msg, "help"), "in", "Command") self.hooks.add_hook(nemubot.hooks.Message(_help_msg, "help"), "in", "Command")
# Messages to be treated # Messages to be treated
from queue import Queue from queue import Queue

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Nemubot is a smart and modulable IM bot. # Nemubot is a smart and modulable IM bot.
# Copyright (C) 2012-2015 Mercier Pierre-Olivier # Copyright (C) 2012-2015 Mercier Pierre-Olivier
# #
@ -16,55 +14,8 @@
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
def call_game(call, *args, **kargs): from nemubot.hooks.abstract import Abstract
"""TODO""" from nemubot.hooks.message import Message
l = list()
d = kargs
for a in args:
if a is not None:
if isinstance(a, dict):
d.update(a)
else:
l.append(a)
return call(*l, **d)
class AbstractHook:
"""Abstract class for Hook implementation"""
def __init__(self, call, data=None, mtimes=-1, end_call=None):
self.call = call
self.data = data
self.times = mtimes
self.end_call = end_call
def match(self, data1, server):
return NotImplemented
def run(self, data1, *args):
"""Run the hook"""
from nemubot.exception import IRCException
self.times -= 1
try:
ret = call_game(self.call, data1, self.data, *args)
except IRCException as e:
ret = e.fill_response(data1)
finally:
if self.times == 0:
self.call_end(ret)
return ret
from nemubot.hooks.messagehook import MessageHook
last_registered = [] last_registered = []
@ -72,16 +23,21 @@ last_registered = []
def hook(store, *args, **kargs): def hook(store, *args, **kargs):
"""Function used as a decorator for module loading""" """Function used as a decorator for module loading"""
def sec(call): def sec(call):
last_registered.append((store, MessageHook(call, *args, **kargs))) last_registered.append((store, Message(call, *args, **kargs)))
return call return call
return sec return sec
def reload(): def reload():
global Abstract, Message
import imp import imp
import nemubot.hooks.abstract
imp.reload(nemubot.hooks.abstract)
Abstract = nemubot.hooks.abstract.Abstract
import nemubot.hooks.message
imp.reload(nemubot.hooks.message)
Message = nemubot.hooks.message.Message
import nemubot.hooks.manager import nemubot.hooks.manager
imp.reload(nemubot.hooks.manager) imp.reload(nemubot.hooks.manager)
import nemubot.hooks.messagehook
imp.reload(nemubot.hooks.messagehook)

69
nemubot/hooks/abstract.py Normal file
View File

@ -0,0 +1,69 @@
# Nemubot is a smart and modulable IM bot.
# Copyright (C) 2012-2015 Mercier Pierre-Olivier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def call_game(call, *args, **kargs):
"""With given args, try to determine the right call to make
Arguments:
call -- the function to call
*args -- unamed arguments to pass, dictionnaries contains are placed into kargs
**kargs -- named arguments
"""
l = list()
d = kargs
for a in args:
if a is not None:
if isinstance(a, dict):
d.update(a)
else:
l.append(a)
return call(*l, **d)
class Abstract:
"""Abstract class for Hook implementation"""
def __init__(self, call, data=None, mtimes=-1, end_call=None):
self.call = call
self.data = data
self.times = mtimes
self.end_call = end_call
def match(self, data1, server):
return NotImplemented
def run(self, data1, *args):
"""Run the hook"""
from nemubot.exception import IRCException
self.times -= 1
try:
ret = call_game(self.call, data1, self.data, *args)
except IRCException as e:
ret = e.fill_response(data1)
finally:
if self.times == 0:
self.call_end(ret)
return ret

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Nemubot is a smart and modulable IM bot. # Nemubot is a smart and modulable IM bot.
# Copyright (C) 2012-2015 Mercier Pierre-Olivier # Copyright (C) 2012-2015 Mercier Pierre-Olivier
# #
@ -18,19 +16,19 @@
import re import re
from nemubot.hooks import AbstractHook from nemubot.hooks.abstract import Abstract
import nemubot.message import nemubot.message
class MessageHook(AbstractHook): class Message(Abstract):
"""Class storing hook information, specialized for a generic Message""" """Class storing hook information, specialized for a generic Message"""
def __init__(self, call, name=None, data=None, regexp=None, def __init__(self, call, name=None, data=None, regexp=None,
channels=list(), server=None, mtimes=-1, end_call=None): channels=list(), server=None, mtimes=-1, end_call=None):
AbstractHook.__init__(self, call=call, data=data, Abstract.__init__(self, call=call, data=data,
end_call=end_call, mtimes=mtimes) end_call=end_call, mtimes=mtimes)
self.name = name self.name = name
self.regexp = regexp self.regexp = regexp