62 lines
2.2 KiB
Python
62 lines
2.2 KiB
Python
"""IRC plugin for retrieval of facts."""
|
|
import logging
|
|
|
|
from irc.client import NickMask
|
|
|
|
from ircbot.lib import Plugin, has_permission
|
|
from facts.models import Fact, FactCategory
|
|
|
|
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'^!facts\s+add\s+(\S+)\s+(.*)$',
|
|
self.handle_add_fact, -20)
|
|
self.connection.reactor.add_global_regex_handler(['pubmsg', 'privmsg'], r'^!facts\s+(\S+)(\s+(.*)$|$)',
|
|
self.handle_facts, -20)
|
|
|
|
super(Facts, self).start()
|
|
|
|
def stop(self):
|
|
"""Tear down handlers."""
|
|
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(1)
|
|
regex = None
|
|
if match.group(2) != '':
|
|
regex = match.group(3)
|
|
|
|
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)
|
|
|
|
def handle_add_fact(self, connection, event, match):
|
|
"""Add a new fact to the database."""
|
|
category_name = match.group(1)
|
|
fact_text = match.group(2)
|
|
|
|
if has_permission(event.source, 'facts.add_fact'):
|
|
# 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:
|
|
return self.bot.reply(event, "fact added to {0:s}".format(category.name))
|
|
|
|
|
|
plugin = Facts
|