2015-12-07 02:40:13 +01:00
|
|
|
"""
|
|
|
|
utils.py - PyLink utilities module.
|
|
|
|
|
|
|
|
This module contains various utility functions related to IRC and/or the PyLink
|
|
|
|
framework.
|
|
|
|
"""
|
|
|
|
|
2015-04-25 07:37:07 +02:00
|
|
|
import string
|
2015-06-17 05:46:01 +02:00
|
|
|
import re
|
2015-11-23 05:14:47 +01:00
|
|
|
import importlib
|
|
|
|
import os
|
2016-05-14 18:55:46 +02:00
|
|
|
import collections
|
2015-04-25 07:37:07 +02:00
|
|
|
|
2016-06-21 03:18:54 +02:00
|
|
|
from .log import log
|
|
|
|
from . import world, conf
|
2016-07-03 08:57:20 +02:00
|
|
|
# This is just so protocols and plugins are importable.
|
|
|
|
from pylinkirc import protocols, plugins
|
2015-05-31 21:20:09 +02:00
|
|
|
|
2016-12-17 04:25:41 +01:00
|
|
|
PLUGIN_PREFIX = 'pylinkirc.plugins.'
|
|
|
|
PROTOCOL_PREFIX = 'pylinkirc.protocols.'
|
2016-12-06 08:33:03 +01:00
|
|
|
NORMALIZEWHITESPACE_RE = re.compile(r'\s+')
|
|
|
|
|
2016-08-25 09:43:44 +02:00
|
|
|
class NotAuthorizedError(Exception):
|
2016-05-14 19:05:18 +02:00
|
|
|
"""
|
|
|
|
Exception raised by checkAuthenticated() when a user fails authentication
|
|
|
|
requirements.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
2016-04-06 03:05:52 +02:00
|
|
|
class IncrementalUIDGenerator():
|
2015-12-26 23:45:28 +01:00
|
|
|
"""
|
2016-04-06 03:05:52 +02:00
|
|
|
Incremental UID Generator module, adapted from InspIRCd source:
|
2015-06-19 19:43:42 +02:00
|
|
|
https://github.com/inspircd/inspircd/blob/f449c6b296ab/src/server.cpp#L85-L156
|
|
|
|
"""
|
|
|
|
|
2015-06-23 01:51:42 +02:00
|
|
|
def __init__(self, sid):
|
2016-04-06 03:05:52 +02:00
|
|
|
if not (hasattr(self, 'allowedchars') and hasattr(self, 'length')):
|
|
|
|
raise RuntimeError("Allowed characters list not defined. Subclass "
|
|
|
|
"%s by defining self.allowedchars and self.length "
|
|
|
|
"and then calling super().__init__()." % self.__class__.__name__)
|
|
|
|
self.uidchars = [self.allowedchars[0]]*self.length
|
2016-06-17 06:55:32 +02:00
|
|
|
self.sid = str(sid)
|
2015-06-19 19:43:42 +02:00
|
|
|
|
2016-04-06 03:05:52 +02:00
|
|
|
def increment(self, pos=None):
|
2015-12-26 23:45:28 +01:00
|
|
|
"""
|
2016-04-06 03:05:52 +02:00
|
|
|
Increments the UID generator to the next available UID.
|
2015-12-26 23:45:28 +01:00
|
|
|
"""
|
2016-04-06 03:05:52 +02:00
|
|
|
# Position starts at 1 less than the UID length.
|
2016-04-06 03:44:00 +02:00
|
|
|
if pos is None:
|
|
|
|
pos = self.length - 1
|
2016-04-06 03:05:52 +02:00
|
|
|
|
2015-06-19 19:43:42 +02:00
|
|
|
# If we're at the last character in the list of allowed ones, reset
|
|
|
|
# and increment the next level above.
|
|
|
|
if self.uidchars[pos] == self.allowedchars[-1]:
|
|
|
|
self.uidchars[pos] = self.allowedchars[0]
|
|
|
|
self.increment(pos-1)
|
|
|
|
else:
|
|
|
|
# Find what position in the allowed characters list we're currently
|
|
|
|
# on, and add one.
|
|
|
|
idx = self.allowedchars.find(self.uidchars[pos])
|
|
|
|
self.uidchars[pos] = self.allowedchars[idx+1]
|
|
|
|
|
2015-06-23 01:51:42 +02:00
|
|
|
def next_uid(self):
|
2015-12-26 23:45:28 +01:00
|
|
|
"""
|
2016-04-06 03:05:52 +02:00
|
|
|
Returns the next unused UID for the server.
|
2015-12-26 23:45:28 +01:00
|
|
|
"""
|
2015-06-23 01:51:42 +02:00
|
|
|
uid = self.sid + ''.join(self.uidchars)
|
2015-06-19 19:43:42 +02:00
|
|
|
self.increment()
|
2015-06-22 03:11:17 +02:00
|
|
|
return uid
|
2015-05-31 08:00:39 +02:00
|
|
|
|
2016-07-17 07:42:17 +02:00
|
|
|
class PUIDGenerator():
|
|
|
|
"""
|
|
|
|
Pseudo UID Generator module, using a prefix and a simple counter.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, prefix):
|
|
|
|
self.prefix = prefix
|
|
|
|
self.counter = 0
|
|
|
|
|
2016-07-29 06:59:56 +02:00
|
|
|
def next_uid(self, prefix=''):
|
2016-07-17 07:42:17 +02:00
|
|
|
"""
|
|
|
|
Generates the next PUID.
|
|
|
|
"""
|
2016-07-29 06:59:56 +02:00
|
|
|
uid = '%s@%s' % (prefix or self.prefix, self.counter)
|
2016-07-17 07:42:17 +02:00
|
|
|
self.counter += 1
|
|
|
|
return uid
|
|
|
|
next_sid = next_uid
|
|
|
|
|
2016-07-01 02:57:40 +02:00
|
|
|
def add_cmd(func, name=None, **kwargs):
|
2015-11-23 05:14:47 +01:00
|
|
|
"""Binds an IRC command function to the given command name."""
|
2016-07-01 02:57:40 +02:00
|
|
|
world.services['pylink'].add_cmd(func, name=name, **kwargs)
|
2015-10-24 03:47:11 +02:00
|
|
|
return func
|
2015-06-08 04:31:56 +02:00
|
|
|
|
2015-06-24 04:08:43 +02:00
|
|
|
def add_hook(func, command):
|
2015-11-23 05:14:47 +01:00
|
|
|
"""Binds a hook function to the given command name."""
|
2015-07-05 04:00:29 +02:00
|
|
|
command = command.upper()
|
2015-09-27 19:53:25 +02:00
|
|
|
world.hooks[command].append(func)
|
2015-10-24 03:47:11 +02:00
|
|
|
return func
|
2015-06-24 04:08:43 +02:00
|
|
|
|
2015-06-17 05:46:01 +02:00
|
|
|
_nickregex = r'^[A-Za-z\|\\_\[\]\{\}\^\`][A-Z0-9a-z\-\|\\_\[\]\{\}\^\`]*$'
|
|
|
|
def isNick(s, nicklen=None):
|
2015-11-23 05:14:47 +01:00
|
|
|
"""Returns whether the string given is a valid nick."""
|
2015-06-17 05:46:01 +02:00
|
|
|
if nicklen and len(s) > nicklen:
|
|
|
|
return False
|
|
|
|
return bool(re.match(_nickregex, s))
|
|
|
|
|
|
|
|
def isChannel(s):
|
2015-11-23 05:14:47 +01:00
|
|
|
"""Returns whether the string given is a valid channel name."""
|
2015-09-13 07:28:34 +02:00
|
|
|
return str(s).startswith('#')
|
2015-06-22 00:00:33 +02:00
|
|
|
|
2015-07-04 02:05:44 +02:00
|
|
|
def _isASCII(s):
|
2015-11-23 05:14:47 +01:00
|
|
|
"""Returns whether the string given is valid ASCII."""
|
2015-07-04 02:05:44 +02:00
|
|
|
chars = string.ascii_letters + string.digits + string.punctuation
|
|
|
|
return all(char in chars for char in s)
|
2015-06-22 00:00:33 +02:00
|
|
|
|
|
|
|
def isServerName(s):
|
2015-11-23 05:14:47 +01:00
|
|
|
"""Returns whether the string given is a valid IRC server name."""
|
2015-07-07 23:31:47 +02:00
|
|
|
return _isASCII(s) and '.' in s and not s.startswith('.')
|
2015-06-21 05:36:35 +02:00
|
|
|
|
2015-09-13 07:28:34 +02:00
|
|
|
hostmaskRe = re.compile(r'^\S+!\S+@\S+$')
|
|
|
|
def isHostmask(text):
|
|
|
|
"""Returns whether the given text is a valid hostmask."""
|
2015-10-09 02:25:17 +02:00
|
|
|
# Band-aid patch here to prevent bad bans set by Janus forwarding people into invalid channels.
|
|
|
|
return hostmaskRe.match(text) and '#' not in text
|
2015-09-13 07:28:34 +02:00
|
|
|
|
2015-07-05 21:48:39 +02:00
|
|
|
def parseModes(irc, target, args):
|
2015-08-29 04:27:38 +02:00
|
|
|
"""Parses a modestring list into a list of (mode, argument) tuples.
|
2015-07-05 08:49:28 +02:00
|
|
|
['+mitl-o', '3', 'person'] => [('+m', None), ('+i', None), ('+t', None), ('+l', '3'), ('-o', 'person')]
|
2016-03-24 02:04:12 +01:00
|
|
|
|
2016-04-25 06:37:23 +02:00
|
|
|
This method is deprecated. Use irc.parseModes() instead.
|
|
|
|
"""
|
2016-04-25 06:44:02 +02:00
|
|
|
log.warning("(%s) utils.parseModes is deprecated. Use irc.parseModes() instead!", irc.name)
|
2016-04-25 06:37:23 +02:00
|
|
|
return irc.parseModes(target, args)
|
2015-06-21 05:36:35 +02:00
|
|
|
|
2015-07-05 21:48:39 +02:00
|
|
|
def applyModes(irc, target, changedmodes):
|
2015-09-13 07:28:34 +02:00
|
|
|
"""Takes a list of parsed IRC modes, and applies them on the given target.
|
2015-07-09 01:58:59 +02:00
|
|
|
|
2016-04-25 06:37:23 +02:00
|
|
|
The target can be either a channel or a user; this is handled automatically.
|
2016-03-27 03:14:53 +02:00
|
|
|
|
2016-04-25 06:37:23 +02:00
|
|
|
This method is deprecated. Use irc.applyModes() instead.
|
|
|
|
"""
|
2016-04-25 06:44:02 +02:00
|
|
|
log.warning("(%s) utils.applyModes is deprecated. Use irc.applyModes() instead!", irc.name)
|
2016-04-25 06:37:23 +02:00
|
|
|
return irc.applyModes(target, changedmodes)
|
2015-06-21 05:54:01 +02:00
|
|
|
|
2016-07-03 08:57:20 +02:00
|
|
|
def loadPlugin(name):
|
|
|
|
"""
|
|
|
|
Imports and returns the requested plugin.
|
|
|
|
"""
|
2016-12-17 04:25:41 +01:00
|
|
|
return importlib.import_module(PLUGIN_PREFIX + name)
|
2016-07-03 08:57:20 +02:00
|
|
|
|
|
|
|
def getProtocolModule(name):
|
2015-12-26 23:45:28 +01:00
|
|
|
"""
|
|
|
|
Imports and returns the protocol module requested.
|
|
|
|
"""
|
2016-12-17 04:25:41 +01:00
|
|
|
return importlib.import_module(PROTOCOL_PREFIX + name)
|
2015-12-07 02:13:47 +01:00
|
|
|
|
|
|
|
def getDatabaseName(dbname):
|
|
|
|
"""
|
|
|
|
Returns a database filename with the given base DB name appropriate for the
|
|
|
|
current PyLink instance.
|
|
|
|
|
|
|
|
This returns '<dbname>.db' if the running config name is PyLink's default
|
2016-06-21 19:56:53 +02:00
|
|
|
(pylink.yml), and '<dbname>-<config name>.db' for anything else. For example,
|
2015-12-07 02:13:47 +01:00
|
|
|
if this is called from an instance running as './pylink testing.yml', it
|
|
|
|
would return '<dbname>-testing.db'."""
|
|
|
|
if conf.confname != 'pylink':
|
|
|
|
dbname += '-%s' % conf.confname
|
|
|
|
dbname += '.db'
|
|
|
|
return dbname
|
2016-05-14 18:55:46 +02:00
|
|
|
|
2016-07-18 00:20:48 +02:00
|
|
|
def splitHostmask(mask):
|
|
|
|
"""
|
|
|
|
Returns a nick!user@host hostmask split into three fields: nick, user, and host.
|
|
|
|
"""
|
|
|
|
nick, identhost = mask.split('!', 1)
|
|
|
|
ident, host = identhost.split('@', 1)
|
|
|
|
return [nick, ident, host]
|
|
|
|
|
2016-05-14 18:55:46 +02:00
|
|
|
class ServiceBot():
|
2016-07-01 03:22:45 +02:00
|
|
|
"""
|
|
|
|
PyLink IRC Service class.
|
|
|
|
"""
|
|
|
|
|
2016-07-24 04:57:05 +02:00
|
|
|
def __init__(self, name, default_help=True, default_list=True,
|
2016-07-08 07:54:57 +02:00
|
|
|
nick=None, ident=None, manipulatable=False, extra_channels=None,
|
2016-07-01 02:30:44 +02:00
|
|
|
desc=None):
|
2016-05-14 21:52:32 +02:00
|
|
|
# Service name
|
2016-05-14 18:55:46 +02:00
|
|
|
self.name = name
|
2016-05-14 19:17:40 +02:00
|
|
|
|
2016-05-14 21:52:32 +02:00
|
|
|
# Nick/ident to take. Defaults to the same as the service name if not given.
|
2016-06-11 19:54:07 +02:00
|
|
|
self.nick = nick
|
|
|
|
self.ident = ident
|
2016-05-14 21:52:32 +02:00
|
|
|
|
|
|
|
# Tracks whether the bot should be manipulatable by the 'bots' plugin and other commands.
|
|
|
|
self.manipulatable = manipulatable
|
|
|
|
|
2016-05-14 18:55:46 +02:00
|
|
|
# We make the command definitions a dict of lists of functions. Multiple
|
|
|
|
# plugins are actually allowed to bind to one function name; this just causes
|
|
|
|
# them to be called in the order that they are bound.
|
|
|
|
self.commands = collections.defaultdict(list)
|
|
|
|
|
|
|
|
# This tracks the UIDs of the service bot on different networks, as they are
|
|
|
|
# spawned.
|
|
|
|
self.uids = {}
|
|
|
|
|
2016-06-25 23:09:41 +02:00
|
|
|
# Track what channels other than those defined in the config
|
|
|
|
# that the bot should join by default.
|
2016-07-08 07:54:57 +02:00
|
|
|
self.extra_channels = extra_channels or collections.defaultdict(set)
|
2016-06-25 23:09:41 +02:00
|
|
|
|
2016-07-01 02:30:44 +02:00
|
|
|
# Service description, used in the default help command if one is given.
|
|
|
|
self.desc = desc
|
|
|
|
|
|
|
|
# List of command names to "feature"
|
|
|
|
self.featured_cmds = set()
|
|
|
|
|
2016-05-14 18:55:46 +02:00
|
|
|
if default_help:
|
|
|
|
self.add_cmd(self.help)
|
|
|
|
|
|
|
|
if default_list:
|
|
|
|
self.add_cmd(self.listcommands, 'list')
|
|
|
|
|
|
|
|
def spawn(self, irc=None):
|
2016-07-01 03:22:45 +02:00
|
|
|
"""
|
|
|
|
Spawns instances of this service on all connected networks.
|
|
|
|
"""
|
2016-05-14 18:55:46 +02:00
|
|
|
# Spawn the new service by calling the PYLINK_NEW_SERVICE hook,
|
|
|
|
# which is handled by coreplugin.
|
|
|
|
if irc is None:
|
|
|
|
for irc in world.networkobjects.values():
|
|
|
|
irc.callHooks([None, 'PYLINK_NEW_SERVICE', {'name': self.name}])
|
|
|
|
else:
|
|
|
|
raise NotImplementedError("Network specific plugins not supported yet.")
|
|
|
|
|
2016-09-24 08:39:12 +02:00
|
|
|
def join(self, irc, channels, autojoin=True):
|
|
|
|
"""
|
|
|
|
Joins the given service bot to the given channel(s).
|
|
|
|
"""
|
2016-09-24 21:33:57 +02:00
|
|
|
|
|
|
|
if type(irc) == str:
|
|
|
|
netname = irc
|
|
|
|
else:
|
|
|
|
netname = irc.name
|
2016-09-24 08:39:12 +02:00
|
|
|
|
|
|
|
# Ensure type safety: pluralize strings if only one channel was given, then convert to set.
|
|
|
|
if type(channels) == str:
|
|
|
|
channels = [channels]
|
|
|
|
channels = set(channels)
|
|
|
|
|
2016-09-24 21:33:57 +02:00
|
|
|
if autojoin:
|
|
|
|
log.debug('(%s/%s) Adding channels %s to autojoin', netname, self.name, channels)
|
|
|
|
self.extra_channels[netname] |= channels
|
|
|
|
|
|
|
|
# If the network was given as a string, look up the Irc object here.
|
|
|
|
try:
|
|
|
|
irc = world.networkobjects[netname]
|
|
|
|
except KeyError:
|
|
|
|
log.debug('(%s/%s) Skipping join(), IRC object not initialized yet', irc, self.name)
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
u = self.uids[irc.name]
|
|
|
|
except KeyError:
|
|
|
|
log.debug('(%s/%s) Skipping join(), UID not initialized yet', irc.name, self.name)
|
|
|
|
return
|
|
|
|
|
2016-09-24 08:39:12 +02:00
|
|
|
# Specify modes to join the services bot with.
|
|
|
|
joinmodes = irc.serverdata.get("%s_joinmodes" % self.name) or conf.conf.get(self.name, {}).get('joinmodes') or ''
|
|
|
|
joinmodes = ''.join([m for m in joinmodes if m in irc.prefixmodes])
|
|
|
|
|
|
|
|
for chan in channels:
|
|
|
|
if isChannel(chan):
|
|
|
|
if u in irc.channels[chan].users:
|
|
|
|
log.debug('(%s) Skipping join of services %s to channel %s - it is already present', irc.name, self.name, chan)
|
|
|
|
continue
|
|
|
|
log.debug('(%s) Joining services %s to channel %s with modes %r', irc.name, self.name, chan, joinmodes)
|
|
|
|
if joinmodes: # Modes on join were specified; use SJOIN to burst our service
|
|
|
|
irc.proto.sjoin(irc.sid, chan, [(joinmodes, u)])
|
|
|
|
else:
|
|
|
|
irc.proto.join(u, chan)
|
|
|
|
|
|
|
|
irc.callHooks([irc.sid, 'PYLINK_SERVICE_JOIN', {'channel': chan, 'users': [u]}])
|
|
|
|
else:
|
|
|
|
log.warning('(%s) Ignoring invalid autojoin channel %r.', irc.name, chan)
|
|
|
|
|
2016-07-01 03:22:45 +02:00
|
|
|
def reply(self, irc, text, notice=False, private=False):
|
|
|
|
"""Replies to a message as the service in question."""
|
2016-05-14 19:17:40 +02:00
|
|
|
servuid = self.uids.get(irc.name)
|
|
|
|
if not servuid:
|
|
|
|
log.warning("(%s) Possible desync? UID for service %s doesn't exist!", irc.name, self.name)
|
|
|
|
return
|
|
|
|
|
2016-07-01 03:22:45 +02:00
|
|
|
irc.reply(text, notice=notice, source=servuid, private=private)
|
2016-12-05 08:35:16 +01:00
|
|
|
|
2016-11-19 07:01:23 +01:00
|
|
|
def error(self, irc, text, notice=False, private=False):
|
|
|
|
"""Replies with an error, as the service in question."""
|
|
|
|
servuid = self.uids.get(irc.name)
|
|
|
|
if not servuid:
|
|
|
|
log.warning("(%s) Possible desync? UID for service %s doesn't exist!", irc.name, self.name)
|
|
|
|
return
|
2016-05-14 19:17:40 +02:00
|
|
|
|
2016-11-19 07:01:23 +01:00
|
|
|
irc.error(text, notice=notice, source=servuid, private=private)
|
2016-12-05 08:35:16 +01:00
|
|
|
|
2016-07-01 03:22:45 +02:00
|
|
|
def call_cmd(self, irc, source, text, called_in=None):
|
2016-05-14 19:17:40 +02:00
|
|
|
"""
|
|
|
|
Calls a PyLink bot command. source is the caller's UID, and text is the
|
|
|
|
full, unparsed text of the message.
|
|
|
|
"""
|
2016-07-01 03:22:45 +02:00
|
|
|
irc.called_in = called_in or source
|
|
|
|
irc.called_by = source
|
2016-05-14 19:17:40 +02:00
|
|
|
|
|
|
|
cmd_args = text.strip().split(' ')
|
|
|
|
cmd = cmd_args[0].lower()
|
|
|
|
cmd_args = cmd_args[1:]
|
|
|
|
if cmd not in self.commands:
|
2016-06-15 20:26:30 +02:00
|
|
|
if not cmd.startswith('\x01'):
|
|
|
|
# Ignore invalid command errors from CTCPs.
|
|
|
|
self.reply(irc, 'Error: Unknown command %r.' % cmd)
|
2016-05-14 19:17:40 +02:00
|
|
|
log.info('(%s/%s) Received unknown command %r from %s', irc.name, self.name, cmd, irc.getHostmask(source))
|
|
|
|
return
|
|
|
|
|
|
|
|
log.info('(%s/%s) Calling command %r for %s', irc.name, self.name, cmd, irc.getHostmask(source))
|
|
|
|
for func in self.commands[cmd]:
|
|
|
|
try:
|
|
|
|
func(irc, source, cmd_args)
|
2016-08-25 09:43:44 +02:00
|
|
|
except NotAuthorizedError as e:
|
2016-08-25 09:57:21 +02:00
|
|
|
self.reply(irc, 'Error: %s' % e)
|
2016-05-14 19:17:40 +02:00
|
|
|
except Exception as e:
|
|
|
|
log.exception('Unhandled exception caught in command %r', cmd)
|
|
|
|
self.reply(irc, 'Uncaught exception in command %r: %s: %s' % (cmd, type(e).__name__, str(e)))
|
2016-05-14 18:55:46 +02:00
|
|
|
|
2016-07-01 02:30:44 +02:00
|
|
|
def add_cmd(self, func, name=None, featured=False):
|
2016-05-14 18:55:46 +02:00
|
|
|
"""Binds an IRC command function to the given command name."""
|
|
|
|
if name is None:
|
|
|
|
name = func.__name__
|
|
|
|
name = name.lower()
|
|
|
|
|
2016-07-01 02:30:44 +02:00
|
|
|
# Mark as a featured command if requested to do so.
|
|
|
|
if featured:
|
|
|
|
self.featured_cmds.add(name)
|
|
|
|
|
2016-05-14 18:55:46 +02:00
|
|
|
self.commands[name].append(func)
|
|
|
|
return func
|
|
|
|
|
2016-07-01 03:52:35 +02:00
|
|
|
def _show_command_help(self, irc, command, private=False, shortform=False):
|
2016-07-01 03:37:14 +02:00
|
|
|
"""
|
|
|
|
Shows help for the given command.
|
|
|
|
"""
|
|
|
|
def _reply(text):
|
|
|
|
"""
|
|
|
|
reply() wrapper to handle the private argument.
|
|
|
|
"""
|
|
|
|
self.reply(irc, text, private=private)
|
|
|
|
|
2016-05-14 21:22:00 +02:00
|
|
|
if command not in self.commands:
|
2016-07-01 03:37:14 +02:00
|
|
|
_reply('Error: Unknown command %r.' % command)
|
2016-05-14 21:22:00 +02:00
|
|
|
return
|
|
|
|
else:
|
|
|
|
funcs = self.commands[command]
|
|
|
|
if len(funcs) > 1:
|
2016-07-01 03:37:14 +02:00
|
|
|
_reply('The following \x02%s\x02 plugins bind to the \x02%s\x02 command: %s'
|
|
|
|
% (len(funcs), command, ', '.join([func.__module__ for func in funcs])))
|
2016-05-14 21:22:00 +02:00
|
|
|
for func in funcs:
|
|
|
|
doc = func.__doc__
|
|
|
|
mod = func.__module__
|
|
|
|
if doc:
|
2016-08-02 21:38:15 +02:00
|
|
|
lines = doc.splitlines()
|
2016-05-14 21:22:00 +02:00
|
|
|
# Bold the first line, which usually just tells you what
|
|
|
|
# arguments the command takes.
|
2016-12-06 08:33:03 +01:00
|
|
|
args_desc = '\x02%s %s\x02' % (command, lines[0])
|
|
|
|
|
|
|
|
_reply(args_desc.strip())
|
|
|
|
if not shortform:
|
|
|
|
# Note: we handle newlines in docstrings a bit differently. Per
|
|
|
|
# https://github.com/GLolol/PyLink/issues/307, only double newlines
|
|
|
|
# have the effect of showing a new line on IRC. Single newlines
|
|
|
|
# are stripped so that word wrap can be applied in the source code
|
|
|
|
# without actually affecting the output on IRC.
|
|
|
|
for line in doc.replace('\r', '').split('\n\n')[1:]:
|
|
|
|
_reply(' ') # Empty line to break up output a bit.
|
|
|
|
real_line = line.replace('\n', ' ')
|
|
|
|
real_line = real_line.strip()
|
|
|
|
real_line = NORMALIZEWHITESPACE_RE.sub(' ', real_line)
|
|
|
|
_reply(real_line)
|
2016-05-14 21:22:00 +02:00
|
|
|
else:
|
2016-07-01 03:37:14 +02:00
|
|
|
_reply("Error: Command %r doesn't offer any help." % command)
|
2016-05-14 21:22:00 +02:00
|
|
|
return
|
2016-05-14 18:55:46 +02:00
|
|
|
|
2016-07-01 02:39:53 +02:00
|
|
|
def help(self, irc, source, args):
|
|
|
|
"""<command>
|
|
|
|
|
|
|
|
Gives help for <command>, if it is available."""
|
|
|
|
try:
|
|
|
|
command = args[0].lower()
|
|
|
|
except IndexError:
|
|
|
|
# No argument given: show service description (if present), 'list' output, and a list
|
|
|
|
# of featured commands.
|
|
|
|
if self.desc:
|
|
|
|
self.reply(irc, self.desc)
|
|
|
|
self.reply(irc, " ") # Extra newline to unclutter the output text
|
|
|
|
|
|
|
|
self.listcommands(irc, source, args)
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
self._show_command_help(irc, command)
|
|
|
|
|
2016-05-14 18:55:46 +02:00
|
|
|
def listcommands(self, irc, source, args):
|
2016-12-17 04:25:41 +01:00
|
|
|
"""[<plugin name>]
|
2016-05-14 21:22:00 +02:00
|
|
|
|
2016-12-17 04:25:41 +01:00
|
|
|
Returns a list of available commands this service has to offer. The optional
|
|
|
|
plugin name argument also allows you to filter commands by plugin (case
|
|
|
|
insensitive)."""
|
|
|
|
|
|
|
|
try:
|
|
|
|
plugin_filter = args[0].lower()
|
|
|
|
except IndexError:
|
|
|
|
plugin_filter = None
|
2016-05-14 21:22:00 +02:00
|
|
|
|
2016-07-01 02:30:44 +02:00
|
|
|
# Don't show CTCP handlers in the public command list.
|
2016-12-17 04:25:41 +01:00
|
|
|
cmds = sorted(cmd for cmd in self.commands.keys() if '\x01' not in cmd)
|
|
|
|
|
|
|
|
if plugin_filter is not None:
|
|
|
|
# Filter by plugin, if the option was given.
|
|
|
|
new_cmds = []
|
|
|
|
|
|
|
|
# Add the pylinkirc.plugins prefix to the module name, so it can be used for matching.
|
|
|
|
plugin_module = PLUGIN_PREFIX + plugin_filter
|
|
|
|
|
|
|
|
for cmd_definition in cmds:
|
|
|
|
for cmdfunc in self.commands[cmd_definition]:
|
|
|
|
if cmdfunc.__module__.lower() == plugin_module:
|
|
|
|
new_cmds.append(cmd_definition)
|
|
|
|
|
|
|
|
# Replace the old command list.
|
|
|
|
cmds = new_cmds
|
2016-07-01 02:30:44 +02:00
|
|
|
|
|
|
|
if cmds:
|
|
|
|
self.reply(irc, 'Available commands include: %s' % ', '.join(cmds))
|
|
|
|
self.reply(irc, 'To see help on a specific command, type \x02help <command>\x02.')
|
2016-12-17 04:25:41 +01:00
|
|
|
elif not plugin_filter:
|
2016-07-01 03:37:14 +02:00
|
|
|
self.reply(irc, 'This service doesn\'t provide any public commands.')
|
2016-12-17 04:25:41 +01:00
|
|
|
else:
|
|
|
|
self.reply(irc, 'This service doesn\'t provide any public commands from the plugin %s.' % plugin_filter)
|
2016-07-01 02:30:44 +02:00
|
|
|
|
2016-07-01 02:39:53 +02:00
|
|
|
# If there are featured commands, list them by showing the help for each.
|
2016-07-01 03:37:14 +02:00
|
|
|
# These definitions are sent in private to prevent flooding in channels.
|
2016-12-17 04:25:41 +01:00
|
|
|
if self.featured_cmds and not plugin_filter:
|
2016-07-01 03:37:14 +02:00
|
|
|
self.reply(irc, " ", private=True)
|
|
|
|
self.reply(irc, 'Featured commands include:', private=True)
|
2016-07-01 03:05:12 +02:00
|
|
|
for cmd in sorted(self.featured_cmds):
|
2016-12-17 04:25:41 +01:00
|
|
|
if cmd in cmds:
|
2016-07-01 02:39:53 +02:00
|
|
|
# Only show featured commands that are both defined and loaded.
|
|
|
|
# TODO: perhaps plugin unload should remove unused featured command
|
|
|
|
# definitions automatically?
|
2016-07-01 03:52:35 +02:00
|
|
|
self._show_command_help(irc, cmd, private=True, shortform=True)
|
2016-07-01 03:55:16 +02:00
|
|
|
self.reply(irc, 'End of command listing.', private=True)
|
2016-05-14 18:55:46 +02:00
|
|
|
|
|
|
|
def registerService(name, *args, **kwargs):
|
2016-05-14 23:52:12 +02:00
|
|
|
"""Registers a service bot."""
|
2016-05-14 18:55:46 +02:00
|
|
|
name = name.lower()
|
|
|
|
if name in world.services:
|
|
|
|
raise ValueError("Service name %s is already bound!" % name)
|
|
|
|
|
|
|
|
world.services[name] = sbot = ServiceBot(name, *args, **kwargs)
|
|
|
|
sbot.spawn()
|
2016-05-14 23:23:52 +02:00
|
|
|
return sbot
|
2016-05-14 23:52:12 +02:00
|
|
|
|
|
|
|
def unregisterService(name):
|
|
|
|
"""Unregisters an existing service bot."""
|
|
|
|
assert name in world.services, "Unknown service %s" % name
|
2016-07-08 07:41:39 +02:00
|
|
|
name = name.lower()
|
2016-05-14 23:52:12 +02:00
|
|
|
sbot = world.services[name]
|
|
|
|
for ircnet, uid in sbot.uids.items():
|
2016-07-27 01:26:01 +02:00
|
|
|
ircobj = world.networkobjects[ircnet]
|
|
|
|
# Special case for the main PyLink client. If we're unregistering that,
|
|
|
|
# clear the irc.pseudoclient entry.
|
|
|
|
if name == 'pylink':
|
|
|
|
ircobj.pseudoclient = None
|
|
|
|
|
|
|
|
ircobj.proto.quit(uid, "Service unloaded.")
|
2016-05-14 23:52:12 +02:00
|
|
|
|
|
|
|
del world.services[name]
|
2017-01-01 08:35:27 +01:00
|
|
|
|
|
|
|
def wrapArguments(prefix, args, length, separator=' '):
|
|
|
|
"""
|
|
|
|
Takes a static prefix and a list of arguments, and returns a list of strings
|
|
|
|
with the arguments wrapped across multiple lines. This is useful for breaking up
|
|
|
|
long SJOIN or MODE strings so they aren't cut off by message length limits.
|
|
|
|
"""
|
|
|
|
strings = []
|
|
|
|
|
|
|
|
assert args, "wrapArguments: no arguments given"
|
|
|
|
|
|
|
|
buf = prefix
|
|
|
|
|
|
|
|
while args:
|
|
|
|
assert len(prefix+args[0]) <= length, \
|
|
|
|
"wrapArguments: Argument %r is too long for the given length %s" % (args[0], length)
|
|
|
|
|
|
|
|
# Add arguments until our buffer is up to the length limit.
|
|
|
|
if (len(buf + args[0]) + 1) <= length:
|
|
|
|
if buf != prefix: # Only add a separator if this isn't the first argument of a line
|
|
|
|
buf += separator
|
|
|
|
buf += args.pop(0)
|
|
|
|
else:
|
|
|
|
# Once this is full, add the string to the list and reset the buffer.
|
|
|
|
strings.append(buf)
|
|
|
|
buf = prefix
|
|
|
|
else:
|
|
|
|
strings.append(buf)
|
|
|
|
|
|
|
|
return strings
|