How to use the pmxbot.core function in pmxbot

To help you get started, we’ve selected a few pmxbot examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yougov / pmxbot / tests / unit / test_handlers.py View on Github external
def test_contains_always_match():
    """
    Contains handler should always match if no rate is specified.
    """
    handler = core.ContainsHandler(name='#', func=None)
    assert handler.match('Tell me about #foo', channel='bar')
github yougov / pmxbot / pmxbot / irc.py View on Github external
def warn(self, nick, connection):
        if pmxbot.config.get('privacy warning') == 'suppress':
            return
        if not self.needs_warning(nick):
            return
        logged_channels_string = ', '.join(pmxbot.config.log_channels)
        msg = self.warn_message.format(**locals())
        for line in msg.splitlines():
            connection.notice(nick, line)


class Scheduler(tempora.schedule.CallbackScheduler, irc.schedule.DefaultScheduler):
    pass


class LoggingCommandBot(core.Bot, irc.bot.SingleServerIRCBot):
    def __init__(self, server, port, nickname, channels, password=None):
        ErrorReportingBuffer.install()
        server_list = [(server, port, password)]
        super().__init__(server_list, nickname, nickname)
        self.reactor.scheduler = Scheduler(dispatch=self.handle_scheduled)
        self.nickname = nickname
        self._channels = channels
        self._nickname = nickname
        self.warn_history = WarnHistory()

    def connect(self, *args, **kwargs):
        factory = irc.connection.Factory(wrapper=self._get_wrapper())
        res = super().connect(connect_factory=factory, *args, **kwargs)
        limit = pmxbot.config.get('message rate limit', float('inf'))
        self.connection.set_rate_limit(limit)
        return res
github yougov / pmxbot / pmxbot / irc.py View on Github external
def on_quit(self, connection, event):
        nick = event.source.nick
        channel = event.target
        client = connection
        for handler in core.LeaveHandler._registry:
            try:
                handler.attach(locals())()
            except Exception:
                log.exception("Error in %s", handler)
github yougov / pmxbot / pmxbot / slack.py View on Github external
import importlib
import logging
import re
import collections
import html

from tempora import schedule

import pmxbot
from pmxbot import core


log = logging.getLogger(__name__)


class Bot(pmxbot.core.Bot):
    def __init__(self, server, port, nickname, channels, password=None):
        token = pmxbot.config['slack token']
        sc = importlib.import_module('slackclient')
        self.slack = sc.SlackClient(token)
        sr = importlib.import_module('slacker')
        self.slacker = sr.Slacker(token)

        self.scheduler = schedule.CallbackScheduler(self.handle_scheduled)

    def start(self):
        res = self.slack.rtm_connect()
        assert res, "Error connecting"
        self.init_schedule(self.scheduler)
        while True:
            for msg in self.slack.rtm_read():
                self.handle_message(msg)
github yougov / pmxbot / pmxbot / web / viewer.py View on Github external
def get_context():
        context = get_context()
        commands = []
        contains = []
        by_name = operator.attrgetter('name')
        for handler in sorted(pmxbot.core.Handler._registry, key=by_name):
            if type(handler) is pmxbot.core.CommandHandler:
                commands.append(handler)
            elif isinstance(handler, pmxbot.core.ContainsHandler):
                contains.append(handler)
        context['commands'] = commands
        context['contains'] = contains
        return context
github yougov / pmxbot / pmxbot / web / viewer.py View on Github external
def _setup_logging():
    cherrypy.log.error_log.propagate = False
    cherrypy.log.access_log.propagate = False
    pmxbot.core._setup_logging()
github yougov / pmxbot / pmxbot / logging.py View on Github external
else:
        return "Sorry!  I don't have any record of %s speaking" % onick


class LoggedChannels:
    def __contains__(self, channel):
        return channel in pmxbot.config.log_channels


class UnloggedChannels:
    def __contains__(self, channel):
        return channel not in pmxbot.config.log_channels


# Create a content handler for capturing logged channels
logging_handler = core.ContentHandler(channels=LoggedChannels())


@logging_handler.decorate
def log_message(channel, nick, rest):
    Logger.store.message(channel, nick, rest)


@command()
def logs(channel):
    "Where can one find the logs?"
    default_url = 'http://' + socket.getfqdn()
    base = pmxbot.config.get('logs URL', default_url)
    logged_channel = channel in pmxbot.config.log_channels
    path = '/channel/' + channel.lstrip('#') if logged_channel else '/'
    return urllib.parse.urljoin(base, path)
github yougov / pmxbot / pmxbot / slack.py View on Github external
if msg.get('type') != 'message':
            return

        # resolve nick based on message subtype
        # https://api.slack.com/events/message
        method_name = '_resolve_nick_{subtype}'.format_map(
            collections.defaultdict(lambda: 'standard', msg)
        )
        resolve_nick = getattr(self, method_name, None)
        if not resolve_nick:
            log.debug('Unhandled message %s', msg)
            return
        nick = resolve_nick(msg)

        channel = self.slack.server.channels.find(msg['channel']).name
        channel = core.AugmentableMessage(channel, thread=msg.get('thread_ts'))

        self.handle_action(channel, nick, html.unescape(msg['text']))
github yougov / pmxbot / pmxbot / commands.py View on Github external
def lookup_command(cmd_name):
        msg = '!' + cmd_name + ' '
        res = pmxbot.core.CommandHandler.find_matching(msg, channel=None)
        return next(res).func
github yougov / pmxbot / pavement.py View on Github external
def update_wiki():
	pmxbot.core._load_library_extensions()
	pmxbot.web.viewer._init_config()
	ctx = pmxbot.web.viewer.HelpPage.get_context()
	commands = ctx['commands']
	project = 'yougov/pmxbot'
	title = 'Home'
	path = 'home.wiki'
	req = pkg_resources.require('pmxbot')
	usage = pkg_resources.resource_stream('pmxbot', 'example usage.txt')
	content = home_wiki % dict(
		commands='\n'.join(to_wiki(commands)),
		usage=usage.read(),
		version=req[0].version,
	)
	# api is broken, so copy/paste
	# bitbucket.update_wiki(project, title, path, content)
	print("You need to update the wiki yourself: ")