dr.botzo/facts/ircplugin.py

67 lines
2.2 KiB
Python
Raw Normal View History

2016-01-16 17:58:11 -06:00
"""IRC plugin for retrieval of facts."""
import logging
from irc.client import NickMask
2015-06-20 10:58:40 -05:00
from facts.models import Fact, FactCategory
from ircbot.lib import Plugin
log = logging.getLogger('facts.ircplugin')
class Facts(Plugin):
"""Present facts to IRC."""
def start(self):
"""Set up the handlers."""
self.connection.reactor.add_global_regex_handler(
['pubmsg', 'privmsg'], r'remember\s+that\s+(?P<which>\S+)\s+(is|means)\s+(?P<what>.*)$',
self.handle_add_fact, -20
)
self.connection.reactor.add_global_regex_handler(
['pubmsg', 'privmsg'], r'^!f(acts)?\s+(?P<which>\S+)(\s+(?P<what>.*)$|$)',
self.handle_facts, -20
)
super(Facts, self).start()
def stop(self):
"""Tear down handlers."""
2015-06-20 10:58:40 -05:00
self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_add_fact)
self.connection.reactor.remove_global_regex_handler(['pubmsg', 'privmsg'], self.handle_facts)
super(Facts, self).stop()
def handle_facts(self, connection, event, match):
"""Respond to the facts command with desired fact."""
category = match.group('which')
regex = None
if match.group(2) != '':
regex = match.group('what')
fact = Fact.objects.random_fact(category, regex)
if fact:
if fact.category.show_source:
nick = NickMask(fact.nickmask).nick
msg = "{0:s} ({1:s})".format(fact.fact, nick)
else:
msg = fact.fact
return self.bot.reply(event, msg)
2015-06-20 10:58:40 -05:00
def handle_add_fact(self, connection, event, match):
"""Add a new fact to the database."""
if event.in_privmsg or event.addressed:
category_name = match.group('which')
fact_text = match.group('what')
2015-06-20 10:58:40 -05:00
# create the category
category, created = FactCategory.objects.get_or_create(name=category_name)
fact = Fact.objects.create(fact=fact_text, category=category, nickmask=event.source)
if fact:
self.bot.reply(event, f"ok, I now know more about {category.name}")
return 'NO MORE'
2015-06-20 10:58:40 -05:00
plugin = Facts