dr.botzo/seen/ircplugin.py

76 lines
2.3 KiB
Python

"""Show seen chatter data over IRC."""
import logging
from django.utils import timezone
import irc.client
from ircbot.lib import Plugin
from seen.models import SeenNick
log = logging.getLogger('seen.ircplugin')
class Seen(Plugin):
"""Track when people say things in public channels, and report on it."""
def start(self):
"""Hook handler functions into the IRC library."""
self.connection.add_global_handler('pubmsg', self.handle_seeing)
self.connection.reactor.add_global_regex_handler(['pubmsg'], r'^!seen\s+(\S+)$', self.handle_seen)
super(Seen, self).start()
def stop(self):
"""Unhook handler functions into the IRC library."""
self.connection.remove_global_handler('pubmsg', self.handle_seeing)
self.connection.reactor.remove_global_regex_handler(['pubmsg'], self.handle_seen)
super(Seen, self).stop()
@staticmethod
def handle_seeing(connection, event):
"""Track pubmsg/privmsg events."""
userhost = event.source
nick = irc.client.NickMask(event.source).nick
where = event.target
what = event.arguments[0]
log.debug("userhost %s, nick %s, where %s, what '%s'", userhost, nick, where, what)
# store the event. only learn events with real wheres
if where:
seen_nick, c = SeenNick.objects.get_or_create(nick=nick, channel=where)
seen_nick.host = userhost
seen_nick.what = what
seen_nick.seen_time = timezone.now()
seen_nick.save()
def handle_seen(self, connection, event, match):
"""Report on when a nick was last seen in a channel."""
query_nick = match.group(1)
source = event.target
log.debug("query nick %s, source %s", query_nick, source)
try:
seen_nick = SeenNick.objects.get(nick=query_nick, channel=source)
local_time = timezone.localtime(seen_nick.seen_time).strftime('%Y-%m-%d %H:%M:%S %Z')
return self.bot.reply(event, "last saw {0:s} in {1:s} at {2:s} saying '{3:s}'."
"".format(seen_nick.nick, seen_nick.channel,
local_time, seen_nick.what))
except SeenNick.DoesNotExist:
return self.bot.reply(event, "i have not seen {0:s} in {1:s}.".format(query_nick, source))
plugin = Seen