Modified supybot-wizard to work with the new registry... somewhat.

It seems to work and generate the config file which right now defaults to
supybot.conf in the current directory (which will be changed, ofcourse).
Moved some of the wizard's stuff to questions.py and cleaned up.
This commit is contained in:
Stéphan Kochen 2004-01-19 17:44:50 +00:00
parent 9aede17efd
commit fccf2c44de
3 changed files with 300 additions and 396 deletions

View File

@ -13,37 +13,22 @@ import pprint
import socket import socket
import logging import logging
import optparse import optparse
import textwrap
from itertools import imap from itertools import imap
import ansi import ansi
import registry
import conf import conf
import log
import utils import utils
import ircutils import ircutils
import Owner
conf.minimumLogPriority = logging.CRITICAL import questions
from questions import output, yn, anything, something, expect, getpass
useColor = False
def wrapWithBold(f):
def ff(*args, **kwargs):
if useColor:
sys.stdout.write(ansi.BOLD)
ret = f(*args, **kwargs)
if useColor:
print ansi.RESET
return ret
return ff
from questions import yn, anything, something, expect, getpass
yn = wrapWithBold(yn)
expect = wrapWithBold(expect)
anything = wrapWithBold(anything)
something = wrapWithBold(something)
def getPlugins(): def getPlugins():
filenames = [] filenames = []
for dir in conf.pluginDirs: for dir in conf.supybot.directories.plugins():
filenames.extend(os.listdir(dir)) filenames.extend(os.listdir(dir))
plugins = sets.Set([]) plugins = sets.Set([])
for filename in filenames: for filename in filenames:
@ -55,63 +40,58 @@ def getPlugins():
return plugins return plugins
def loadPlugin(name): def loadPlugin(name):
import Owner
try: try:
module = Owner.loadPluginModule(name) module = Owner.loadPluginModule(name)
if hasattr(module, 'Class'): if hasattr(module, 'Class'):
return module return module
else: else:
myPrint("""That plugin loaded fine, but didn't seem to be a real output("""That plugin loaded fine, but didn't seem to be a real
Supybot plugin; there was no Class variable to tell us what class Supybot plugin; there was no Class variable to tell us what class
to load when we load the plugin. We'll skip over it for now, but to load when we load the plugin. We'll skip over it for now, but
you can always add it later.""") you can always add it later.""")
return None return None
except Exception, e: except Exception, e:
myPrint("""We encountered a bit of trouble trying to load plugin %r. output("""We encountered a bit of trouble trying to load plugin %r.
Python told us %r. We'll skip over it for now, you can always add it Python told us %r. We'll skip over it for now, you can always add it
later.""" % (name, utils.exnToString(e))) later.""" % (name, utils.exnToString(e)))
return None return None
def describePlugin(module, showUsage): def describePlugin(module, showUsage):
if module.__doc__: if module.__doc__:
myPrint(module.__doc__, unformatted=False) output(module.__doc__, unformatted=False)
elif hasattr(module.Class, '__doc__'): elif hasattr(module.Class, '__doc__'):
myPrint(module.Class.__doc__, unformatted=False) output(module.Class.__doc__, unformatted=False)
else: else:
myPrint("""Unfortunately, this plugin doesn't seem to have any output("""Unfortunately, this plugin doesn't seem to have any
documentation. Sorry about that.""") documentation. Sorry about that.""")
if showUsage: if showUsage:
if hasattr(module, 'example'): if hasattr(module, 'example'):
if yn('This plugin has a usage example. ' if yn('This plugin has a usage example. '
'Would you like to see it?') == 'y': 'Would you like to see it?', default=False):
pydoc.pager(module.example) pydoc.pager(module.example)
else: else:
myPrint("""This plugin has no usage example.""") output("""This plugin has no usage example.""")
def configurePlugin(module, onStart, afterConnect, advanced): def configurePlugin(module, advanced):
if hasattr(module, 'configure'): if hasattr(module, 'configure'):
myPrint("""Beginning configuration for %s..."""%module.Class.__name__) output("""Beginning configuration for %s..."""%module.Class.__name__)
module.configure(onStart, afterConnect, advanced) module.configure(advanced)
print # Blank line :) print # Blank line :)
myPrint("""Done!""") output("""Done!""")
else: else:
onStart.append('load %s' % module.__name__) Owner.registerPlugin(module, currentValue=True)
def clearLoadedPlugins(onStart, plugins): def clearLoadedPlugins(plugins):
for s in onStart: for plugin, group in conf.supybot.plugins.children.iteritems():
if s.startswith('load '): if plugin in plugins and group():
(_, plugin) = s.split(None, 1)
if plugin in plugins:
plugins.remove(plugin) plugins.remove(plugin)
_windowsVarRe = re.compile(r'%(\w+)%') _windowsVarRe = re.compile(r'%(\w+)%')
def getDirectoryName(default): def getDirectoryName(default):
done = False done = False
while not done: while not done:
dir = anything('What directory do you want to use? ' dir = something('What directory do you want to use?',
'[defaults to %s]' % os.path.join(os.curdir, default)) default=os.path.join(os.curdir, default))
if not dir:
dir = default
dir = os.path.expanduser(dir) dir = os.path.expanduser(dir)
dir = _windowsVarRe.sub(r'$\1', dir) dir = _windowsVarRe.sub(r'$\1', dir)
dir = os.path.expandvars(dir) dir = os.path.expandvars(dir)
@ -121,139 +101,122 @@ def getDirectoryName(default):
done = True done = True
except OSError, e: except OSError, e:
if e.args[0] != 17: # File exists. if e.args[0] != 17: # File exists.
myPrint("""Sorry, I couldn't make that directory for some output("""Sorry, I couldn't make that directory for some
reason. The Operating System told me %s. You're going to reason. The Operating System told me %s. You're going to
have to pick someplace else.""" % e) have to pick someplace else.""" % e)
else: else:
done = True done = True
return os.path.expandvars(os.path.expanduser(dir)) return os.path.expandvars(os.path.expanduser(dir))
def myPrint(s, unformatted=True):
if unformatted:
s = utils.normalizeWhitespace(s)
print textwrap.fill(s)
print
def main(): def main():
global useColor conf.supybot.log.minimumPriority.setValue('CRITICAL')
parser = optparse.OptionParser(usage='Usage: %prog [options]', parser = optparse.OptionParser(usage='Usage: %prog [options]',
version='Supybot %s' % conf.version) version='Supybot %s' % conf.version)
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
nick = ''
user = ''
ident = ''
serverpassword = ''
server = None
onStart = []
afterConnect = []
configVariables = {}
myPrint("""This is a wizard to help you start running supybot. What it output("""This is a wizard to help you start running supybot. What it
will do is create a single Python file whose effect will be that of will do is create a single Python file whose effect will be that of
starting an IRC bot with the options you select here. So hold on tight starting an IRC bot with the options you select here. So hold on tight
and be ready to be interrogated :)""") and be ready to be interrogated :)""")
myPrint("""First of all, we can bold the questions you're asked so you can output("""First of all, we can bold the questions you're asked so you can
easily distinguish the mostly useless blather (like this) from the easily distinguish the mostly useless blather (like this) from the
questions that you actually have to answer.""") questions that you actually have to answer.""")
if yn('Would you like to try this bolding?') == 'y': if yn('Would you like to try this bolding?', default=True):
useColor = True questions.useColor = True
if yn('Do you see this in bold?') == 'n': if not yn('Do you see this in bold?'):
myPrint("""Sorry, it looks like your terminal isn't ANSI compliant. output("""Sorry, it looks like your terminal isn't ANSI compliant.
Try again some other day, on some other terminal :)""") Try again some other day, on some other terminal :)""")
useColor = False questions.useColor = False
else: else:
myPrint("""Great!""") output("""Great!""")
### ###
# Preliminary questions. # Preliminary questions.
### ###
myPrint("""We've got some preliminary things to get out of the way before output("""We've got some preliminary things to get out of the way before
we can really start asking you questions that directly relate to what your we can really start asking you questions that directly relate to what your
bot is going to be like.""") bot is going to be like.""")
# Advanced? # Advanced?
myPrint("""We want to know if you consider yourself an advanced Supybot output("""We want to know if you consider yourself an advanced Supybot
user because some questions are just utterly boring and useless for new user because some questions are just utterly boring and useless for new
users. Others might not make sense unless you've used Supybot for some users. Others might not make sense unless you've used Supybot for some
time.""") time.""")
advanced = yn('Are you an advanced Supybot user?') == 'y' advanced = yn('Are you an advanced Supybot user?', default=False)
### Directories. ### Directories.
myPrint("""Now we've got to ask you some questions about where some of output("""Now we've got to ask you some questions about where some of
your directories are (or, perhaps, will be :)). If you're running this your directories are (or, perhaps, will be :)). If you're running this
wizard from the directory you'll actually be starting your bot from and wizard from the directory you'll actually be starting your bot from and
don't mind creating some directories in the current directory, then just don't mind creating some directories in the current directory, then just
don't give answers to these questions and we'll create the directories we don't give answers to these questions and we'll create the directories we
need right here in this directory.""") need right here in this directory.""")
# logDir # conf.supybot.directories.log
myPrint("""Your bot will need to put his logs somewhere. Do you have any output("""Your bot will need to put his logs somewhere. Do you have any
specific place you'd like them? If not, just press enter and we'll make specific place you'd like them? If not, just press enter and we'll make
a directory named "logs" right here.""") a directory named "logs" right here.""")
conf.logDir = getDirectoryName('logs') conf.supybot.directories.log.setValue(getDirectoryName('logs'))
configVariables['logDir'] = conf.logDir
# dataDir # conf.supybot.directories.data
myPrint("""Your bot will need to put various data somewhere. Things like output("""Your bot will need to put various data somewhere. Things like
databases, downloaded files, etc. Do you have any specific place you'd databases, downloaded files, etc. Do you have any specific place you'd
like the bot to put these things? If not, just press enter and we'll make like the bot to put these things? If not, just press enter and we'll make
a directory named "data" right here.""") a directory named "data" right here.""")
conf.dataDir = getDirectoryName('data') conf.supybot.directories.data.setValue(getDirectoryName('data'))
configVariables['dataDir'] = conf.dataDir
# confDir # conf.supybot.directories.conf
myPrint("""Your bot must know where to find his configuration files. It'll output("""Your bot must know where to find his configuration files. It'll
probably only make one or two, but it's gotta have some place to put them. probably only make one or two, but it's gotta have some place to put them.
Where should that place be? If you don't care, just press enter and we'll Where should that place be? If you don't care, just press enter and we'll
make a directory right here named "conf" where it'll store his stuff. """) make a directory right here named "conf" where it'll store his stuff. """)
conf.confDir = getDirectoryName('conf') conf.supybot.directories.conf.setValue(getDirectoryName('conf'))
configVariables['confDir'] = conf.confDir
myPrint("Good! We're done with the directory stuff.") output("Good! We're done with the directory stuff.")
# pluginDirs # pluginDirs
myPrint("""Your bot will also need to know where to find his plugins at. output("""Your bot will also need to know where to find his plugins at.
Of course, he already knows where the plugins that he came with are, but Of course, he already knows where the plugins that he came with are, but
your own personal plugins that you write for will probably be somewhere your own personal plugins that you write for will probably be somewhere
else. Where do you plan to put those plugins? If you don't know, just else. Where do you plan to put those plugins? If you don't know, just
press enter and we'll put a "plugins" directory right here that you can press enter and we'll put a "plugins" directory right here that you can
stick your own personal plugins in.""") stick your own personal plugins in.""")
pluginDirs = conf.supybot.directories.plugins()
pluginDir = getDirectoryName('plugins') pluginDir = getDirectoryName('plugins')
conf.pluginDirs.insert(0, pluginDir) if pluginDir not in pluginDirs:
myPrint("""Of course, you can have more than one plugin directory.""") pluginDirs.append(pluginDir)
while yn('Would you like to add another plugin directory?') == 'y': output("""Of course, you can have more than one plugin directory.""")
while yn('Would you like to add another plugin directory?',
default=False):
pluginDir = getDirectoryName('plugins') pluginDir = getDirectoryName('plugins')
if pluginDir != 'plugins' and pluginDir not in conf.pluginDirs: if pluginDir not in pluginDirs:
conf.pluginDirs.insert(0, pluginDir) pluginDirs.append(pluginDir)
configVariables['pluginDirs'] = conf.pluginDirs conf.supybot.directories.plugins.setValue(pluginDirs)
### ###
# Bot stuff # Bot stuff
### ###
myPrint("""Now we're going to ask you things that actually relate to the output("""Now we're going to ask you things that actually relate to the
bot you'll be running.""") bot you'll be running.""")
# server # conf.supybot.server
if server:
if yn('You\'ve already got a default server of %s:%s. '
'Do you want to change this?' % server) == 'y':
server = None server = None
while not server: while not server:
serverString = something('What server would you like to connect to?') serverString = something('What server would you like to connect to?')
try: try:
myPrint("""Looking up %s...""" % serverString) output("""Looking up %s...""" % serverString)
ip = socket.gethostbyname(serverString) ip = socket.gethostbyname(serverString)
except: except:
myPrint("""Sorry, I couldn't find that server. Perhaps you output("""Sorry, I couldn't find that server. Perhaps you
misspelled it?""") misspelled it?""")
continue continue
myPrint("""Found %s (%s).""" % (serverString, ip)) output("""Found %s (%s).""" % (serverString, ip))
myPrint("""IRC Servers almost always accept connections on port output("""IRC Servers almost always accept connections on port
6667. They can, however, accept connections anywhere their admin 6667. They can, however, accept connections anywhere their admin
feels like he wants to accept connections from.""") feels like he wants to accept connections from.""")
if yn('Does this server require connection on a non-standard port?') \ if yn('Does this server require connection on a non-standard port?',
=='y': default=False):
port = 0 port = 0
while not port: while not port:
port = something('What port is that?') port = something('What port is that?')
@ -262,30 +225,25 @@ def main():
if not (0 < i < 65536): if not (0 < i < 65536):
raise ValueError raise ValueError
except ValueError: except ValueError:
myPrint("""That's not a valid port.""") output("""That's not a valid port.""")
port = 0 port = 0
else: else:
port = 6667 port = 6667
server = ':'.join(map(str, [serverString, port])) server = ':'.join(map(str, [serverString, port]))
conf.supybot.server.setValue(server)
# nick # conf.supybot.nick
if nick:
if yn("You've already got a default nick of %s. "
"Do you want to change this?" % nick) == 'y':
nick = '' nick = ''
while not nick: while not nick:
nick = something('What nick would you like your bot to use?') nick = something('What nick would you like your bot to use?')
if not ircutils.isNick(nick): if not ircutils.isNick(nick):
myPrint("""That's not a valid nick. Go ahead and pick another.""") output("""That's not a valid nick. Go ahead and pick another.""")
nick = '' nick = ''
conf.supybot.nick.setValue(nick)
# user # conf.supybot.user
if user:
if yn("You've already got a default user of %s. "
"Do you want to change this?" % user) == 'y':
user = '' user = ''
if not user: output("""If you've ever done a /whois on a person, you know that IRC
myPrint("""If you've ever done a /whois on a person, you know that IRC
provides a way for users to show the world their full name. What would provides a way for users to show the world their full name. What would
you like your bot's full name to be? If you don't care, just press you like your bot's full name to be? If you don't care, just press
enter and it'll be the same as your bot's nick.""") enter and it'll be the same as your bot's nick.""")
@ -293,15 +251,12 @@ def main():
user = anything('What would you like your bot\'s full name to be?') user = anything('What would you like your bot\'s full name to be?')
if not user: if not user:
user = nick user = nick
conf.supybot.user.setValue(user)
# ident (if advanced) # conf.supybot.ident (if advanced)
if advanced: if advanced:
if ident:
if yn("You've already got a default ident of %s. "
"Do you want to change this?" % ident) == 'y':
ident = '' ident = ''
if not ident: output("""IRC servers also allow you to set your ident, which they
myPrint("""IRC servers also allow you to set your ident, which they
might need if they can't find your identd server. What would you might need if they can't find your identd server. What would you
like your ident to be? If you don't care, press enter and we'll like your ident to be? If you don't care, press enter and we'll
use the same string as your bot's nick.""") use the same string as your bot's nick.""")
@ -311,49 +266,44 @@ def main():
ident = nick ident = nick
else: else:
ident = nick ident = nick
conf.supybot.ident.setValue(ident)
# password # conf.supybot.password
if serverpassword: output("""Some servers require a password to connect to them. Most
if yn('You\'ve already got a default password of %s. '
'Do you want to change this?' % password) == 'y':
serverpassword = ''
if not serverpassword:
myPrint("""Some servers require a password to connect to them. Most
public servers don't. If you try to connect to a server and for some public servers don't. If you try to connect to a server and for some
reason it just won't work, it might be that you need to set a reason it just won't work, it might be that you need to set a
password.""") password.""")
if yn('Do you want to set such a password?') == 'y': if yn('Do you want to set such a password?', default=False):
serverpassword = getpass() conf.supybot.password.setValue(getpass())
myPrint("""Of course, having an IRC bot isn't the most useful thing in the # conf.supybot.channels
output("""Of course, having an IRC bot isn't the most useful thing in the
world unless you can make that bot join some channels.""") world unless you can make that bot join some channels.""")
if yn('Do you want your bot to join some channels when he connects?')=='y': if yn('Do you want your bot to join some channels when he connects?',
channels = something('What channels? Separate channels by spaces.') default=True):
channels = channels.split() channels = something('What channels? Separate channels with '
'spaces.').split()
while not all(ircutils.isChannel, channels): while not all(ircutils.isChannel, channels):
# FIXME: say which ones weren't channels. # FIXME: say which ones weren't channels.
myPrint("""Not all of those are valid IRC channels. Be sure to output("""Not all of those are valid IRC channels. Be sure to
prefix the channel with # (or +, or !, or &, but no one uses those prefix the channel with # (or +, or !, or &, but no one uses those
channels, really).""") channels, really).""")
channels = something('What channels?') channels = something('What channels?').split()
afterConnect.append('admin join %s' % conf.supybot.channels.setValue(channels)
' '.join(imap(utils.dqrepr, channels)))
### ###
# Plugins # Plugins
### ###
plugins = getPlugins() plugins = getPlugins()
for s in ('Admin','User','Channel','Misc'): for s in ('Admin', 'User', 'Channel', 'Misc', 'Config'):
s = 'load %s' % s configurePlugin(s, advanced)
if s not in onStart: clearLoadedPlugins(plugins)
onStart.append(s)
clearLoadedPlugins(onStart, plugins)
# bulk # bulk
addedBulk = False addedBulk = False
if advanced and yn('Would you like to add plugins en masse first?') == 'y': if advanced and yn('Would you like to add plugins en masse first?'):
addedBulk = True addedBulk = True
myPrint("""The available plugins are %s. What plugins would you like output("""The available plugins are %s. What plugins would you like
to add? If you've changed your mind and would rather not add plugins to add? If you've changed your mind and would rather not add plugins
in bulk like this, just press enter and we'll move on to the individual in bulk like this, just press enter and we'll move on to the individual
plugin configuration.""" % utils.commaAndify(plugins)) plugin configuration.""" % utils.commaAndify(plugins))
@ -361,54 +311,55 @@ def main():
for name in re.split(r',?\s+', massPlugins): for name in re.split(r',?\s+', massPlugins):
module = loadPlugin(name) module = loadPlugin(name)
if module is not None: if module is not None:
configurePlugin(module, onStart, afterConnect, advanced) configurePlugin(module, advanced)
clearLoadedPlugins(onStart, plugins) clearLoadedPlugins(plugins)
# individual # individual
if yn('Would you like to look at plugins individually?') == 'y': if yn('Would you like to look at plugins individually?'):
myPrint("""Next comes your oppurtunity to learn more about the plugins output("""Next comes your oppurtunity to learn more about the plugins
that are available and select some (or all!) of them to run in your that are available and select some (or all!) of them to run in your
bot. Before you have to make a decision, of course, you'll be able to bot. Before you have to make a decision, of course, you'll be able to
see a short description of the plugin and, if you choose, an example see a short description of the plugin and, if you choose, an example
session with the plugin. Let's begin.""") session with the plugin. Let's begin.""")
# until we get example strings again, this will default to false # until we get example strings again, this will default to false
#showUsage =yn('Would you like the option of seeing usage examples?') \ #showUsage =yn('Would you like the option of seeing usage examples?')
# =='y'
showUsage = False showUsage = False
name = expect('What plugin would you like to look at?', plugins) name = expect('What plugin would you like to look at?', plugins)
while name: while name:
module = loadPlugin(name) module = loadPlugin(name)
if module is not None: if module is not None:
describePlugin(module, showUsage) describePlugin(module, showUsage)
if yn('Would you like to load this plugin?') == 'y': if yn('Would you like to load this plugin?', default=True):
configurePlugin(module, onStart, afterConnect, advanced) configurePlugin(module, advanced)
clearLoadedPlugins(onStart, plugins) clearLoadedPlugins(plugins)
if yn('Would you like add another plugin?') == 'n': if not yn('Would you like add another plugin?'):
break break
name = expect('What plugin would you like to look at?', plugins) name = expect('What plugin would you like to look at?', plugins)
### ###
# Sundry # Sundry
### ###
myPrint("""Although supybot offers a supybot-adduser.py script, with which output("""Although supybot offers a supybot-adduser.py script, with which
you can add users to your bot's user database, it's *very* important that you can add users to your bot's user database, it's *very* important that
you have an owner user for you bot.""") you have an owner user for you bot.""")
if yn('Would you like to add an owner user for your bot?') == 'y': if yn('Would you like to add an owner user for your bot?', default=True):
import ircdb import ircdb
name = something('What should the owner\'s username be?') name = something('What should the owner\'s username be?')
try: try:
id = ircdb.users.getUserId(name) id = ircdb.users.getUserId(name)
u = ircdb.users.getUser(id) u = ircdb.users.getUser(id)
if u.checkCapability('owner'): if u.checkCapability('owner'):
myPrint("""That user already exists, and has owner capabilities output("""That user already exists, and has owner capabilities
already. Perhaps you added it before? """) already. Perhaps you added it before? """)
if yn('Do you want to remove its owner capability?')=='y': if yn('Do you want to remove its owner capability?',
default=False):
u.removeCapability('owner') u.removeCapability('owner')
ircdb.users.setUser(id, u) ircdb.users.setUser(id, u)
else: else:
myPrint("""That user already exists, but doesn't have owner output("""That user already exists, but doesn't have owner
capabilities.""") capabilities.""")
if yn('Do you want to add to it owner capabilities?') == 'y': if yn('Do you want to add to it owner capabilities?',
default=False):
u.addCapability('owner') u.addCapability('owner')
ircdb.users.setUser(id, u) ircdb.users.setUser(id, u)
except KeyError: except KeyError:
@ -419,7 +370,7 @@ def main():
u.addCapability('owner') u.addCapability('owner')
ircdb.users.setUser(id, u) ircdb.users.setUser(id, u)
myPrint("""Of course, when you're in an IRC channel you can address the bot output("""Of course, when you're in an IRC channel you can address the bot
by its nick and it will respond, if you give it a valid command (it may or by its nick and it will respond, if you give it a valid command (it may or
may not respond, depending on what your config variable replyWhenNotCommand may not respond, depending on what your config variable replyWhenNotCommand
is set to). But your bot can also respond to a short "prefix character," is set to). But your bot can also respond to a short "prefix character,"
@ -427,36 +378,29 @@ def main():
the same effect. Of course, you don't *have* to have a prefix char, but the same effect. Of course, you don't *have* to have a prefix char, but
if the bot ends up participating significantly in your channel, it'll ease if the bot ends up participating significantly in your channel, it'll ease
things.""") things.""")
if yn('Would you like to set the prefix char(s) for your bot?') == 'y': if yn('Would you like to set the prefix char(s) for your bot?',
myPrint("""Enter any characters you want here, but be careful: they default=True):
output("""Enter any characters you want here, but be careful: they
should be rare enough that people don't accidentally address the bot should be rare enough that people don't accidentally address the bot
(simply because they'll probably be annoyed if they do address the bot (simply because they'll probably be annoyed if they do address the bot
on accident). You can even have more than one. I (jemfinch) am quite on accident). You can even have more than one. I (jemfinch) am quite
partial to @, but that's because I've been using it since my ocamlbot partial to @, but that's because I've been using it since my ocamlbot
days.""") days.""")
import callbacks import callbacks
invalidPrefixChar = False while True:
conf.prefixChars = anything('What would you like your bot\'s ' try:
'prefix character(s) to be?') conf.supybot.prefixChars.setValue(
for c in conf.prefixChars: something('What would you like your '
if c not in conf.validPrefixChars: 'bot\'s prefix character(s) to be?',
invalidPrefixChar = True default='@'))
while invalidPrefixChar: break
invalidPrefixChar = False except registry.InvalidRegistryValue, reason:
for c in conf.prefixChars: output(reason)
if c not in conf.validPrefixChars:
invalidPrefixChar = True
myPrint('%r is not a valid prefixChar.' % c)
conf.prefixChars = anything('That includes one or more invalid '
'prefix characters. What would you '
'like your bot\'s prefix character(s)'
'to be?')
configVariables['prefixChars'] = conf.prefixChars
else: else:
configVariables['prefixChars'] = '' conf.supybot.prefixChars.setValue('')
# enablePipeSyntax # enablePipeSyntax
myPrint("""Supybot allows nested commands. You've probably output("""Supybot allows nested commands. You've probably
read about them in our website or documentation, and almost certainly have read about them in our website or documentation, and almost certainly have
seen them in the plugin examples (if you chose to read them), By default, seen them in the plugin examples (if you chose to read them), By default,
they work with a syntax that looks something like Lisp with square they work with a syntax that looks something like Lisp with square
@ -467,102 +411,104 @@ def main():
syntax is disabled by default because so many people have pipes in their syntax is disabled by default because so many people have pipes in their
nicks, and we've found it to be somewhat frustrating to have to quote such nicks, and we've found it to be somewhat frustrating to have to quote such
nicks in commands.""") nicks in commands.""")
if yn('Would you like to enable the pipe syntax for nesting?') == 'y': conf.supybot.pipeSyntax.setValue(yn('Would you like to enable the pipe '
configVariables['enablePipeSyntax'] = True 'syntax for nesting?', default=False))
### ###
# logging variables. # logging variables.
### ###
# conf.stdoutLogging # conf.supybot.log.stdout
myPrint("""By default, your bot will log not only to files in the logs output("""By default, your bot will log not only to files in the logs
directory you gave it, but also to stdout. We find this useful for directory you gave it, but also to stdout. We find this useful for
debugging, and also just for the pretty output (it's colored!)""") debugging, and also just for the pretty output (it's colored!)""")
if yn('Would you like to turn off this logging to stdout?') == 'y': conf.supybot.log.stdout.setValue(not yn('Would you like to turn off '
configVariables['stdoutLogging'] = False 'this logging to stdout?', default=False))
else: if conf.supybot.log.stdout():
# conf.something # conf.something
myPrint("""Some terminals may not be able to display the pretty colors output("""Some terminals may not be able to display the pretty colors
logged to stderr. By default, though, we turn the colors off for logged to stderr. By default, though, we turn the colors off for
Windows machines and leave it on for *nix machines.""") Windows machines and leave it on for *nix machines.""")
if yn('Would you like to turn this colorization off?') == 'y': if os.name is not 'nt':
configVariables['colorizedStdoutLogging'] = False conf.supybot.log.stdout.colorized.setValue(
not yn('Would you like to turn this colorization off?',
default=False))
# conf.minimumLogPriority # conf.supybot.log.minimumPriority
myPrint("""Your bot can handle debug messages at several priorities, output("""Your bot can handle debug messages at several priorities,
CRITICAL, in decreasing order of priority. By CRITICAL, in decreasing order of priority. By
default, your bot will log all of these priorities. You can, however, default, your bot will log all of these priorities. You can, however,
specify that he only log messages above a certain priority level. Of specify that he only log messages above a certain priority level. Of
course, all error messages will still be logged.""") course, all error messages will still be logged.""")
priority = anything('What would you like the minimum priority to be? ' priority = something('What would you like the minimum priority to be? '
'Just press enter to accept the default.') 'Just press enter to accept the default.',
priority = priority.lower() default='INFO').lower()
while priority and priority not in ['debug', 'info', while priority not in ['debug', 'info', 'warning', 'error', 'critical']:
'warning', 'error', 'critical']: output("""That's not a valid priority. Valid priorities include
myPrint("""That's not a valid priority. Valid priorities include 'DEBUG', 'INFO', 'WARNING', 'ERROR', and 'CRITICAL'""")
'debug', 'info', 'warning', 'error', and 'critical'""") priority = something('What would you like the minimum priority to be?'
priority = anything('What would you like the minimum priority to be? ' ' Just press enter to accept the default.',
'Just press enter to accept the default.') default='INFO').lower()
if priority:
configVariables['minimumLogPriority']=getattr(logging,priority.upper())
if advanced: if advanced:
myPrint("""Here's some stuff you only get to choose if you're an output("""Here's some stuff you only get to choose if you're an
advanced user :)""") advanced user :)""")
# replyWithNickPrefix # conf.supybot.reply.withNickPrefix
myPrint("""By defualt, the bot will respond to all commands with a output("""By defualt, the bot will respond to all commands with a
Nick: <response> response. That is, the user making the command will Nick: <response> response. That is, the user making the command will
have their nick prefixed to the command. If conf.replyWithNickPrefix have their nick prefixed to the command.
is set to False, replies from the bot will not include this nick If supybot.reply.withNickPrefix is set to False, replies from the bot
prefix.""") will not include this nick prefix.""")
if yn('Would you like to turn off this nick prefix?') == 'y': conf.supybot.reply.withNickPrefix.setValue(
configVariables['replyWithNickPrefix'] = False not yn('Would you like to turn off this nick prefix?',
default=False))
# replyWhenAddressedByNick # conf.supybot.reply.whenAddressedByNick
myPrint("""By default, the bot will respond when addressed by its nick. output("""By default, the bot will respond when addressed by its nick.
That is, if the bot's nick is 'botnick', then 'botnick: foo' will call That is, if the bot's nick is 'botnick', then 'botnick: foo' will call
the foo command. If replyWhenAddressedByNick is False, the bot will the foo command. If replyWhenAddressedByNick is False, the bot will
not respond to such messages. Make sure you have a prefixChar set if not respond to such messages. Make sure you have a prefixChar set if
you set this, otherwise people will only be able to communicate with you set this, otherwise people will only be able to communicate with
the bot through private messages.""") the bot through private messages.""")
if yn('Would you like to turn off the bot\'s replies to messages ' conf.supybot.reply.whenAddressedByNick.setValue(
'prefixed with its nick?') == 'y': not yn('Would you like to turn off the bot\'s replies to messages '
configVariables['replyWhenAddressedByNick'] = False 'prefixed with its nick?', default=False))
# showOnlySyntax # conf.supybot.showSimpleSyntax
myPrint("""By default, when the bot receives a message with invalid output("""By default, when the bot receives a message with invalid
arguments, the bot returns the full help (syntax and description) of arguments, the bot returns the full help (syntax and description) of
the command. If showOnlySyntax is set to True, though, the bot will the command. If showOnlySyntax is set to True, though, the bot will
return just the syntax of the command. Of course, the help will still return just the syntax of the command. Of course, the help will still
be available via the help command.""") be available via the help command.""")
if yn('Would you like to show only the syntax of commands when ' conf.supybot.showSimpleSyntax.setValue(
'they\'re given invalid arguments?') == 'y': yn('Would you like to show only the syntax of commands when '
configVariables['showOnlySyntax'] = True 'they\'re given invalid arguments?', default=False))
# replyWhenNotCommand # conf.supybot.reply.whenNotCommand
myPrint("""By default, when people address your bot but don't give it output("""By default, when people address your bot but don't give it
a valid command, it'll respond with a message saying that they didn't a valid command, it'll respond with a message saying that they didn't
give it a valid command. When your channel grows more accustomed to give it a valid command. When your channel grows more accustomed to
the bot, they may prefer that it not do that, since any command you the bot, they may prefer that it not do that, since any command you
give the bot (at least within the included plugins) will respond with give the bot (at least within the included plugins) will respond with
something, so invalid commands are still noticeable. This decreases something, so invalid commands are still noticeable. This decreases
the channel traffic somewhat.""") the channel traffic somewhat.""")
if yn('Would you like to turn off the bot\'s replies when he\'s ' conf.supybot.reply.whenNotCommand.setValue(
'addressed but given a non-command?') == 'y': not yn('Would you like to turn off the bot\'s replies when he\'s '
configVariables['replyWhenNotCommand'] = False 'addressed but given a non-command?', default=False))
# replyWithPrivateNotice # conf.supybot.reply.withPrivateNotice
myPrint("""When a user sends a command to the bot from within a output("""When a user sends a command to the bot from within a
channel, the bot, by default, also responds to that channel. In some channel, the bot, by default, also responds to that channel. In some
rather busy channels this might be considered spam, especially if the rather busy channels this might be considered spam, especially if the
command returns several lines in its result. In this case you may want command returns several lines in its result. In this case you may want
to notice the user instead.""") to notice the user instead.""")
if yn('Would you like the bot to notice replies to users in private ' conf.supybot.reply.withPrivateNotice.setValue(
'when a command is executed in a channel?') == 'y': yn('Would you like the bot to notice replies to users in private '
configVariables['replyWithPrivateNotice'] = True 'when a command is executed in a channel?', default=False))
myPrint("""Here in supybot-developer world, we really like Python. In # allowEval
output("""Here in supybot-developer world, we really like Python. In
fact, we like it so much we just couldn't do without the ability to fact, we like it so much we just couldn't do without the ability to
have our bots evaluate arbitrary Python code. Of course, we are aware have our bots evaluate arbitrary Python code. Of course, we are aware
of the possible security hazards in allowing such a thing, but we're of the possible security hazards in allowing such a thing, but we're
@ -576,57 +522,37 @@ def main():
can't do via a command because the command you want doesn't exist, you can't do via a command because the command you want doesn't exist, you
should tell us and we'll implement the command (rather than make you should tell us and we'll implement the command (rather than make you
allow eval). But either way, here's your chance to enable it.""") allow eval). But either way, here's your chance to enable it.""")
if yn('Would you like to enable allowEval, possibly opening you to ' allowEval = yn('Would you like to enable allowEval, possibly opening '
'a significant security risk?') == 'y': 'you to a significant security risk?', default=False)
configVariables['allowEval'] = True
# throttleTime # conf.supybot.throttleTime
myPrint("""In order to prevent flooding itself off the network, output("""In order to prevent flooding itself off the network,
your bot by default will not send more than one message per second to your bot by default will not send more than one message per second to
the network. This is, however, configurable.""") the network. This is, however, configurable.""")
if yn('Would you like to change the minimum amount of time between ' if yn('Would you like to change the minimum amount of time between '
'messages your bot sends to the network?') == 'y': 'messages your bot sends to the network?', default=False):
throttleTime = None while True:
while throttleTime is None:
throttleTime = something('How long do you want your bot to '
'wait between sending messages to '
'the server? Floating point values '
'are accepted.')
try: try:
throttleTime = float(throttleTime) conf.supybot.throttleTime.setValue(something(
except ValueError: 'How long do you want your bot to wait between '
myPrint("""That's not a valid time. You'll need to give 'sending messages to the server? Floating '
'point values are accepted.'))
break
except InvalidRegistryValue:
output("""That's not a valid time. You'll need to give
a floating-point number.""") a floating-point number.""")
throttleTime = None
### ###
# This is close to the end. # This is close to the end.
### ###
if not advanced: if not advanced:
myPrint("""There are a lot of options we didn't ask you about simply output("""There are a lot of options we didn't ask you about simply
because we'd rather you get up and running and have time left to play because we'd rather you get up and running and have time left to play
around with your bot. But come back and see us! When you've played around with your bot. But come back and see us! When you've played
around with your bot enough to know what you like, what you don't like, around with your bot enough to know what you like, what you don't like,
what you'd like to change, then come back and run this script again what you'd like to change, then come back and run this script again
and tell us you're an advanced user. Some of those questions might be and tell us you're an advanced user. Some of those questions might be
boring, but they'll really help you customize your bot :)""") boring, but they'll really help you customize your bot :)""")
else:
myPrint("""This is your last chance to do any configuration before I
write the bot script.""")
if yn('Would you like to add any commands to be given to the bot '
'before it connects to the server?') == 'y':
command = True
while command:
command = something('Command? ')
onStart.append(command)
command = yn('Would you like to add another command?') == 'y'
if yn('Would you like to add any commands to be given to the bot '
'after it connects to the server?') == 'y':
command = True
while command:
command = Something('Command? ')
afterConnect.append(command)
command = yn('Would you like to add another command?') == 'y'
### ###
# Writing the bot script. # Writing the bot script.
@ -637,15 +563,8 @@ def main():
fd.close() fd.close()
format = pprint.pformat format = pprint.pformat
template = template.replace('"%%nick%%"', repr(nick)) template = template.replace('"%%allowEval%%"',
template = template.replace('"%%user%%"', repr(user)) format(allowEval))
template = template.replace('"%%ident%%"', repr(ident))
template = template.replace('"%%password%%"', repr(serverpassword))
template = template.replace('"%%server%%"', repr(server))
template = template.replace('"%%onStart%%"', format(onStart))
template = template.replace('"%%afterConnect%%"', format(afterConnect))
template = template.replace('"%%configVariables%%"',
format(configVariables))
template = template.replace('/usr/bin/env python', template = template.replace('/usr/bin/env python',
os.path.normpath(sys.executable)) os.path.normpath(sys.executable))
@ -657,7 +576,14 @@ def main():
if os.name == 'posix': if os.name == 'posix':
os.chmod(filename, 0755) os.chmod(filename, 0755)
myPrint("""All done! Your new bot script is %s. If you're running a *nix, # Overwrite temporary minimum log priority
conf.supybot.log.minimumPriority.setValue(priority)
# Save the registry registry
registry.close(conf.supybot, 'supybot.conf')
# Done!
output("""All done! Your new bot script is %s. If you're running a *nix,
you can start your bot script with the command line "./%s". If you're not you can start your bot script with the command line "./%s". If you're not
running a *nix or similar machine, you'll just have to start it like you running a *nix or similar machine, you'll just have to start it like you
start all your other Python scripts.""" % (filename, filename)) start all your other Python scripts.""" % (filename, filename))
@ -666,8 +592,12 @@ if __name__ == '__main__':
try: try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
# We may still be using bold text when exiting during a prompt
if questions.useColor:
import ansi
print ansi.RESET
print print
print print
myPrint("""Well, it looks like you cancelled out of the wizard before output("""Well, it looks like you cancelled out of the wizard before
it was done. Unfortunately, I didn't get to write anything to file. it was done. Unfortunately, I didn't get to write anything to file.
Please run the wizard again to completion.""") Please run the wizard again to completion.""")

View File

@ -33,10 +33,26 @@
__revision__ = "$Id$" __revision__ = "$Id$"
import sys
import textwrap import textwrap
from getpass import getpass as getPass from getpass import getpass as getPass
def expect(prompt, possibilities, recursed=False, doindent=True): import ansi
import utils
useColor = False
def output(s, unformatted=True, useBold=False):
if unformatted:
s = textwrap.fill(utils.normalizeWhitespace(s))
if useColor and useBold:
sys.stdout.write(ansi.BOLD)
print s
if useColor and useBold:
print ansi.RESET
print
def expect(prompt, possibilities, recursed=False, doindent=True, default=None):
"""Prompt the user with prompt, allow them to choose from possibilities. """Prompt the user with prompt, allow them to choose from possibilities.
If possibilities is empty, allow anything. If possibilities is empty, allow anything.
@ -47,70 +63,75 @@ def expect(prompt, possibilities, recursed=False, doindent=True):
else: else:
indent = '' indent = ''
if recursed: if recursed:
print 'Sorry, that response was not an option.' output('Sorry, that response was not an option.', unformatted=False)
if possibilities: if possibilities:
prompt = '%s [%s]' % (originalPrompt, '/'.join(possibilities)) prompt = '%s [%s]' % (originalPrompt, '/'.join(possibilities))
if len(prompt) > 70: if len(prompt) > 70:
prompt = '%s [%s]' % (originalPrompt, '/ '.join(possibilities)) prompt = '%s [%s]' % (originalPrompt, '/ '.join(possibilities))
if default is not None:
prompt = '%s (default: %s)' % (prompt, default)
prompt = textwrap.fill(prompt, subsequent_indent=indent) prompt = textwrap.fill(prompt, subsequent_indent=indent)
else:
prompt = textwrap.fill(prompt)
prompt = prompt.replace('/ ', '/') prompt = prompt.replace('/ ', '/')
prompt = prompt.strip() + ' ' prompt = prompt.strip() + ' '
if useColor:
sys.stdout.write(ansi.BOLD)
s = raw_input(prompt) s = raw_input(prompt)
if useColor:
print ansi.RESET
s = s.strip() s = s.strip()
if possibilities: if possibilities:
if s in possibilities: if s in possibilities:
return s return s
elif not s and default is not None:
return default
else: else:
return expect(originalPrompt, possibilities, recursed=True, return expect(originalPrompt, possibilities, recursed=True,
doindent=doindent) doindent=doindent, default=default)
else:
return s.strip()
def expectWithDefault(prompt, possibilities, default):
"""Same as expect, except with a default."""
indent = ' ' * ((len(prompt)%68) + 2)
prompt = '%s [%s] (default: %s) ' % \
(prompt.strip(), '/'.join(possibilities), default)
if len(prompt) > 70:
prompt = '%s [%s] (default: %s) ' % \
(prompt.strip(), ' / '.join(possibilities), default)
prompt = textwrap.fill(prompt, subsequent_indent=indent)
s = raw_input(prompt)
s = s.strip()
if s in possibilities:
return s
else: else:
if not s and default is not None:
return default return default
return s.strip()
def anything(prompt): def anything(prompt):
"""Allow anything from the user.""" """Allow anything from the user."""
return expect(prompt, []) return expect(prompt, [])
def something(prompt): def something(prompt, default=None):
"""Allow anything *except* nothing from the user.""" """Allow anything *except* nothing from the user."""
s = expect(prompt, []) s = expect(prompt, [], default=default)
while not s: while not s:
print 'Sorry, you must enter a value.' output('Sorry, you must enter a value.', unformatted=False)
s = expect(prompt, []) s = expect(prompt, [], default=default)
return s return s
def yn(prompt): def yn(prompt, default=None):
"""Allow only 'y' or 'n' from the user.""" """Allow only 'y' or 'n' from the user."""
return expect(prompt, ['y', 'n'], doindent=False) if default is not None:
if default:
default = 'y'
else:
default = 'n'
s = expect(prompt, ['y', 'n'], doindent=False, default=default)
if s is 'y':
return True
return False
def getpass(prompt='Enter password: '): def getpass(prompt='Enter password: '):
"""Prompt the user for a password."""
password = '' password = ''
password2 = ' ' password2 = ' '
assert prompt assert prompt
if not prompt[-1].isspace(): if not prompt[-1].isspace():
prompt += ' ' prompt += ' '
while True: while True:
if useColor:
sys.stdout.write(ansi.BOLD)
password = getPass(prompt) password = getPass(prompt)
password2 = getPass('Re-enter password: ') password2 = getPass('Re-enter password: ')
if useColor:
print ansi.RESET
if password != password2: if password != password2:
print 'Passwords don\'t match.' output('Passwords don\'t match.', unformatted=False)
else: else:
break break
return password return password

View File

@ -56,28 +56,16 @@ started = time.time()
import supybot import supybot
import registry
import conf import conf
defaultNick = "%%nick%%" registry.open('supybot.conf')
defaultUser = "%%user%%" conf.allowEval = "%%allowEval%%"
defaultIdent = "%%ident%%"
defaultServer = "%%server%%"
defaultPassword = "%%password%%"
conf.commandsOnStart = "%%onStart%%" if not os.path.exists(conf.supybot.directories.data()):
os.mkdir(conf.supybot.directories.data())
afterConnect = "%%afterConnect%%" if not os.path.exists(conf.supybot.directories.conf()):
os.mkdir(conf.supybot.directories.conf())
configVariables = "%%configVariables%%"
if not isinstance(configVariables, basestring):
for (name, value) in configVariables.iteritems():
setattr(conf, name, value)
if not os.path.exists(conf.dataDir):
os.mkdir(conf.dataDir)
if not os.path.exists(conf.confDir):
os.mkdir(conf.confDir)
# Must be after import conf. # Must be after import conf.
import log import log
@ -105,8 +93,6 @@ if __name__ == '__main__':
# -O (optimizing) # -O (optimizing)
# -n, --nick (nick) # -n, --nick (nick)
# -s, --server (server) # -s, --server (server)
# --startup (commands to run onStart)
# --connect (commands to run afterConnect)
# --config (configuration values) # --config (configuration values)
parser = optparse.OptionParser(usage='Usage: %prog [options]', parser = optparse.OptionParser(usage='Usage: %prog [options]',
version='supybot %s' % conf.version) version='supybot %s' % conf.version)
@ -116,26 +102,22 @@ if __name__ == '__main__':
help='-O optimizes asserts out of the code; ' \ help='-O optimizes asserts out of the code; ' \
'-OO optimizes asserts and uses psyco.') '-OO optimizes asserts and uses psyco.')
parser.add_option('-n', '--nick', action='store', parser.add_option('-n', '--nick', action='store',
dest='nick', default=defaultNick, dest='nick', default=conf.supybot.nick(),
help='nick the bot should use') help='nick the bot should use')
parser.add_option('-s', '--server', action='store', parser.add_option('-s', '--server', action='store',
dest='server', default=defaultServer, dest='server', default=conf.supybot.server(),
help='server to connect to') help='server to connect to')
parser.add_option('-u', '--user', action='store', parser.add_option('-u', '--user', action='store',
dest='user', default=defaultUser, dest='user', default=conf.supybot.user(),
help='full username the bot should use') help='full username the bot should use')
parser.add_option('-i', '--ident', action='store', parser.add_option('-i', '--ident', action='store',
dest='ident', default=defaultIdent, dest='ident', default=conf.supybot.ident(),
help='ident the bot should use') help='ident the bot should use')
parser.add_option('-p', '--password', action='store', parser.add_option('-p', '--password', action='store',
dest='password', default=defaultPassword, dest='password', default=conf.supybot.password(),
help='server password the bot should use') help='server password the bot should use')
parser.add_option('--startup', action='append', dest='onStart', #parser.add_option('--config', action='append', dest='conf',
help='file of additional commands to run at startup.') # help='file of configuration variables to set')
parser.add_option('--connect', action='append', dest='afterConnect',
help='file of additional commands to run after connect')
parser.add_option('--config', action='append', dest='conf',
help='file of configuration variables to set')
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
@ -145,32 +127,18 @@ if __name__ == '__main__':
import psyco import psyco
psyco.full() psyco.full()
if options.onStart: #assignmentRe = re.compile('\s*[:=]\s*')
for filename in options.onStart: #if options.conf:
fd = file(filename) # for filename in options.conf:
for line in fd: # fd = file(filename)
conf.commandsOnStart.append(line.rstrip()) # for line in fd:
fd.close() # (name, valueString) = assignmentRe.split(line.rstrip(), 1)
# try:
if options.afterConnect: # value = eval(valueString)
for filename in options.afterConnect: # except Exception, e:
fd = file(filename) # sys.stderr.write('Invalid configuration value: %r' % \
for line in fd: # valueString)
afterConnect.append(line.rstrip()) # sys.exit(-1)
fd.close()
assignmentRe = re.compile('\s*[:=]\s*')
if options.conf:
for filename in options.conf:
fd = file(filename)
for line in fd:
(name, valueString) = assignmentRe.split(line.rstrip(), 1)
try:
value = eval(valueString)
except Exception, e:
sys.stderr.write('Invalid configuration value: %r' % \
valueString)
sys.exit(-1)
nick = options.nick nick = options.nick
user = options.user user = options.user
@ -190,24 +158,9 @@ if __name__ == '__main__':
import callbacks import callbacks
import Owner import Owner
class ConfigAfterConnect(irclib.IrcCallback):
public = False
def __init__(self, commands):
self.commands = commands
def do376(self, irc, msg):
for command in self.commands:
msg = ircmsgs.privmsg(irc.nick, command, prefix=irc.prefix)
irc.queueMsg(msg)
do377 = do376
do422 = do376 # MOTD File is missing.
# We pre-tokenize the commands just to save on significant amounts of work.
conf.commandsOnStart = map(callbacks.tokenize, conf.commandsOnStart)
irc = irclib.Irc(nick, user, ident, password) irc = irclib.Irc(nick, user, ident, password)
callback = Owner.Class() callback = Owner.Class()
irc.addCallback(callback) irc.addCallback(callback)
irc.addCallback(ConfigAfterConnect(afterConnect))
callback.configure(irc) callback.configure(irc)
driver = drivers.newDriver(server, irc) driver = drivers.newDriver(server, irc)