3
0
mirror of https://github.com/jlu5/PyLink.git synced 2025-01-26 20:24:34 +01:00

move utils.msg() => classes.Irc.msg()

New function gets an extra (optional) "source" argument for specifying a sender UID. It's also shorter since no IRC object has to be passed to utils.
This commit is contained in:
James Lu 2015-09-06 22:23:44 -07:00
parent 7952590436
commit 62e7cc4fca
9 changed files with 106 additions and 103 deletions

View File

@ -166,6 +166,15 @@ class Irc():
else: else:
return return
def msg(self, target, text, notice=False, source=None):
"""Handy function to send messages/notices to clients. Source
is optional, and defaults to the main PyLink client if not specified."""
source = source or self.pseudoclient.uid
if notice:
self.proto.noticeClient(source, target, text)
else:
self.proto.messageClient(source, target, text)
def _disconnect(self): def _disconnect(self):
log.debug('(%s) Canceling pingTimer at %s due to _disconnect() call', self.name, time.time()) log.debug('(%s) Canceling pingTimer at %s due to _disconnect() call', self.name, time.time())
self.connected.clear() self.connected.clear()

View File

@ -26,17 +26,17 @@ def handle_commands(irc, source, command, args):
cmd = cmd_args[0].lower() cmd = cmd_args[0].lower()
cmd_args = cmd_args[1:] cmd_args = cmd_args[1:]
if cmd not in world.bot_commands: if cmd not in world.bot_commands:
utils.msg(irc, source, 'Error: Unknown command %r.' % cmd) irc.msg(source, 'Error: Unknown command %r.' % cmd)
return return
log.info('(%s) Calling command %r for %s', irc.name, cmd, utils.getHostmask(irc, source)) log.info('(%s) Calling command %r for %s', irc.name, cmd, utils.getHostmask(irc, source))
for func in world.bot_commands[cmd]: for func in world.bot_commands[cmd]:
try: try:
func(irc, source, cmd_args) func(irc, source, cmd_args)
except utils.NotAuthenticatedError: except utils.NotAuthenticatedError:
utils.msg(irc, source, 'Error: You are not authorized to perform this operation.') irc.msg(source, 'Error: You are not authorized to perform this operation.')
except Exception as e: except Exception as e:
log.exception('Unhandled exception caught in command %r', cmd) log.exception('Unhandled exception caught in command %r', cmd)
utils.msg(irc, source, 'Uncaught exception in command %r: %s: %s' % (cmd, type(e).__name__, str(e))) irc.msg(source, 'Uncaught exception in command %r: %s: %s' % (cmd, type(e).__name__, str(e)))
utils.add_hook(handle_commands, 'PRIVMSG') utils.add_hook(handle_commands, 'PRIVMSG')
# Handle WHOIS queries, for IRCds that send them across servers (charybdis, UnrealIRCd; NOT InspIRCd). # Handle WHOIS queries, for IRCds that send them across servers (charybdis, UnrealIRCd; NOT InspIRCd).

View File

@ -20,7 +20,7 @@ def spawnclient(irc, source, args):
try: try:
nick, ident, host = args[:3] nick, ident, host = args[:3]
except ValueError: except ValueError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 3: nick, user, host.") irc.msg(source, "Error: Not enough arguments. Needs 3: nick, user, host.")
return return
irc.proto.spawnClient(nick, ident, host) irc.proto.spawnClient(nick, ident, host)
@ -33,10 +33,10 @@ def quit(irc, source, args):
try: try:
nick = args[0] nick = args[0]
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 1-2: nick, reason (optional).") irc.msg(source, "Error: Not enough arguments. Needs 1-2: nick, reason (optional).")
return return
if irc.pseudoclient.uid == utils.nickToUid(irc, nick): if irc.pseudoclient.uid == utils.nickToUid(irc, nick):
utils.msg(irc, source, "Error: Cannot quit the main PyLink PseudoClient!") irc.msg(source, "Error: Cannot quit the main PyLink PseudoClient!")
return return
u = utils.nickToUid(irc, nick) u = utils.nickToUid(irc, nick)
quitmsg = ' '.join(args[1:]) or 'Client Quit' quitmsg = ' '.join(args[1:]) or 'Client Quit'
@ -54,12 +54,12 @@ def joinclient(irc, source, args):
if not clist: if not clist:
raise IndexError raise IndexError
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 2: nick, comma separated list of channels.") irc.msg(source, "Error: Not enough arguments. Needs 2: nick, comma separated list of channels.")
return return
u = utils.nickToUid(irc, nick) u = utils.nickToUid(irc, nick)
for channel in clist: for channel in clist:
if not utils.isChannel(channel): if not utils.isChannel(channel):
utils.msg(irc, source, "Error: Invalid channel name %r." % channel) irc.msg(source, "Error: Invalid channel name %r." % channel)
return return
irc.proto.joinClient(u, channel) irc.proto.joinClient(u, channel)
irc.callHooks([u, 'PYLINK_BOTSPLUGIN_JOIN', {'channel': channel, 'users': [u], irc.callHooks([u, 'PYLINK_BOTSPLUGIN_JOIN', {'channel': channel, 'users': [u],
@ -77,13 +77,13 @@ def nick(irc, source, args):
nick = args[0] nick = args[0]
newnick = args[1] newnick = args[1]
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 2: nick, newnick.") irc.msg(source, "Error: Not enough arguments. Needs 2: nick, newnick.")
return return
u = utils.nickToUid(irc, nick) u = utils.nickToUid(irc, nick)
if newnick in ('0', u): if newnick in ('0', u):
newnick = u newnick = u
elif not utils.isNick(newnick): elif not utils.isNick(newnick):
utils.msg(irc, source, 'Error: Invalid nickname %r.' % newnick) irc.msg(source, 'Error: Invalid nickname %r.' % newnick)
return return
irc.proto.nickClient(u, newnick) irc.proto.nickClient(u, newnick)
irc.callHooks([u, 'PYLINK_BOTSPLUGIN_NICK', {'newnick': newnick, 'oldnick': nick, 'parse_as': 'NICK'}]) irc.callHooks([u, 'PYLINK_BOTSPLUGIN_NICK', {'newnick': newnick, 'oldnick': nick, 'parse_as': 'NICK'}])
@ -99,12 +99,12 @@ def part(irc, source, args):
clist = args[1].split(',') clist = args[1].split(',')
reason = ' '.join(args[2:]) reason = ' '.join(args[2:])
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 2: nick, comma separated list of channels.") irc.msg(source, "Error: Not enough arguments. Needs 2: nick, comma separated list of channels.")
return return
u = utils.nickToUid(irc, nick) u = utils.nickToUid(irc, nick)
for channel in clist: for channel in clist:
if not utils.isChannel(channel): if not utils.isChannel(channel):
utils.msg(irc, source, "Error: Invalid channel name %r." % channel) irc.msg(source, "Error: Invalid channel name %r." % channel)
return return
irc.proto.partClient(u, channel, reason) irc.proto.partClient(u, channel, reason)
irc.callHooks([u, 'PYLINK_BOTSPLUGIN_PART', {'channels': clist, 'text': reason, 'parse_as': 'PART'}]) irc.callHooks([u, 'PYLINK_BOTSPLUGIN_PART', {'channels': clist, 'text': reason, 'parse_as': 'PART'}])
@ -121,12 +121,12 @@ def kick(irc, source, args):
target = args[2] target = args[2]
reason = ' '.join(args[3:]) reason = ' '.join(args[3:])
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 3-4: source nick, channel, target, reason (optional).") irc.msg(source, "Error: Not enough arguments. Needs 3-4: source nick, channel, target, reason (optional).")
return return
u = utils.nickToUid(irc, nick) or nick u = utils.nickToUid(irc, nick) or nick
targetu = utils.nickToUid(irc, target) targetu = utils.nickToUid(irc, target)
if not utils.isChannel(channel): if not utils.isChannel(channel):
utils.msg(irc, source, "Error: Invalid channel name %r." % channel) irc.msg(source, "Error: Invalid channel name %r." % channel)
return return
if utils.isInternalServer(irc, u): if utils.isInternalServer(irc, u):
irc.proto.kickServer(u, channel, targetu, reason) irc.proto.kickServer(u, channel, targetu, reason)
@ -143,17 +143,17 @@ def mode(irc, source, args):
try: try:
modesource, target, modes = args[0], args[1], args[2:] modesource, target, modes = args[0], args[1], args[2:]
except IndexError: except IndexError:
utils.msg(irc, source, 'Error: Not enough arguments. Needs 3: source nick, target, modes to set.') irc.msg(source, 'Error: Not enough arguments. Needs 3: source nick, target, modes to set.')
return return
if not modes: if not modes:
utils.msg(irc, source, "Error: No modes given to set!") irc.msg(source, "Error: No modes given to set!")
return return
parsedmodes = utils.parseModes(irc, target, modes) parsedmodes = utils.parseModes(irc, target, modes)
targetuid = utils.nickToUid(irc, target) targetuid = utils.nickToUid(irc, target)
if targetuid: if targetuid:
target = targetuid target = targetuid
elif not utils.isChannel(target): elif not utils.isChannel(target):
utils.msg(irc, source, "Error: Invalid channel or nick %r." % target) irc.msg(source, "Error: Invalid channel or nick %r." % target)
return return
if utils.isInternalServer(irc, modesource): if utils.isInternalServer(irc, modesource):
irc.proto.modeServer(modesource, target, parsedmodes) irc.proto.modeServer(modesource, target, parsedmodes)
@ -172,21 +172,21 @@ def msg(irc, source, args):
try: try:
msgsource, target, text = args[0], args[1], ' '.join(args[2:]) msgsource, target, text = args[0], args[1], ' '.join(args[2:])
except IndexError: except IndexError:
utils.msg(irc, source, 'Error: Not enough arguments. Needs 3: source nick, target, text.') irc.msg(source, 'Error: Not enough arguments. Needs 3: source nick, target, text.')
return return
sourceuid = utils.nickToUid(irc, msgsource) sourceuid = utils.nickToUid(irc, msgsource)
if not sourceuid: if not sourceuid:
utils.msg(irc, source, 'Error: Unknown user %r.' % msgsource) irc.msg(source, 'Error: Unknown user %r.' % msgsource)
return return
if not utils.isChannel(target): if not utils.isChannel(target):
real_target = utils.nickToUid(irc, target) real_target = utils.nickToUid(irc, target)
if real_target is None: if real_target is None:
utils.msg(irc, source, 'Error: Unknown user %r.' % target) irc.msg(source, 'Error: Unknown user %r.' % target)
return return
else: else:
real_target = target real_target = target
if not text: if not text:
utils.msg(irc, source, 'Error: No text given.') irc.msg(source, 'Error: No text given.')
return return
irc.proto.messageClient(sourceuid, real_target, text) irc.proto.messageClient(sourceuid, real_target, text)
irc.callHooks([sourceuid, 'PYLINK_BOTSPLUGIN_MSG', {'target': real_target, 'text': text, 'parse_as': 'PRIVMSG'}]) irc.callHooks([sourceuid, 'PYLINK_BOTSPLUGIN_MSG', {'target': real_target, 'text': text, 'parse_as': 'PRIVMSG'}])

View File

@ -16,10 +16,10 @@ def status(irc, source, args):
Returns your current PyLink login status.""" Returns your current PyLink login status."""
identified = irc.users[source].identified identified = irc.users[source].identified
if identified: if identified:
utils.msg(irc, source, 'You are identified as \x02%s\x02.' % identified) irc.msg(source, 'You are identified as \x02%s\x02.' % identified)
else: else:
utils.msg(irc, source, 'You are not identified as anyone.') irc.msg(source, 'You are not identified as anyone.')
utils.msg(irc, source, 'Operator access: \x02%s\x02' % bool(utils.isOper(irc, source))) irc.msg(source, 'Operator access: \x02%s\x02' % bool(utils.isOper(irc, source)))
@utils.add_cmd @utils.add_cmd
def identify(irc, source, args): def identify(irc, source, args):
@ -29,17 +29,17 @@ def identify(irc, source, args):
try: try:
username, password = args[0], args[1] username, password = args[0], args[1]
except IndexError: except IndexError:
utils.msg(irc, source, 'Error: Not enough arguments.') irc.msg(source, 'Error: Not enough arguments.')
return return
# Usernames are case-insensitive, passwords are NOT. # Usernames are case-insensitive, passwords are NOT.
if username.lower() == conf['login']['user'].lower() and password == conf['login']['password']: if username.lower() == conf['login']['user'].lower() and password == conf['login']['password']:
realuser = conf['login']['user'] realuser = conf['login']['user']
irc.users[source].identified = realuser irc.users[source].identified = realuser
utils.msg(irc, source, 'Successfully logged in as %s.' % realuser) irc.msg(source, 'Successfully logged in as %s.' % realuser)
log.info("(%s) Successful login to %r by %s.", log.info("(%s) Successful login to %r by %s.",
irc.name, username, utils.getHostmask(irc, source)) irc.name, username, utils.getHostmask(irc, source))
else: else:
utils.msg(irc, source, 'Error: Incorrect credentials.') irc.msg(source, 'Error: Incorrect credentials.')
u = irc.users[source] u = irc.users[source]
log.warning("(%s) Failed login to %r from %s.", log.warning("(%s) Failed login to %r from %s.",
irc.name, username, utils.getHostmask(irc, source)) irc.name, username, utils.getHostmask(irc, source))
@ -54,8 +54,8 @@ def listcommands(irc, source, args):
nfuncs = len(world.bot_commands[cmd]) nfuncs = len(world.bot_commands[cmd])
if nfuncs > 1: if nfuncs > 1:
cmds[idx] = '%s(x%s)' % (cmd, nfuncs) cmds[idx] = '%s(x%s)' % (cmd, nfuncs)
utils.msg(irc, source, 'Available commands include: %s' % ', '.join(cmds)) irc.msg(source, 'Available commands include: %s' % ', '.join(cmds))
utils.msg(irc, source, 'To see help on a specific command, type \x02help <command>\x02.') irc.msg(source, 'To see help on a specific command, type \x02help <command>\x02.')
utils.add_cmd(listcommands, 'list') utils.add_cmd(listcommands, 'list')
@utils.add_cmd @utils.add_cmd
@ -69,12 +69,12 @@ def help(irc, source, args):
listcommands(irc, source, args) listcommands(irc, source, args)
return return
if command not in world.bot_commands: if command not in world.bot_commands:
utils.msg(irc, source, 'Error: Unknown command %r.' % command) irc.msg(source, 'Error: Unknown command %r.' % command)
return return
else: else:
funcs = world.bot_commands[command] funcs = world.bot_commands[command]
if len(funcs) > 1: if len(funcs) > 1:
utils.msg(irc, source, 'The following \x02%s\x02 plugins bind to the \x02%s\x02 command: %s' irc.msg(source, 'The following \x02%s\x02 plugins bind to the \x02%s\x02 command: %s'
% (len(funcs), command, ', '.join([func.__module__ for func in funcs]))) % (len(funcs), command, ', '.join([func.__module__ for func in funcs])))
for func in funcs: for func in funcs:
doc = func.__doc__ doc = func.__doc__
@ -85,9 +85,9 @@ def help(irc, source, args):
# arguments the command takes. # arguments the command takes.
lines[0] = '\x02%s %s\x02 (plugin: %r)' % (command, lines[0], mod) lines[0] = '\x02%s %s\x02 (plugin: %r)' % (command, lines[0], mod)
for line in lines: for line in lines:
utils.msg(irc, source, line.strip()) irc.msg(source, line.strip())
else: else:
utils.msg(irc, source, "Error: Command %r (from plugin %r) " irc.msg(source, "Error: Command %r (from plugin %r) "
"doesn't offer any help." % (command, mod)) "doesn't offer any help." % (command, mod))
return return
@ -99,17 +99,17 @@ def showuser(irc, source, args):
try: try:
target = args[0] target = args[0]
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 1: nick.") irc.msg(source, "Error: Not enough arguments. Needs 1: nick.")
return return
u = utils.nickToUid(irc, target) or target u = utils.nickToUid(irc, target) or target
# Only show private info if the person is calling 'showuser' on themselves, # Only show private info if the person is calling 'showuser' on themselves,
# or is an oper. # or is an oper.
verbose = utils.isOper(irc, source) or u == source verbose = utils.isOper(irc, source) or u == source
if u not in irc.users: if u not in irc.users:
utils.msg(irc, source, 'Error: Unknown user %r.' % target) irc.msg(source, 'Error: Unknown user %r.' % target)
return return
f = lambda s: utils.msg(irc, source, s) f = lambda s: irc.msg(source, s)
userobj = irc.users[u] userobj = irc.users[u]
f('Information on user \x02%s\x02 (%s@%s): %s' % (userobj.nick, userobj.ident, f('Information on user \x02%s\x02 (%s@%s): %s' % (userobj.nick, userobj.ident,
userobj.host, userobj.realname)) userobj.host, userobj.realname))

View File

@ -14,7 +14,7 @@ def _exec(irc, source, args):
utils.checkAuthenticated(irc, source, allowOper=False) utils.checkAuthenticated(irc, source, allowOper=False)
args = ' '.join(args) args = ' '.join(args)
if not args.strip(): if not args.strip():
utils.msg(irc, source, 'No code entered!') irc.msg(source, 'No code entered!')
return return
log.info('(%s) Executing %r for %s', irc.name, args, utils.getHostmask(irc, source)) log.info('(%s) Executing %r for %s', irc.name, args, utils.getHostmask(irc, source))
exec(args, globals(), locals()) exec(args, globals(), locals())

View File

@ -14,6 +14,6 @@ def hook_privmsg(irc, source, command, args):
channel = args['target'] channel = args['target']
text = args['text'] text = args['text']
if utils.isChannel(channel) and irc.pseudoclient.nick in text: if utils.isChannel(channel) and irc.pseudoclient.nick in text:
utils.msg(irc, channel, 'hi there!') irc.msg(channel, 'hi there!')
log.info('%s said my name on channel %s (PRIVMSG hook caught)' % (source, channel)) log.info('%s said my name on channel %s (PRIVMSG hook caught)' % (source, channel))
utils.add_hook(hook_privmsg, 'PRIVMSG') utils.add_hook(hook_privmsg, 'PRIVMSG')

View File

@ -22,12 +22,12 @@ def disconnect(irc, source, args):
netname = args[0] netname = args[0]
network = world.networkobjects[netname] network = world.networkobjects[netname]
except IndexError: # No argument given. except IndexError: # No argument given.
utils.msg(irc, source, 'Error: Not enough arguments (needs 1: network name (case sensitive)).') irc.msg(source, 'Error: Not enough arguments (needs 1: network name (case sensitive)).')
return return
except KeyError: # Unknown network. except KeyError: # Unknown network.
utils.msg(irc, source, 'Error: No such network "%s" (case sensitive).' % netname) irc.msg(source, 'Error: No such network "%s" (case sensitive).' % netname)
return return
utils.msg(irc, source, "Done.") irc.msg(source, "Done.")
# Abort the connection! Simple as that. # Abort the connection! Simple as that.
network.aborted.set() network.aborted.set()
@ -41,18 +41,18 @@ def connect(irc, source, args):
netname = args[0] netname = args[0]
network = world.networkobjects[netname] network = world.networkobjects[netname]
except IndexError: # No argument given. except IndexError: # No argument given.
utils.msg(irc, source, 'Error: Not enough arguments (needs 1: network name (case sensitive)).') irc.msg(source, 'Error: Not enough arguments (needs 1: network name (case sensitive)).')
return return
except KeyError: # Unknown network. except KeyError: # Unknown network.
utils.msg(irc, source, 'Error: No such network "%s" (case sensitive).' % netname) irc.msg(source, 'Error: No such network "%s" (case sensitive).' % netname)
return return
if network.connection_thread.is_alive(): if network.connection_thread.is_alive():
utils.msg(irc, source, 'Error: Network "%s" seems to be already connected.' % netname) irc.msg(source, 'Error: Network "%s" seems to be already connected.' % netname)
else: # Reconnect the network! else: # Reconnect the network!
network.initVars() network.initVars()
network.connection_thread = threading.Thread(target=network.connect) network.connection_thread = threading.Thread(target=network.connect)
network.connection_thread.start() network.connection_thread.start()
utils.msg(irc, source, "Done.") irc.msg(source, "Done.")
@utils.add_cmd @utils.add_cmd
def autoconnect(irc, source, args): def autoconnect(irc, source, args):
@ -66,13 +66,13 @@ def autoconnect(irc, source, args):
seconds = float(args[1]) seconds = float(args[1])
network = world.networkobjects[netname] network = world.networkobjects[netname]
except IndexError: # Arguments not given. except IndexError: # Arguments not given.
utils.msg(irc, source, 'Error: Not enough arguments (needs 2: network name (case sensitive), autoconnect time (in seconds)).') irc.msg(source, 'Error: Not enough arguments (needs 2: network name (case sensitive), autoconnect time (in seconds)).')
return return
except KeyError: # Unknown network. except KeyError: # Unknown network.
utils.msg(irc, source, 'Error: No such network "%s" (case sensitive).' % netname) irc.msg(source, 'Error: No such network "%s" (case sensitive).' % netname)
return return
except ValueError: except ValueError:
utils.msg(irc, source, 'Error: Invalid argument "%s" for <seconds>.' % seconds) irc.msg(source, 'Error: Invalid argument "%s" for <seconds>.' % seconds)
return return
network.serverdata['autoconnect'] = seconds network.serverdata['autoconnect'] = seconds
utils.msg(irc, source, "Done.") irc.msg(source, "Done.")

View File

@ -109,9 +109,9 @@ def save(irc, source, args):
Saves the relay database to disk.""" Saves the relay database to disk."""
if utils.isOper(irc, source): if utils.isOper(irc, source):
exportDB() exportDB()
utils.msg(irc, source, 'Done.') irc.msg(source, 'Done.')
else: else:
utils.msg(irc, source, 'Error: You are not authenticated!') irc.msg(source, 'Error: You are not authenticated!')
return return
def getPrefixModes(irc, remoteirc, channel, user): def getPrefixModes(irc, remoteirc, channel, user):
@ -352,7 +352,7 @@ def handle_privmsg(irc, numeric, command, args):
# it's the only way we can make sure they have a spawned client on ALL # it's the only way we can make sure they have a spawned client on ALL
# of the linked networks. This affects -n channels too; see # of the linked networks. This affects -n channels too; see
# https://github.com/GLolol/PyLink/issues/91 for an explanation of why. # https://github.com/GLolol/PyLink/issues/91 for an explanation of why.
utils.msg(irc, numeric, 'Error: You must be in %r in order to send ' irc.msg(numeric, 'Error: You must be in %r in order to send '
'messages over the relay.' % target, notice=True) 'messages over the relay.' % target, notice=True)
return return
if utils.isChannel(target): if utils.isChannel(target):
@ -376,7 +376,7 @@ def handle_privmsg(irc, numeric, command, args):
# on the remote network, and we won't have anything to send our # on the remote network, and we won't have anything to send our
# messages from. # messages from.
if homenet not in remoteusers.keys(): if homenet not in remoteusers.keys():
utils.msg(irc, numeric, 'Error: You must be in a common channel ' irc.msg(numeric, 'Error: You must be in a common channel '
'with %r in order to send messages.' % \ 'with %r in order to send messages.' % \
irc.users[target].nick, notice=True) irc.users[target].nick, notice=True)
return return
@ -436,7 +436,7 @@ def handle_kick(irc, source, command, args):
log.info('(%s) Relay claim: Blocked KICK (reason %r) from %s to relay client %s/%s on %s.', log.info('(%s) Relay claim: Blocked KICK (reason %r) from %s to relay client %s/%s on %s.',
irc.name, args['text'], irc.users[source].nick, irc.name, args['text'], irc.users[source].nick,
remoteirc.users[real_target].nick, remoteirc.name, channel) remoteirc.users[real_target].nick, remoteirc.name, channel)
utils.msg(irc, kicker, "This channel is claimed; your kick to " irc.msg(kicker, "This channel is claimed; your kick to "
"%s has been blocked because you are not " "%s has been blocked because you are not "
"(half)opped." % channel, notice=True) "(half)opped." % channel, notice=True)
else: else:
@ -681,7 +681,7 @@ def handle_kill(irc, numeric, command, args):
log.info('(%s) Relay claim: Blocked KILL (reason %r) from %s to relay client %s/%s.', log.info('(%s) Relay claim: Blocked KILL (reason %r) from %s to relay client %s/%s.',
irc.name, args['text'], irc.users[numeric].nick, irc.name, args['text'], irc.users[numeric].nick,
remoteirc.users[realuser[1]].nick, realuser[0]) remoteirc.users[realuser[1]].nick, realuser[0])
utils.msg(irc, numeric, "Your kill to %s has been blocked " irc.msg(numeric, "Your kill to %s has been blocked "
"because PyLink does not allow killing" "because PyLink does not allow killing"
" users over the relay at this time." % \ " users over the relay at this time." % \
userdata.nick, notice=True) userdata.nick, notice=True)
@ -797,20 +797,20 @@ def create(irc, source, args):
try: try:
channel = utils.toLower(irc, args[0]) channel = utils.toLower(irc, args[0])
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 1: channel.") irc.msg(source, "Error: Not enough arguments. Needs 1: channel.")
return return
if not utils.isChannel(channel): if not utils.isChannel(channel):
utils.msg(irc, source, 'Error: Invalid channel %r.' % channel) irc.msg(source, 'Error: Invalid channel %r.' % channel)
return return
if source not in irc.channels[channel].users: if source not in irc.channels[channel].users:
utils.msg(irc, source, 'Error: You must be in %r to complete this operation.' % channel) irc.msg(source, 'Error: You must be in %r to complete this operation.' % channel)
return return
if not utils.isOper(irc, source): if not utils.isOper(irc, source):
utils.msg(irc, source, 'Error: You must be opered in order to complete this operation.') irc.msg(source, 'Error: You must be opered in order to complete this operation.')
return return
db[(irc.name, channel)] = {'claim': [irc.name], 'links': set(), 'blocked_nets': set()} db[(irc.name, channel)] = {'claim': [irc.name], 'links': set(), 'blocked_nets': set()}
initializeChannel(irc, channel) initializeChannel(irc, channel)
utils.msg(irc, source, 'Done.') irc.msg(source, 'Done.')
@utils.add_cmd @utils.add_cmd
def destroy(irc, source, args): def destroy(irc, source, args):
@ -820,13 +820,13 @@ def destroy(irc, source, args):
try: try:
channel = utils.toLower(irc, args[0]) channel = utils.toLower(irc, args[0])
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 1: channel.") irc.msg(source, "Error: Not enough arguments. Needs 1: channel.")
return return
if not utils.isChannel(channel): if not utils.isChannel(channel):
utils.msg(irc, source, 'Error: Invalid channel %r.' % channel) irc.msg(source, 'Error: Invalid channel %r.' % channel)
return return
if not utils.isOper(irc, source): if not utils.isOper(irc, source):
utils.msg(irc, source, 'Error: You must be opered in order to complete this operation.') irc.msg(source, 'Error: You must be opered in order to complete this operation.')
return return
entry = (irc.name, channel) entry = (irc.name, channel)
@ -835,9 +835,9 @@ def destroy(irc, source, args):
removeChannel(world.networkobjects.get(link[0]), link[1]) removeChannel(world.networkobjects.get(link[0]), link[1])
removeChannel(irc, channel) removeChannel(irc, channel)
del db[entry] del db[entry]
utils.msg(irc, source, 'Done.') irc.msg(source, 'Done.')
else: else:
utils.msg(irc, source, 'Error: No such relay %r exists.' % channel) irc.msg(source, 'Error: No such relay %r exists.' % channel)
return return
@utils.add_cmd @utils.add_cmd
@ -850,7 +850,7 @@ def link(irc, source, args):
channel = utils.toLower(irc, args[1]) channel = utils.toLower(irc, args[1])
remotenet = args[0].lower() remotenet = args[0].lower()
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 2-3: remote netname, channel, local channel name (optional).") irc.msg(source, "Error: Not enough arguments. Needs 2-3: remote netname, channel, local channel name (optional).")
return return
try: try:
localchan = utils.toLower(irc, args[2]) localchan = utils.toLower(irc, args[2])
@ -858,39 +858,39 @@ def link(irc, source, args):
localchan = channel localchan = channel
for c in (channel, localchan): for c in (channel, localchan):
if not utils.isChannel(c): if not utils.isChannel(c):
utils.msg(irc, source, 'Error: Invalid channel %r.' % c) irc.msg(source, 'Error: Invalid channel %r.' % c)
return return
if source not in irc.channels[localchan].users: if source not in irc.channels[localchan].users:
utils.msg(irc, source, 'Error: You must be in %r to complete this operation.' % localchan) irc.msg(source, 'Error: You must be in %r to complete this operation.' % localchan)
return return
if not utils.isOper(irc, source): if not utils.isOper(irc, source):
utils.msg(irc, source, 'Error: You must be opered in order to complete this operation.') irc.msg(source, 'Error: You must be opered in order to complete this operation.')
return return
if remotenet not in world.networkobjects: if remotenet not in world.networkobjects:
utils.msg(irc, source, 'Error: No network named %r exists.' % remotenet) irc.msg(source, 'Error: No network named %r exists.' % remotenet)
return return
localentry = findRelay((irc.name, localchan)) localentry = findRelay((irc.name, localchan))
if localentry: if localentry:
utils.msg(irc, source, 'Error: Channel %r is already part of a relay.' % localchan) irc.msg(source, 'Error: Channel %r is already part of a relay.' % localchan)
return return
try: try:
entry = db[(remotenet, channel)] entry = db[(remotenet, channel)]
except KeyError: except KeyError:
utils.msg(irc, source, 'Error: No such relay %r exists.' % channel) irc.msg(source, 'Error: No such relay %r exists.' % channel)
return return
else: else:
if irc.name in entry['blocked_nets']: if irc.name in entry['blocked_nets']:
utils.msg(irc, source, 'Error: Access denied (network is banned from linking to this channel).') irc.msg(source, 'Error: Access denied (network is banned from linking to this channel).')
return return
for link in entry['links']: for link in entry['links']:
if link[0] == irc.name: if link[0] == irc.name:
utils.msg(irc, source, "Error: Remote channel '%s%s' is already" irc.msg(source, "Error: Remote channel '%s%s' is already"
" linked here as %r." % (remotenet, " linked here as %r." % (remotenet,
channel, link[1])) channel, link[1]))
return return
entry['links'].add((irc.name, localchan)) entry['links'].add((irc.name, localchan))
initializeChannel(irc, localchan) initializeChannel(irc, localchan)
utils.msg(irc, source, 'Done.') irc.msg(source, 'Done.')
@utils.add_cmd @utils.add_cmd
def delink(irc, source, args): def delink(irc, source, args):
@ -901,23 +901,23 @@ def delink(irc, source, args):
try: try:
channel = utils.toLower(irc, args[0]) channel = utils.toLower(irc, args[0])
except IndexError: except IndexError:
utils.msg(irc, source, "Error: Not enough arguments. Needs 1-2: channel, remote netname (optional).") irc.msg(source, "Error: Not enough arguments. Needs 1-2: channel, remote netname (optional).")
return return
try: try:
remotenet = args[1].lower() remotenet = args[1].lower()
except IndexError: except IndexError:
remotenet = None remotenet = None
if not utils.isOper(irc, source): if not utils.isOper(irc, source):
utils.msg(irc, source, 'Error: You must be opered in order to complete this operation.') irc.msg(source, 'Error: You must be opered in order to complete this operation.')
return return
if not utils.isChannel(channel): if not utils.isChannel(channel):
utils.msg(irc, source, 'Error: Invalid channel %r.' % channel) irc.msg(source, 'Error: Invalid channel %r.' % channel)
return return
entry = findRelay((irc.name, channel)) entry = findRelay((irc.name, channel))
if entry: if entry:
if entry[0] == irc.name: # We own this channel. if entry[0] == irc.name: # We own this channel.
if not remotenet: if not remotenet:
utils.msg(irc, source, "Error: You must select a network to " irc.msg(source, "Error: You must select a network to "
"delink, or use the 'destroy' command to remove " "delink, or use the 'destroy' command to remove "
"this relay entirely (it was created on the current " "this relay entirely (it was created on the current "
"network).") "network).")
@ -930,9 +930,9 @@ def delink(irc, source, args):
else: else:
removeChannel(irc, channel) removeChannel(irc, channel)
db[entry]['links'].remove((irc.name, channel)) db[entry]['links'].remove((irc.name, channel))
utils.msg(irc, source, 'Done.') irc.msg(source, 'Done.')
else: else:
utils.msg(irc, source, 'Error: No such relay %r.' % channel) irc.msg(source, 'Error: No such relay %r.' % channel)
def initializeAll(irc): def initializeAll(irc):
log.debug('(%s) initializeAll: waiting for world.started', irc.name) log.debug('(%s) initializeAll: waiting for world.started', irc.name)
@ -1007,7 +1007,7 @@ def linked(irc, source, args):
networks = list(world.networkobjects.keys()) networks = list(world.networkobjects.keys())
networks.remove(irc.name) networks.remove(irc.name)
s = 'Connected networks: \x02%s\x02 %s' % (irc.name, ' '.join(networks)) s = 'Connected networks: \x02%s\x02 %s' % (irc.name, ' '.join(networks))
utils.msg(irc, source, s) irc.msg(source, s)
# Sort relay DB by channel name, and then sort. # Sort relay DB by channel name, and then sort.
for k, v in sorted(db.items(), key=lambda channel: channel[0][1]): for k, v in sorted(db.items(), key=lambda channel: channel[0][1]):
s = '\x02%s%s\x02 ' % k s = '\x02%s%s\x02 ' % k
@ -1015,7 +1015,7 @@ def linked(irc, source, args):
s += ' '.join([''.join(link) for link in v['links']]) s += ' '.join([''.join(link) for link in v['links']])
else: else:
s += '(no relays yet)' s += '(no relays yet)'
utils.msg(irc, source, s) irc.msg(source, s)
def handle_away(irc, numeric, command, args): def handle_away(irc, numeric, command, args):
for netname, user in relayusers[(irc.name, numeric)].items(): for netname, user in relayusers[(irc.name, numeric)].items():
@ -1039,12 +1039,12 @@ def handle_invite(irc, source, command, args):
remotechan = findRemoteChan(irc, remoteirc, channel) remotechan = findRemoteChan(irc, remoteirc, channel)
remotesource = getRemoteUser(irc, remoteirc, source, spawnIfMissing=False) remotesource = getRemoteUser(irc, remoteirc, source, spawnIfMissing=False)
if remotesource is None: if remotesource is None:
utils.msg(irc, source, 'Error: You must be in a common channel ' irc.msg(source, 'Error: You must be in a common channel '
'with %s to invite them to channels.' % \ 'with %s to invite them to channels.' % \
irc.users[target].nick, irc.users[target].nick,
notice=True) notice=True)
elif remotechan is None: elif remotechan is None:
utils.msg(irc, source, 'Error: You cannot invite someone to a ' irc.msg(source, 'Error: You cannot invite someone to a '
'channel not on their network!', 'channel not on their network!',
notice=True) notice=True)
else: else:
@ -1060,43 +1060,43 @@ def linkacl(irc, source, args):
LINKACL LIST returns a list of blocked networks for a channel, while the ALLOW and DENY subcommands allow manipulating this blacklist.""" LINKACL LIST returns a list of blocked networks for a channel, while the ALLOW and DENY subcommands allow manipulating this blacklist."""
missingargs = "Error: Not enough arguments. Needs 2-3: subcommand (ALLOW/DENY/LIST), channel, remote network (for ALLOW/DENY)." missingargs = "Error: Not enough arguments. Needs 2-3: subcommand (ALLOW/DENY/LIST), channel, remote network (for ALLOW/DENY)."
if not utils.isOper(irc, source): if not utils.isOper(irc, source):
utils.msg(irc, source, 'Error: You must be opered in order to complete this operation.') irc.msg(source, 'Error: You must be opered in order to complete this operation.')
return return
try: try:
cmd = args[0].lower() cmd = args[0].lower()
channel = utils.toLower(irc, args[1]) channel = utils.toLower(irc, args[1])
except IndexError: except IndexError:
utils.msg(irc, source, missingargs) irc.msg(source, missingargs)
return return
if not utils.isChannel(channel): if not utils.isChannel(channel):
utils.msg(irc, source, 'Error: Invalid channel %r.' % channel) irc.msg(source, 'Error: Invalid channel %r.' % channel)
return return
relay = findRelay((irc.name, channel)) relay = findRelay((irc.name, channel))
if not relay: if not relay:
utils.msg(irc, source, 'Error: No such relay %r exists.' % channel) irc.msg(source, 'Error: No such relay %r exists.' % channel)
return return
if cmd == 'list': if cmd == 'list':
s = 'Blocked networks for \x02%s\x02: \x02%s\x02' % (channel, ', '.join(db[relay]['blocked_nets']) or '(empty)') s = 'Blocked networks for \x02%s\x02: \x02%s\x02' % (channel, ', '.join(db[relay]['blocked_nets']) or '(empty)')
utils.msg(irc, source, s) irc.msg(source, s)
return return
try: try:
remotenet = args[2] remotenet = args[2]
except IndexError: except IndexError:
utils.msg(irc, source, missingargs) irc.msg(source, missingargs)
return return
if cmd == 'deny': if cmd == 'deny':
db[relay]['blocked_nets'].add(remotenet) db[relay]['blocked_nets'].add(remotenet)
utils.msg(irc, source, 'Done.') irc.msg(source, 'Done.')
elif cmd == 'allow': elif cmd == 'allow':
try: try:
db[relay]['blocked_nets'].remove(remotenet) db[relay]['blocked_nets'].remove(remotenet)
except KeyError: except KeyError:
utils.msg(irc, source, 'Error: Network %r is not on the blacklist for %r.' % (remotenet, channel)) irc.msg(source, 'Error: Network %r is not on the blacklist for %r.' % (remotenet, channel))
else: else:
utils.msg(irc, source, 'Done.') irc.msg(source, 'Done.')
else: else:
utils.msg(irc, source, 'Error: Unknown subcommand %r: valid ones are ALLOW, DENY, and LIST.' % cmd) irc.msg(source, 'Error: Unknown subcommand %r: valid ones are ALLOW, DENY, and LIST.' % cmd)
@utils.add_cmd @utils.add_cmd
def showuser(irc, source, args): def showuser(irc, source, args):
@ -1125,11 +1125,11 @@ def showuser(irc, source, args):
remotenet, remoteuser = r remotenet, remoteuser = r
remoteirc = world.networkobjects[remotenet] remoteirc = world.networkobjects[remotenet]
nicks.append('%s: \x02%s\x02' % (remotenet, remoteirc.users[remoteuser].nick)) nicks.append('%s: \x02%s\x02' % (remotenet, remoteirc.users[remoteuser].nick))
utils.msg(irc, source, "\x02Relay nicks\x02: %s" % ', '.join(nicks)) irc.msg(source, "\x02Relay nicks\x02: %s" % ', '.join(nicks))
relaychannels = [] relaychannels = []
for ch in irc.users[u].channels: for ch in irc.users[u].channels:
relay = findRelay((irc.name, ch)) relay = findRelay((irc.name, ch))
if relay: if relay:
relaychannels.append(''.join(relay)) relaychannels.append(''.join(relay))
if relaychannels and (utils.isOper(irc, source) or u == source): if relaychannels and (utils.isOper(irc, source) or u == source):
utils.msg(irc, source, "\x02Relay channels\x02: %s" % ' '.join(relaychannels)) irc.msg(source, "\x02Relay channels\x02: %s" % ' '.join(relaychannels))

View File

@ -98,12 +98,6 @@ class TS6SIDGenerator():
self.increment() self.increment()
return sid return sid
def msg(irc, target, text, notice=False):
if notice:
irc.proto.noticeClient(irc.pseudoclient.uid, target, text)
else:
irc.proto.messageClient(irc.pseudoclient.uid, target, text)
def add_cmd(func, name=None): def add_cmd(func, name=None):
if name is None: if name is None:
name = func.__name__ name = func.__name__