events: ModuleEvent don't store function argument anymore

This commit is contained in:
nemunaire 2018-12-30 00:42:21 +01:00
parent 8605932702
commit b349d22370
4 changed files with 23 additions and 66 deletions

View File

@ -1,5 +1,6 @@
"""Alert on changes on websites"""
from functools import partial
import logging
from random import randint
import urllib.parse
@ -209,15 +210,14 @@ def start_watching(site, offset=0):
offset -- offset time to delay the launch of the first check
"""
o = urlparse(getNormalizedURL(site["url"]), "http")
#print_debug("Add %s event for site: %s" % (site["type"], o.netloc))
#o = urlparse(getNormalizedURL(site["url"]), "http")
#print("Add %s event for site: %s" % (site["type"], o.netloc))
try:
evt = ModuleEvent(func=fwatch,
cmp_data=site["lastcontent"],
func_data=site["url"], offset=offset,
interval=site.getInt("time"),
call=alert_change, call_data=site)
evt = ModuleEvent(func=partial(fwatch, url=site["url"]),
cmp=site["lastcontent"],
offset=offset, interval=site.getInt("time"),
call=partial(alert_change, site=site))
site["_evt_id"] = add_event(evt)
except IMException:
logger.exception("Unable to watch %s", site["url"])

View File

@ -4,6 +4,7 @@
import email
from email.utils import mktime_tz, parseaddr, parsedate_tz
from functools import partial
from nntplib import NNTP, decode_header
import re
import time
@ -89,7 +90,7 @@ def _indexServer(**kwargs):
return "{user}:{password}@{host}:{port}".format(**kwargs)
def _newevt(**args):
context.add_event(ModuleEvent(call=_fini, call_data=args, interval=42))
context.add_event(ModuleEvent(call=partial(_fini, **args), interval=42))
def _fini(to_server, to_channel, lastcheck, group, server):
print("fini called")

View File

@ -3,6 +3,7 @@
"""The 2014,2018 football worldcup module"""
from datetime import datetime, timezone
from functools import partial
import json
import re
from urllib.parse import quote
@ -21,7 +22,7 @@ from nemubot.module.more import Response
API_URL="http://worldcup.sfg.io/%s"
def load(context):
context.add_event(ModuleEvent(func=lambda url: urlopen(url, timeout=10).read().decode(), func_data=API_URL % "matches/current?by_date=DESC", call=current_match_new_action, interval=30))
context.add_event(ModuleEvent(func=partial(lambda url: urlopen(url, timeout=10).read().decode(), API_URL % "matches/current?by_date=DESC"), call=current_match_new_action, interval=30))
def help_full ():
@ -65,10 +66,10 @@ def cmd_watch(msg):
context.save()
raise IMException("This channel will not anymore receives world cup events.")
def current_match_new_action(matches, osef):
def current_match_new_action(matches):
def cmp(om, nm):
return len(nm) and (len(om) == 0 or len(nm[0]["home_team_events"]) != len(om[0]["home_team_events"]) or len(nm[0]["away_team_events"]) != len(om[0]["away_team_events"]))
context.add_event(ModuleEvent(func=lambda url: json.loads(urlopen(url).read().decode()), func_data=API_URL % "matches/current?by_date=DESC", cmp=cmp, call=current_match_new_action, interval=30))
context.add_event(ModuleEvent(func=partial(lambda url: json.loads(urlopen(url).read().decode()), API_URL % "matches/current?by_date=DESC"), cmp=partial(cmp, matches), call=current_match_new_action, interval=30))
for match in matches:
if is_valid(match):

View File

@ -21,18 +21,14 @@ class ModuleEvent:
"""Representation of a event initiated by a bot module"""
def __init__(self, call=None, call_data=None, func=None, func_data=None,
cmp=None, cmp_data=None, interval=60, offset=0, times=1):
def __init__(self, call=None, func=None, cmp=None, interval=60, offset=0, times=1):
"""Initialize the event
Keyword arguments:
call -- Function to call when the event is realized
call_data -- Argument(s) (single or dict) to pass as argument
func -- Function called to check
func_data -- Argument(s) (single or dict) to pass as argument OR if no func, initial data to watch
cmp -- Boolean function called to check changes
cmp_data -- Argument(s) (single or dict) to pass as argument OR if no cmp, data compared to previous
cmp -- Boolean function called to check changes or value to compare with
interval -- Time in seconds between each check (default: 60)
offset -- Time in seconds added to interval before the first check (default: 0)
times -- Number of times the event has to be realized before being removed; -1 for no limit (default: 1)
@ -40,27 +36,12 @@ class ModuleEvent:
# What have we to check?
self.func = func
self.func_data = func_data
# How detect a change?
self.cmp = cmp
self.cmp_data = None
if cmp_data is not None:
self.cmp_data = cmp_data
elif self.func is not None:
if self.func_data is None:
self.cmp_data = self.func()
elif isinstance(self.func_data, dict):
self.cmp_data = self.func(**self.func_data)
else:
self.cmp_data = self.func(self.func_data)
# What should we call when?
self.call = call
if call_data is not None:
self.call_data = call_data
else:
self.call_data = func_data
# Store times
if isinstance(offset, timedelta):
@ -106,44 +87,18 @@ class ModuleEvent:
def check(self):
"""Run a check and realized the event if this is time"""
# Get initial data
if self.func is None:
d_init = self.func_data
elif self.func_data is None:
d_init = self.func()
elif isinstance(self.func_data, dict):
d_init = self.func(**self.func_data)
# Get new data
if self.func is not None:
d_new = self.func()
else:
d_init = self.func(self.func_data)
d_new = None
# then compare with current data
if self.cmp is None:
if self.cmp_data is None:
rlz = True
else:
rlz = (d_init != self.cmp_data)
elif self.cmp_data is None:
rlz = self.cmp(d_init)
elif isinstance(self.cmp_data, dict):
rlz = self.cmp(d_init, **self.cmp_data)
else:
rlz = self.cmp(d_init, self.cmp_data)
if rlz:
if self.cmp is None or (callable(self.cmp) and self.cmp(d_new)) or (not callable(self.cmp) and d_new != self.cmp):
self.times -= 1
# Call attended function
if self.call_data is None:
if d_init is None:
self.call()
else:
self.call(d_init)
elif d_init is None:
if isinstance(self.call_data, dict):
self.call(**self.call_data)
else:
self.call(self.call_data)
elif isinstance(self.call_data, dict):
self.call(d_init, **self.call_data)
if self.func is not None:
self.call(d_new)
else:
self.call(d_init, self.call_data)
self.call()