Skip to content

Commit 32b3095

Browse files
committed
Merge branch 'gonzobot' of github.com:edwardslabs/CloudBot into gonzobot
2 parents d940172 + 57505b9 commit 32b3095

5 files changed

Lines changed: 278 additions & 294 deletions

File tree

cloudbot/hook.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,6 @@ def _periodic_hook(func):
316316
return lambda func: _periodic_hook(func)
317317

318318

319-
320319
def on_start(param=None, **kwargs):
321320
"""External on_start decorator. Can be used directly as a decorator, or with args to return a decorator
322321
:type param: function | None
@@ -339,3 +338,22 @@ def _on_start_hook(func):
339338

340339
# this is temporary, to ease transition
341340
onload = on_start
341+
342+
343+
def on_stop(param=None, **kwargs):
344+
"""External on_stop decorator. Can be used directly as a decorator, or with args to return a decorator
345+
:type param: function | None
346+
"""
347+
def _on_stop_hook(func):
348+
hook = _get_hook(func, "on_stop")
349+
if hook is None:
350+
hook = _Hook(func, "on_stop")
351+
_add_hook(func, hook)
352+
hook._add_hook(kwargs)
353+
return func
354+
if callable(param):
355+
return _on_stop_hook(param)
356+
else:
357+
return lambda func: _on_stop_hook(func)
358+
359+
on_unload = on_stop

cloudbot/plugin.py

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def find_hooks(parent, module):
1818
"""
1919
:type parent: Plugin
2020
:type module: object
21-
:rtype: (list[CommandHook], list[RegexHook], list[RawHook], list[SieveHook], List[EventHook], list[OnStartHook])
21+
:rtype: (list[CommandHook], list[RegexHook], list[RawHook], list[SieveHook], List[EventHook], List[PeriodicHook], list[OnStartHook], List[OnStopHook])
2222
"""
2323
# set the loaded flag
2424
module._cloudbot_loaded = True
@@ -29,8 +29,9 @@ def find_hooks(parent, module):
2929
event = []
3030
periodic = []
3131
on_start = []
32+
on_stop = []
3233
type_lists = {"command": command, "regex": regex, "irc_raw": raw, "sieve": sieve, "event": event,
33-
"periodic": periodic, "on_start": on_start}
34+
"periodic": periodic, "on_start": on_start, "on_stop": on_stop}
3435
for name, func in module.__dict__.items():
3536
if hasattr(func, "_cloudbot_hook"):
3637
# if it has cloudbot hook
@@ -42,7 +43,7 @@ def find_hooks(parent, module):
4243
# delete the hook to free memory
4344
del func._cloudbot_hook
4445

45-
return command, regex, raw, sieve, event, periodic, on_start
46+
return command, regex, raw, sieve, event, periodic, on_start, on_stop
4647

4748

4849
def find_tables(code):
@@ -293,6 +294,11 @@ def unload_plugin(self, path):
293294
for sieve_hook in plugin.sieves:
294295
self.sieves.remove(sieve_hook)
295296

297+
# Run on_stop hooks
298+
for on_stop_hook in plugin.run_on_stop:
299+
event = Event(bot=self.bot, hook=on_stop_hook)
300+
yield from self.launch(on_stop_hook, event)
301+
296302
# unregister databases
297303
plugin.unregister_tables(self.bot)
298304

@@ -439,7 +445,7 @@ def launch(self, hook, event):
439445
:rtype: bool
440446
"""
441447

442-
if hook.type not in ("on_start", "periodic"): # we don't need sieves on on_start hooks.
448+
if hook.type not in ("on_start", "on_stop", "periodic"): # we don't need sieves on on_start hooks.
443449
for sieve in self.bot.plugin_manager.sieves:
444450
event = yield from self._sieve(sieve, event, hook)
445451
if event is None:
@@ -515,7 +521,7 @@ def __init__(self, filepath, filename, title, code):
515521
self.file_path = filepath
516522
self.file_name = filename
517523
self.title = title
518-
self.commands, self.regexes, self.raw_hooks, self.sieves, self.events, self.periodic, self.run_on_start = find_hooks(self, code)
524+
self.commands, self.regexes, self.raw_hooks, self.sieves, self.events, self.periodic, self.run_on_start, self.run_on_stop = find_hooks(self, code)
519525
# we need to find tables for each plugin so that they can be unloaded from the global metadata when the
520526
# plugin is reloaded
521527
self.tables = find_tables(code)
@@ -759,12 +765,24 @@ def __str__(self):
759765
return "on_start {} from {}".format(self.function_name, self.plugin.file_name)
760766

761767

768+
class OnStopHook(Hook):
769+
def __init__(self, plugin, on_stop_hook):
770+
super().__init__("on_stop", plugin, on_stop_hook)
771+
772+
def __repr__(self):
773+
return "On_stop[{}]".format(Hook.__repr__(self))
774+
775+
def __str__(self):
776+
return "on_stop {} from {}".format(self.function_name, self.plugin.file_name)
777+
778+
762779
_hook_name_to_plugin = {
763780
"command": CommandHook,
764781
"regex": RegexHook,
765782
"irc_raw": RawHook,
766783
"sieve": SieveHook,
767784
"event": EventHook,
768785
"periodic": PeriodicHook,
769-
"on_start": OnStartHook
786+
"on_start": OnStartHook,
787+
"on_stop": OnStopHook,
770788
}

plugins/grab.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,23 +17,21 @@
1717
Column('chan', String)
1818
)
1919

20+
grab_cache = {}
21+
22+
2023
@hook.on_start()
2124
def load_cache(db):
2225
"""
2326
:type db: sqlalchemy.orm.Session
2427
"""
25-
global grab_cache
26-
grab_cache = {}
28+
grab_cache.clear()
2729
for row in db.execute(table.select().order_by(table.c.time)):
2830
name = row["name"].lower()
2931
quote = row["quote"]
3032
chan = row["chan"]
31-
if chan not in grab_cache:
32-
grab_cache.update({chan:{name:[chan]}})
33-
elif name not in grab_cache[chan]:
34-
grab_cache[chan].update({name:[quote]})
35-
else:
36-
grab_cache[chan][name].append(quote)
33+
grab_cache.setdefault(chan, {}).setdefault(name, []).append(quote)
34+
3735

3836
def two_lines(bigstring, chan):
3937
"""Receives a string with new lines. Groups the string into a list of strings with up to 3 new lines per string element. Returns first string element then stores the remaining list in search_pages."""
@@ -61,7 +59,7 @@ def moregrab(text, chan):
6159
index = ""
6260
try:
6361
index = int(text)
64-
except:
62+
except ValueError:
6563
return "Please specify an integer value."
6664
if abs(int(index)) > len(search_pages[chan]) or index == 0:
6765
return "please specify a valid page number between 1 and {}.".format(len(search_pages[chan]))
@@ -74,15 +72,17 @@ def moregrab(text, chan):
7472
else:
7573
return "All pages have been shown you can specify a page number or do a new search."
7674

75+
7776
def check_grabs(name, quote, chan):
7877
try:
7978
if quote in grab_cache[chan][name]:
8079
return True
8180
else:
8281
return False
83-
except:
82+
except KeyError:
8483
return False
8584

85+
8686
def grab_add(nick, time, msg, chan, db, conn):
8787
# Adds a quote to the grab table
8888
db.execute(table.insert().values(name=nick, time=time, quote=msg, chan=chan))
@@ -103,15 +103,16 @@ def grab(text, nick, chan, db, conn):
103103
# check to see if the quote has been added
104104
if check_grabs(name.lower(), msg, chan):
105105
return "I already have that quote from {} in the database".format(text)
106-
break
107106
else:
108107
# the quote is new so add it to the db.
109108
grab_add(name.lower(),timestamp, msg, chan, db, conn)
110109
if check_grabs(name.lower(), msg, chan):
111110
return "the operation succeeded."
112-
break
111+
else:
112+
return "the operation failed"
113113
return "I couldn't find anything from {} in recent history.".format(text)
114114

115+
115116
def format_grab(name, quote):
116117
# add nonbreaking space to nicks to avoid highlighting people with printed grabs
117118
name = "{}{}{}".format(name[0], u"\u200B", name[1:])
@@ -123,13 +124,14 @@ def format_grab(name, quote):
123124
out = "<{}> {}".format(name, quote)
124125
return out
125126

127+
126128
@hook.command("lastgrab", "lgrab")
127129
def lastgrab(text, chan, message):
128130
"""prints the last grabbed quote from <nick>."""
129131
lgrab = ""
130132
try:
131133
lgrab = grab_cache[chan][text.lower()][-1]
132-
except:
134+
except (KeyError, IndexError):
133135
return "<{}> has never been grabbed.".format(text)
134136
if lgrab:
135137
quote = lgrab
@@ -150,11 +152,11 @@ def grabrandom(text, chan, message):
150152
else:
151153
try:
152154
name = random.choice(list(grab_cache[chan].keys()))
153-
except:
155+
except KeyError:
154156
return "I couldn't find any grabs in {}.".format(chan)
155157
try:
156158
grab = random.choice(grab_cache[chan][name.lower()])
157-
except:
159+
except KeyError:
158160
return "it appears {} has never been grabbed in {}".format(name, chan)
159161
if grab:
160162
message(format_grab(name, grab), chan)
@@ -173,8 +175,8 @@ def grabsearch(text, chan):
173175
quotes = grab_cache[chan][text.lower()]
174176
for grab in quotes:
175177
result.append((text, grab))
176-
except:
177-
pass
178+
except KeyError:
179+
pass
178180
for name in grab_cache[chan]:
179181
for grab in grab_cache[chan][name]:
180182
if name != text.lower():

0 commit comments

Comments
 (0)