note that for now anyone can add a fact, going to assume responsible usage on the part of users on my networks
67 lines
2.2 KiB
Python
67 lines
2.2 KiB
Python
"""IRC plugin for retrieval of facts."""
|
|
import logging
|
|
|
|
from irc.client import NickMask
|
|
|
|
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."""
|
|
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)
|
|
|
|
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')
|
|
|
|
# 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'
|
|
|
|
|
|
plugin = Facts
|