Esempio n. 1
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    Jira = conf.registerPlugin('Jira', True)
    server = something("""What is the URL for the Jira instance?""")
    user = something("""What is the username for the Jira user?""")
    password = something("""What is the password for the Jira user?""")
    template = something("""What output template would you like?""",
            default=template)
    lookup = yn("""Do you want to lookup Jira issues once they appear on a channel?""", default=True)
    snarfRegex = something("""What is the prefix for your Jira issue keys?""",
            default="JRA")
    snarfRegex = ''.join((snarfRegex, '-[0-9]+'))
    verifySSL = yn("""Would you like the plugin to verify your Jira instance's
            SSL certificate?""", default=False)
    OAuthConsumerName = something("""What is the consumer name as per the Jira linked applications?""")
    OAuthConsumerKey = something("""What is the consumer secret key as per the Jira linked applications?""")
    OAuthVerifier = something("""What is the consumer verifier string for Jira OAuth?""", default='none')
    OAuthConsumerSSLKey = something("""What is the filename holding the SSL key bound with the Jira trusted cert?""")
    OAuthTokenDatabase = something("""What is the filename holding the yaml structure with OAuth tokens?""")

    Jira.server.setValue(server)
    Jira.user.setValue(user)
    Jira.password.setValue(password)
    Jira.template.setValue(template)
    Jira.lookup.setValue(lookup)
    Jira.snarfRegex.setValue(snarfRegex)
    Jira.verifySSL.setValue(verifySSL)
    Jira.OAuthConsumerName.setValue(OauthConsumerName)
    Jira.OAuthConsumerKey.setValue(OauthConsumerKey)
    Jira.OAuthVerifier.setValue(OauthVerifier)
    Jira.OAuthTokenDatabase.setValue(OauthTokenDatabase)
Esempio n. 2
0
def configure(advanced):
    from supybot.questions import expect, anything, something, yn
    UbuntuMan = conf.registerPlugin('UbuntuMan', True)

    if advanced == False:
        return

    baseurl = something("""What value should be used for base URL?""",
                        default="http://manpages.ubuntu.com/manpages")

    release = expect("""What value should be used as the default Ubuntu release?""",
                     possibilities=['dapper', 'hardy', 'intrepid', 'jaunty',
                         'karmic', 'lucid'],
                     default='karmic')

    sections = something("""What manual page sections should be enabled?""",
                         default='1 5 8')

    language = expect("""Which language should be used by default?""",
                      possibilities=['en', 'es', 'de', 'fi'],
                      default='en')

    UbuntuMan.baseurl.setValue(baseurl)
    UbuntuMan.release.setValue(release)
    UbuntuMan.sections.setValue(sections)
    UbuntuMan.language.setValue(language)
Esempio n. 3
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    botPort = conf.registerPlugin(PluginName, True)
    
    if yn("""The Beatport plugin rocks.  Would you like these commands to
             be enabled for everyone?""", default = False):
        botPort.userLevelRequires.setValue("")
    else:
        cap = something("""What capability would you like to require for
                           this command to be used?""", default = "Admin")
        botPort.userLevelRequires.setValue(cap)
    
    perPage = something("""How many results would you like returned per search?
                           """, default = 5)
    botPort.numResults.setValue(perPage)
    
    sortBy = expect("""In what order would you like results displayed?
                       See http://api.beatport.com/catalog-search.html for
                       options.""",
                       ["releaseDate", "publishDate", "releaseId", "trackName",
                        "trackId", "labelName", "genreName"],
                       default = "releaseDate")
    botPort.sortBy.setValue(sortBy)
Esempio n. 4
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    dtBot = conf.registerPlugin(PluginName, True)
    
    if yn("""The Digital-Tunes plugin rocks.  Would you like these commands to
             be enabled for everyone?""", default = False):
        dtBot.userLevelRequires.setValue("")
    else:
        cap = something("""What capability would you like to require for
                           this command to be used?""", default = "Admin")
        dtBot.userLevelRequires.setValue(cap)
    
    # 905872135d3b762556484e3256bdf17aa2ddcba0
    apiKey = something("""Digital-Tunes requires an API key to access their API.
                          If you don't have one, sign up at:
                          http://www.digital-tunes.net/affiliates/new""", default = False)
    dtBot.apiKey.setValue(apiKey)

    perPage = something("""How many results would you like returned per search?
                           """, default = 5)
    dtBot.numResults.setValue(perPage)
Esempio n. 5
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import output, expect, anything, something, yn

    output("To use the Acronym Finder, you must have obtained a license key.")
    if yn("Do you have a license key?"):
        key = something("What is it?")
        while len(key) != 36:
            output("That is not a valid Acronym Finder license key.")
            if yn("Are you sure you have a valid Acronym Finder license key?"):
                key = something("What is it?")
            else:
                key = ""
                break
        if key:
            conf.registerPlugin("AcronymFinder", True)
            conf.supybot.plugins.AcronymFinder.licenseKey.setValue(key)
    else:
        output(
            """You'll need to get a key before you can use this plugin.
                  You can apply for a key at http://www.acronymfinder.com/dontknowyet/"""
        )
Esempio n. 6
0
def configure(advanced):
    from supybot.questions import something
    conf.registerPlugin('Services', True)
    nick = something(_('What is your registered nick?'))
    password = something(_('What is your password for that nick?'))
    chanserv = something(_('What is your ChanServ named?'), default='ChanServ')
    nickserv = something(_('What is your NickServ named?'), default='NickServ')
    conf.supybot.plugins.Services.nicks.setValue([nick])
    conf.supybot.plugins.Services.NickServ.setValue(nickserv)
    registerNick(nick, password)
    conf.supybot.plugins.Services.ChanServ.setValue(chanserv)
Esempio n. 7
0
def configure(advanced):
    from supybot.questions import expect, anything, something, yn, getpass
    conf.registerPlugin('Services', True)
    nick = something(_('What is your registered nick?'))
    password = something(_('What is your password for that nick?'))
    chanserv = something(_('What is your ChanServ named?'), default='ChanServ')
    nickserv = something(_('What is your NickServ named?'), default='NickServ')
    conf.supybot.plugins.Services.nicks.setValue([nick])
    conf.supybot.plugins.Services.NickServ.setValue(nickserv)
    registerNick(nick, password)
    conf.supybot.plugins.Services.ChanServ.setValue(chanserv)
Esempio n. 8
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('Lastfm', True)

    apikey = something('What is your Last.fm apikey?')
    secret = something('What is your Last.fm secret?')
    conf.supybot.plugins.Lastfm.apikey.setValue(apikey)
    conf.supybot.plugins.Lastfm.secret.setValue(secret)
Esempio n. 9
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    QuoteGrabs = conf.registerPlugin('QuoteGrabs', True)

    QuoteGrabs.consumer_key.setValue(something('twitter consumer key:'))
    QuoteGrabs.consumer_secret.setValue(something('twitter consumer secret:'))
    QuoteGrabs.access_key.setValue(something('twitter access key:'))
    QuoteGrabs.access_secret.setValue(something('twitter access secret:'))
Esempio n. 10
0
def configure(advanced):
    from supybot.questions import expect, something, yn, output

    def anything(prompt, default=None):
        """Because supybot is pure fail"""
        from supybot.questions import expect
        return expect(prompt, [], default=default)

    Bugtracker = conf.registerPlugin('Bugtracker', True)

    def getRepeatdelay():
        output("How many seconds should the bot wait before repeating bug information?")
        repeatdelay = something("Enter a number greater or equal to 0.", default=Bugtracker.repeatdelay._default)

        try:
            repeatdelay = int(repeatdelay)
            if repeatdelay < 0:
                raise TypeError
        except TypeError:
            output("Invalid value '%s', it must be an integer greater or equal to 0." % repeatdelay)
            return getRepeatdelay()
        else:
            return repeatdelay

    output("Each of the next 3 questions can be set per-channel with the '@config channel' command.")
    bugSnarfer = yn("Enable detecting bugs numbers and URL in all channels?", default=Bugtracker.bugSnarfer._default)
    cveSnarfer = yn("Enable detecting CVE numbers and URL in all channels?", default=Bugtracker.cveSnarfer._default)
    oopsSnarfer = yn("Enable detecting Launchpad OOPS IDs in all channels?", default=Bugtracker.oopsSnarfer._default)
    if advanced:
        replyNoBugtracker = something("What should the bot reply with when a user requests information from an unknown bug tracker?", default=Bugtracker.replyNoBugtracker._default)
        snarfTarget = something("What should be the default bug tracker used when none is specified?", default=Bugtracker.snarfTarget._default)
        replyWhenNotFound = yn("Should the bot report when a bug is not found?", default=Bugtracker.replyWhenNotFound._default)
        repeatdelay = getRepeatdelay()
    else:
        replyNoBugtracker = Bugtracker.replyNoBugtracker._default
        snarfTarget = Bugtracker.snarfTarget._default
        replyWhenNotFound = Bugtracker.replyWhenNotFound._default
        repeatdelay = Bugtracker.repeatdelay._default

    showassignee = yn("Show the assignee of a bug in the reply?", default=Bugtracker.showassignee._default)
    extended = yn("Show tracker-specific extended infomation?", default=Bugtracker.extended._default)

    Bugtracker.bugSnarfer.setValue(bugSnarfer)
    Bugtracker.cveSnarfer.setValue(cveSnarfer)
    Bugtracker.oopsSnarfer.setValue(oopsSnarfer)
    Bugtracker.replyNoBugtracker.setValue(replyNoBugtracker)
    Bugtracker.snarfTarget.setValue(snarfTarget)
    Bugtracker.replyWhenNotFound.setValue(replyWhenNotFound)
    Bugtracker.repeatdelay.setValue(repeatdelay)
    Bugtracker.showassignee.setValue(showassignee)
    Bugtracker.extended.setValue(extended)
Esempio n. 11
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    assembla = conf.registerPlugin('Assembla', True)
    if yn("Would you like to configure Assembla now?", default=False):
    	key = something("Please enter an API key", '')
    	secret = something("Please enter an API Secret", '')
    	assembla.apiKey.setValue(key)
    	assembla.apiSecret.setValue(Secret)
    if yn('Do you want the Assembla snarfer enabled by default?'):
        conf.supybot.plugins.Google.ticketSnarfer.setValue(True)
Esempio n. 12
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified themself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    Mittag = conf.registerPlugin('Mittag', True)

    Mittag.apiKey.setValue(something("Please enter your API Key:"))
    Mittag.latitude.setValue(something("Latitude:"))
    Mittag.longitude.setValue(something("Longitude:"))
    Mittag.distance.setValue(something("Distance:", default=2.5))
    Mittag.prefixNick.setValue(yn("Prefix nickname in replies?",
                                  default=False))
Esempio n. 13
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    Racebot = conf.registerPlugin('Racebot', True)

    username = something("""What iRacing user name (email address) should be used to query for users?
                            This account must watch or friend any user to be known to this bot.""")
    password = something("""What is the password for that iRacing account?""")

    Racebot.iRacingUsername.setValue(username)
    Racebot.iRacingPassword.setValue(password)
Esempio n. 14
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    Twitter = conf.registerPlugin('Twitter', True)
    consumer_key = something("twitter.com consumer key:");
    Twitter.consumer_key.setValue(consumer_key)
    consumer_secret = something("twitter.com consumer secret:");
    Twitter.consumer_secret.setValue(consumer_secret)

    access_key = something("twitter.com access token:");
    Twitter.access_key.setValue(access_key)
    access_secret = something("twitter.com access token secret:");
    Twitter.access_secret.setValue(access_secret)
Esempio n. 15
0
def configure(advanced):
    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('Intranet', True)
    output('The default whois server is whois.verisign-grs.com.')
    if yn('Would you like to specify a different whois server?'):
        server = something('What server?')
        conf.plugins.Intranet.whoisServer.setValue(server)
Esempio n. 16
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    Twitter = conf.registerPlugin('Twitter', True)
    consumer_key = something("twitter.com consumer key:")
    Twitter.consumer_key.setValue(consumer_key)
    consumer_secret = something("twitter.com consumer secret:")
    Twitter.consumer_secret.setValue(consumer_secret)

    access_key = something("twitter.com access token:")
    Twitter.access_key.setValue(access_key)
    access_secret = something("twitter.com access token secret:")
    Twitter.access_secret.setValue(access_secret)
Esempio n. 17
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    Racebot = conf.registerPlugin('Racebot', True)

    username = something(
        """What iRacing user name (email address) should be used to query for users?
                            This account must watch or friend any user to be known to this bot."""
    )
    password = something("""What is the password for that iRacing account?""")

    Racebot.iRacingUsername.setValue(username)
    Racebot.iRacingPassword.setValue(password)
Esempio n. 18
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('Jira', True)
    user = something('What is your api username?')
    password = something('What is your password for that username?')
    api_url = something('What is your api url (eg. https://jira.com/api/v2)?')
    url = something('What is your domain (eg. https://jira.com)?')

    conf.supybot.plugins.Jira.apiUser.setValue(user)
    conf.supybot.plugins.Jira.apiPass.setValue(password)
    conf.supybot.plugins.Jira.apiUrl.setValue(api_url)
    conf.supybot.plugins.Jira.domain.setValue(url)
Esempio n. 19
0
def configure(advanced):
    from supybot.questions import output, expect, anything, something, yn
    conf.registerPlugin('Dict', True)
    output('The default dictd server is dict.org.')
    if yn('Would you like to specify a different dictd server?'):
        server = something('What server?')
        conf.supybot.plugins.Dict.server.set(server)
Esempio n. 20
0
def configure(advanced):
    from supybot.questions import something, anything, yn, output
    output("""Here you can set which channels and who the bot has to send log
              messages to. Note that by default in order to log to a channel
              the channel has to have mode +s set. Logging to a user requires
              the user to have the Owner capability.""")
    targets = ''
    while not targets:
        try:
            targets = anything('Which channels or users would you like to '
                               'send log messages to?')
            conf.supybot.plugins.LogToIrc.targets.set(targets)
        except registry.InvalidRegistryValue as e:
            output(str(e))
            targets = ''
    colorized = yn('Would you like these messages to be colored?')
    conf.supybot.plugins.LogToIrc.color.setValue(colorized)
    if advanced:
        level = ''
        while not level:
            try:
                level = something('What would you like the minimum priority '
                                  'level to be which will be logged to IRC?')
                conf.supybot.plugins.LogToIrc.level.set(level)
            except registry.InvalidRegistryValue as e:
                output(str(e))
                level = ''
Esempio n. 21
0
def configure(advanced):
    from supybot.questions import output, expect, anything, something, yn
    conf.registerPlugin('Dict', True)
    output(_('The default dictd server is dict.org.'))
    if yn(_('Would you like to specify a different dictd server?')):
        server = something('What server?')
        conf.supybot.plugins.Dict.server.set(server)
Esempio n. 22
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('Jira', True)
    user = something('What is your api username?')
    password = something('What is your password for that username?')
    api_url = something('What is your api url (eg. https://jira.com/api/v2)?')
    url = something('What is your domain (eg. https://jira.com)?')

    conf.supybot.plugins.Jira.apiUser.setValue(user)
    conf.supybot.plugins.Jira.apiPass.setValue(password)
    conf.supybot.plugins.Jira.apiUrl.setValue(api_url)
    conf.supybot.plugins.Jira.domain.setValue(url)
Esempio n. 23
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    output("""Where is your miniqdb instance located? Please don't put a slash
    at the end of the URL -- for example, http://example.com/miniqdb .""")
    root = something('root?')
    conf.registerPlugin('Miniqdb', True)
    conf.supybot.plugins.Miniqdb.miniqdbRoot.setValue(root)
    output("""This plugin has support to utilize HTTP Basic authentication.
    HTTP Digest is not supported just yet.""")
    if yn("Do you use HTTP Basic authentication on your miniqdb?"):
        conf.supybot.plugins.Miniqdb.auth.username.setValue(something('username?'))
        conf.supybot.plugins.Miniqdb.auth.username.setValue(something('password?'))
    output("""Thanks for using miniqdb! http://miniqdb.googlecode.com/""")
Esempio n. 24
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified themself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('TwitterLite', True)

    consumer_key = something("consumer_key")
    consumer_secret = something("consumer_secret")
    access_token_key = something("access_token_key")
    access_token_secret = something("access_token_secret")

    conf.supybot.plugins.TwitterLite.consumer_key.set(consumer_key)
    conf.supybot.plugins.TwitterLite.consumer_secret.set(consumer_secret)
    conf.supybot.plugins.TwitterLite.access_token_key.set(access_token_key)
    conf.supybot.plugins.TwitterLite.access_token_secret.set(
        access_token_secret)
Esempio n. 25
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    PPWolframAlpha = conf.registerPlugin('WolframAlpha', True)
    key = something("What is your API key?")
    PPWolframAlpha.apikey.setValue(key)
Esempio n. 26
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('MicrosoftTranslator', True)
    azurekey = something(""" Please enter your Azure Marketplace key: """)
    conf.supybot.plugins.MicrosoftTranslator.azureKey.setValue(azurekey)
Esempio n. 27
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    GroupStatus = conf.registerPlugin('GroupStatus')

    cs = something("""What is the database connect string?""")
    GroupStatus.databaseConnectString.setValue(cs)
Esempio n. 28
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import output, expect, anything, something, yn
    Lookup = conf.registerPlugin('Lookup', True)
    lookups = Lookup.lookups
    output("""This module allows you to define commands that do a simple key
              lookup and return some simple value.  It has a command "add"
              that takes a command name and a file from the data dir and adds a
              command with that name that responds with the mapping from that
              file. The file itself should be composed of lines
              of the form key:value.""")
    while yn('Would you like to add a file?'):
        filename = something('What\'s the filename?')
        try:
            fd = file(filename)
        except EnvironmentError, e:
            output('I couldn\'t open that file: %s' % e)
            continue
        counter = 1
        try:
            try:
                for line in fd:
                    line = line.rstrip('\r\n')
                    if not line or line.startswith('#'):
                        continue
                    (key, value) = line.split(':', 1)
                    counter += 1
            except ValueError:
                output('That\'s not a valid file; '
                       'line #%s is malformed.' % counter)
                continue
        finally:
            fd.close()
        command = something('What would you like the command to be?')
        conf.registerGlobalValue(lookups,command, registry.String(filename,''))
        nokeyVal = yn('Would you like the key to be shown for random '
                      'responses?')
        conf.registerGlobalValue(lookups.get(command), 'nokey',
                                    registry.Boolean(nokeyVal, ''))
Esempio n. 29
0
    def getRepeatdelay():
        output("How many seconds should the bot wait before repeating bug information?")
        repeatdelay = something("Enter a number greater or equal to 0.", default=Bugtracker.repeatdelay._default)

        try:
            repeatdelay = int(repeatdelay)
            if repeatdelay < 0:
                raise TypeError
        except TypeError:
            output("Invalid value '%s', it must be an integer greater or equal to 0." % repeatdelay)
            return getRepeatdelay()
        else:
            return repeatdelay
Esempio n. 30
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import output, expect, anything, something, yn
    output('To use the Acronym Finder, you must have obtained a license key.')
    if yn('Do you have a license key?'):
        key = something('What is it?')
        while len(key) != 36:
            output('That is not a valid Acronym Finder license key.')
            if yn('Are you sure you have a valid Acronym Finder license key?'):
                key = something('What is it?')
            else:
                key = ''
                break
        if key:
            conf.registerPlugin('AcronymFinder', True)
            conf.supybot.plugins.AcronymFinder.licenseKey.setValue(key)
    else:
        output("""You'll need to get a key before you can use this plugin.
                  You can apply for a key at http://www.acronymfinder.com/dontknowyet/""")
Esempio n. 31
0
    def getDelay():
        output("What should be the minimum number of seconds between mess output?")
        delay = something("Enter an integer greater or equal to 0", default=Mess.delay._default)

        try:
            delay = int(delay)
            if delay < 0:
                raise TypeError
        except TypeError:
            output("%r is not a valid value, it must be an interger greater or equal to 0" % delay)
            return getDelay()
        else:
            return delay
Esempio n. 32
0
    def getReviewTime():
        output("How many days should the bot wait before requesting a ban/quiet review?")
        review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.request.review._default))

        try:
            review = float(review)
            if review < 0:
                raise TypeError
        except TypeError:
            output("%r is an invalid value, it must be an integer or float greater or equal to 0" % review)
            return getReviewTime()
        else:
            return review
Esempio n. 33
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    from supybot.questions import expect, anything, something, yn
    Jira = conf.registerPlugin('Jira', True)
    server = something("""What is the URL for the Jira instance?""")
    lookup = yn(
        """Do you want to lookup Jira issues once they appear on a channel?""",
        default=True)
    snarfRegex = something("""What is the prefix for your Jira issue keys?""",
                           default="AR")
    snarfRegex = ''.join((snarfRegex, '-[0-9]+'))
    snarfChannel = something(
        """What channel you'd like to snarf for issues?""", default="#armbian")
    channel = something("""Where to send anouncements for new issues to?""")

    Jira.server.setValue(server)
    Jira.lookup.setValue(lookup)
    Jira.snarfRegex.setValue(snarfRegex)
    Jira.channel.setValue(channel)
    Jira.snarfChannel.setValue(snarfChannel)
Esempio n. 34
0
    def getReviewTime():
        output(
            "How many days should the bot wait before requesting a ban/quiet review?"
        )
        review = something(
            "Can be an integer or decimal value. Zero disables reviews.",
            default=str(Bantracker.request.review._default))

        try:
            review = float(review)
            if review < 0:
                raise TypeError
        except TypeError:
            output(
                "%r is an invalid value, it must be an integer or float greater or equal to 0"
                % review)
            return getReviewTime()
        else:
            return review
Esempio n. 35
0
def getDirectoryName(default, basedir=os.curdir, prompt=True):
    done = False
    while not done:
        if prompt:
            dir = something('What directory do you want to use?',
                           default=os.path.join(basedir, default))
        else:
            dir = os.path.join(basedir, default)
        orig_dir = dir
        dir = os.path.expanduser(dir)
        dir = _windowsVarRe.sub(r'$\1', dir)
        dir = os.path.expandvars(dir)
        dir = os.path.abspath(dir)
        try:
            os.makedirs(dir)
            done = True
        except OSError, e:
            if e.args[0] != 17: # File exists.
                output("""Sorry, I couldn't make that directory for some
                reason.  The Operating System told me %s.  You're going to
                have to pick someplace else.""" % e)
                prompt = True
            else:
                done = True
Esempio n. 36
0
def getDirectoryName(default, basedir=os.curdir, prompt=True):
    done = False
    while not done:
        if prompt:
            dir = something('What directory do you want to use?',
                            default=os.path.join(basedir, default))
        else:
            dir = os.path.join(basedir, default)
        orig_dir = dir
        dir = os.path.expanduser(dir)
        dir = _windowsVarRe.sub(r'$\1', dir)
        dir = os.path.expandvars(dir)
        dir = os.path.abspath(dir)
        try:
            os.makedirs(dir)
            done = True
        except OSError, e:
            if e.args[0] != 17:  # File exists.
                output("""Sorry, I couldn't make that directory for some
                reason.  The Operating System told me %s.  You're going to
                have to pick someplace else.""" % e)
                prompt = True
            else:
                done = True
Esempio n. 37
0
def main():
    import supybot.log as log
    import supybot.conf as conf
    log._stdoutHandler.setLevel(100) # *Nothing* gets through this!
    parser = optparse.OptionParser(usage='Usage: %prog [options]',
                                   version='Supybot %s' % conf.version)
    parser.add_option('', '--allow-root', action='store_true',
                      dest='allowRoot',
                      help='Determines whether the wizard will be allowed to '
                           'run as root.  You don\'t want this.  Don\'t do it.'
                           '  Even if you think you want it, you don\'t.  '
                           'You\'re probably dumb if you do this.')
    parser.add_option('', '--no-network', action='store_false',
                      dest='network',
                      help='Determines whether the wizard will be allowed to '
                           'run without a network connection.')
    (options, args) = parser.parse_args()
    if os.name == 'posix':
        if (os.getuid() == 0 or os.geteuid() == 0) and not options.allowRoot:
            error('Please, don\'t run this as root.')

    filename = ''
    if args:
        parser.error('This program takes no non-option arguments.')
    output("""This is a wizard to help you start running supybot.  What it
    will do is create the necessary config files based on the options you
    select here.  So hold on tight and be ready to be interrogated :)""")


    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
    questions that you actually have to answer.""")
    if yn('Would you like to try this bolding?', default=True):
        questions.useBold = True
        if not yn('Do you see this in bold?'):
            output("""Sorry, it looks like your terminal isn't ANSI compliant.
            Try again some other day, on some other terminal :)""")
            questions.useBold = False
        else:
            output("""Great!""")

    ###
    # Preliminary questions.
    ###
    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
    bot is going to be like.""")

    # Advanced?
    output("""We want to know if you consider yourself an advanced Supybot
    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
    time.""")
    advanced = yn('Are you an advanced Supybot user?', default=False)

    ### Directories.
    # We set these variables in cache because otherwise conf and log will
    # create directories for the default values, which might not be what the
    # user wants.
    if advanced:
        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
        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 give answers to these questions and we'll create the
        directories we need right here in this directory.""")

        # conf.supybot.directories.log
        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 a directory named "logs" right here.""")
        (logDir, basedir) = getDirectoryName('logs')
        conf.supybot.directories.log.setValue(logDir)

        # conf.supybot.directories.data
        output("""Your bot will need to put various data somewhere.  Things
        like 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 a directory named "data" right here.""")
        (dataDir, basedir) = getDirectoryName('data', basedir=basedir)
        conf.supybot.directories.data.setValue(dataDir)

        # conf.supybot.directories.conf
        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.  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. """)
        (confDir, basedir) = getDirectoryName('conf', basedir=basedir)
        conf.supybot.directories.conf.setValue(confDir)

        # conf.supybot.directories.backup
        output("""Your bot must know where to place backups of its conf and
        data files.  Where should that place be?  If you don't care, just press
        enter and we'll make a directory right here named "backup" where it'll
        store his stuff.""")
        (backupDir, basedir) = getDirectoryName('backup', basedir=basedir)
        conf.supybot.directories.backup.setValue(backupDir)

        # pluginDirs
        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 your own personal plugins that you write for will probably be
        somewhere else.""")
        pluginDirs = conf.supybot.directories.plugins()
        output("""Currently, the bot knows about the following directories:""")
        output(format('%L', pluginDirs + [plugin._pluginsDir]))
        while yn('Would you like to add another plugin directory?  '
                 'Adding a local plugin directory is good style.',
                 default=True):
            (pluginDir, _) = getDirectoryName('plugins', basedir=basedir)
            if pluginDir not in pluginDirs:
                pluginDirs.append(pluginDir)
        conf.supybot.directories.plugins.setValue(pluginDirs)
    else:
        output("""Your bot needs to create some directories in order to store
        the various log, config, and data files.""")
        basedir = something("""Where would you like to create these
                            directories?""", default=os.curdir)
        # conf.supybot.directories.log
        (logDir, basedir) = getDirectoryName('logs', prompt=False)
        conf.supybot.directories.log.setValue(logDir)
        # conf.supybot.directories.data
        (dataDir, basedir) = getDirectoryName('data',
                                              basedir=basedir, prompt=False)
        conf.supybot.directories.data.setValue(dataDir)
        # conf.supybot.directories.conf
        (confDir, basedir) = getDirectoryName('conf',
                                              basedir=basedir, prompt=False)
        conf.supybot.directories.conf.setValue(confDir)
        # conf.supybot.directories.backup
        (backupDir, basedir) = getDirectoryName('backup',
                                                basedir=basedir, prompt=False)
        conf.supybot.directories.backup.setValue(backupDir)
        # pluginDirs
        pluginDirs = conf.supybot.directories.plugins()
        (pluginDir, _) = getDirectoryName('plugins',
                                          basedir=basedir, prompt=False)
        if pluginDir not in pluginDirs:
            pluginDirs.append(pluginDir)
        conf.supybot.directories.plugins.setValue(pluginDirs)

    output("Good!  We're done with the directory stuff.")

    ###
    # Bot stuff
    ###
    output("""Now we're going to ask you things that actually relate to the
    bot you'll be running.""")

    network = None
    while not network:
        output("""First, we need to know the name of the network you'd like to
        connect to.  Not the server host, mind you, but the name of the
        network.  If you plan to connect to irc.freenode.net, for instance, you
        should answer this question with 'freenode' (without the quotes).""")
        network = something('What IRC network will you be connecting to?')
        if '.' in network:
            output("""There shouldn't be a '.' in the network name.  Remember,
            this is the network name, not the actual server you plan to connect
            to.""")
            network = None
        elif not registry.isValidRegistryName(network):
            output("""That's not a valid name for one reason or another.  Please
            pick a simpler name, one more likely to be valid.""")
            network = None

    conf.supybot.networks.setValue([network])
    network = conf.registerNetwork(network)

    defaultServer = None
    server = None
    ip = None
    while not ip:
        serverString = something('What server would you like to connect to?',
                                 default=defaultServer)
        if options.network:
            try:
                output("""Looking up %s...""" % serverString)
                ip = socket.gethostbyname(serverString)
            except:
                output("""Sorry, I couldn't find that server.  Perhaps you
                misspelled it?  Also, be sure not to put the port in the
                server's name -- we'll ask you about that later.""")
        else:
            ip = 'no network available'

    output("""Found %s (%s).""" % (serverString, ip))
    output("""IRC Servers almost always accept connections on port
    6667.  They can, however, accept connections anywhere their admin
    feels like he wants to accept connections from.""")
    if yn('Does this server require connection on a non-standard port?',
          default=False):
        port = 0
        while not port:
            port = something('What port is that?')
            try:
                i = int(port)
                if not (0 < i < 65536):
                    raise ValueError
            except ValueError:
                output("""That's not a valid port.""")
                port = 0
    else:
        port = 6667
    server = ':'.join([serverString, str(port)])
    network.servers.setValue([server])

    # conf.supybot.nick
    # Force the user into specifying a nick if he didn't have one already
    while True:
        nick = something('What nick would you like your bot to use?',
                         default=None)
        try:
            conf.supybot.nick.set(nick)
            break
        except registry.InvalidRegistryValue:
            output("""That's not a valid nick.  Go ahead and pick another.""")

    # conf.supybot.user
    if advanced:
        output("""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
        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.""")
        user = ''
        user = something('What would you like your bot\'s full name to be?',
                         default=nick)
        conf.supybot.user.set(user)
    # conf.supybot.ident (if advanced)
    defaultIdent = 'supybot'
    if advanced:
        output("""IRC servers also allow you to set your ident, which they
        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 use
        'supybot'.  In fact, we prefer that you do this, because it provides
        free advertising for Supybot when users /whois your bot.  But, of
        course, it's your call.""")
        while True:
            ident = something('What would you like your bot\'s ident to be?',
                              default=defaultIdent)
            try:
                conf.supybot.ident.set(ident)
                break
            except registry.InvalidRegistryValue:
                output("""That was not a valid ident.  Go ahead and pick
                another.""")
    else:
        conf.supybot.ident.set(defaultIdent)

    if advanced:
        # conf.supybot.networks.<network>.ssl
        output("""Some servers allow you to use a secure connection via SSL.
        This requires having pyOpenSSL installed.  Currently, you also need
        Twisted installed as only the Twisted drivers supports SSL
        connections.""")
        if yn('Do you want to use an SSL connection?', default=False):
            network.ssl.setValue(True)

    # conf.supybot.networks.<network>.password
    output("""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
    reason it just won't work, it might be that you need to set a
    password.""")
    if yn('Do you want to set such a password?', default=False):
        network.password.set(getpass())

    # conf.supybot.networks.<network>.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.""")
    if yn('Do you want your bot to join some channels when he connects?',
          default=True):
        defaultChannels = ' '.join(network.channels())
        output("""Separate channels with spaces.  If the channel is locked
                  with a key, follow the channel name with the key separated
                  by a comma. For example:
                  #supybot-bots #mychannel,mykey #otherchannel""");
        while True:
            channels = something('What channels?', default=defaultChannels)
            try:
                network.channels.set(channels)
                break
            except registry.InvalidRegistryValue, e:
                output(""""%s" is an invalid IRC channel.  Be sure to prefix
                the channel with # (or +, or !, or &, but no one uses those
                channels, really).  Be sure the channel key (if you are
                supplying one) does not contain a comma.""" % e.channel)
Esempio n. 38
0
 def configure(self, plugin, advanced):
     '''Called by config.py during the initial configure step'''
     if yn(_('Enable for YouTube links? (needs API key)')):
         plugin.youtube_enabled.setValue(True)
         token = something(_('Enter Google Simple API key'))
         plugin.youtube_api_token.setValue(token)
Esempio n. 39
0
def configure(advanced):
    from supybot.questions import yn, something, output
    import sqlite
    import re
    import os
    from supybot.utils.str import format

    def anything(prompt, default=None):
        """Because supybot is pure fail"""
        from supybot.questions import expect
        return expect(prompt, [], default=default)

    Bantracker = conf.registerPlugin('Bantracker', True)

    def getReviewTime():
        output(
            "How many days should the bot wait before requesting a ban/quiet review?"
        )
        review = something(
            "Can be an integer or decimal value. Zero disables reviews.",
            default=str(Bantracker.request.review._default))

        try:
            review = float(review)
            if review < 0:
                raise TypeError
        except TypeError:
            output(
                "%r is an invalid value, it must be an integer or float greater or equal to 0"
                % review)
            return getReviewTime()
        else:
            return review

    enabled = yn("Enable Bantracker for all channels?")
    database = something(
        "Location of the Bantracker database",
        default=conf.supybot.directories.data.dirize('bans.db'))
    bansite = anything(
        "URL of the Bantracker web interface, without the 'bans.cgi'. (leave this blank if you don't want to run a web server)"
    )

    request = yn("Enable review and comment requests from bot?", default=False)
    if request and advanced:
        output("Which types would you like the bot to request comments for?")
        output(
            format("The available request types are %L",
                   Bantracker.request.type._default))
        types = anything("Separate types by spaces or commas:",
                         default=', '.join(Bantracker.request.type._default))
        type = set([])
        for name in re.split(r',?\s+', types):
            name = name.lower()
            if name in ('removal', 'ban', 'quiet'):
                type.add(name)

        output("Which nicks should be bot not requets comments from?")
        output("Is case insensitive and wildcards '*' and '?' are accepted.")
        ignores = anything("Separate types by spaces or commas:",
                           default=', '.join(
                               Bantracker.request.ignore._default))
        ignore = set([])
        for name in re.split(r',?\s+', ignores):
            name = name.lower()
            ignore.add(name)

        output(
            "You can set the comment and review requests for some nicks to be forwarded to specific nicks/channels"
        )
        output("Which nicks should these requests be forwarded for?")
        output("Is case insensitive and wildcards '*' and '?' are accepted.")
        forwards = anything("Separate types by spaces or commas:",
                            default=', '.join(
                                Bantracker.request.forward._default))
        forward = set([])
        for name in re.split(r',?\s+', forwards):
            name = name.lower()
            forward.add(name)

        output("Which nicks/channels should the requests be forwarded to?")
        output("Is case insensitive and wildcards '*' and '?' are accepted.")
        channels_i = anything("Separate types by spaces or commas:",
                              default=', '.join(
                                  Bantracker.request.forward._default))
        channels = set([])
        for name in re.split(r',?\s+', channels_i):
            name = name.lower()
            channels.add(name)

        review = getReviewTime()

    else:
        type = Bantracker.request.type._default
        ignore = Bantracker.request.ignore._default
        forward = Bantracker.request.forward._default
        channels = Bantracker.request.forward.channels._default
        review = Bantracker.request.review._default

    Bantracker.enabled.setValue(enabled)
    Bantracker.database.setValue(database)
    Bantracker.bansite.setValue(bansite)
    Bantracker.request.setValue(request)
    Bantracker.request.type.setValue(type)
    Bantracker.request.ignore.setValue(ignore)
    Bantracker.request.forward.setValue(forward)
    Bantracker.request.forward.channels.setValue(channels)
    Bantracker.request.review.setValue(review)

    # Create the initial database
    db_file = Bantracker.database()
    if not db_file:
        db_file = conf.supybot.directories.data.dirize('bans.db')
        output("supybot.plugins.Bantracker.database will be set to %r" %
               db_file)
        Bantracker.database.setValue(db_file)

    if os.path.exists(db_file):
        return

    output("Creating an initial database in %r" % db_file)
    con = sqlite.connect(db_file)
    cur = con.cursor()

    try:
        cur.execute("""CREATE TABLE 'bans' (
    id INTEGER PRIMARY KEY,
    channel VARCHAR(30) NOT NULL,
    mask VARCHAR(100) NOT NULL,
    operator VARCHAR(30) NOT NULL,
    time VARCHAR(300) NOT NULL,
    removal DATETIME,
    removal_op VARCHAR(30),
    log TEXT
)""")
        #"""

        cur.execute("""CREATE TABLE comments (
    ban_id INTEGER,
    who VARCHAR(100) NOT NULL,
    comment MEDIUMTEXT NOT NULL,
    time VARCHAR(300) NOT NULL
)""")
        #"""

        cur.execute("""CREATE TABLE sessions (
    session_id VARCHAR(50) PRIMARY KEY,
    user MEDIUMTEXT NOT NULL,
    time INT NOT NULL
)""")
        #"""

        cur.execute("""CREATE TABLE users (
    username VARCHAR(50) PRIMARY KEY,
    salt VARCHAR(8),
    password VARCHAR(50)
)""")


#"""

    except:
        con.rollback()
        raise
    else:
        con.commit()
    finally:
        cur.close()
        con.close()
Esempio n. 40
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    def makeSource(release):
        return """deb http://archive.ubuntu.com/ubuntu/ %s main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ %s main restricted universe multiverse
""" % (release, release)


#"""

    from supybot.questions import output, expect, something, yn
    import subprocess
    import os

    def anything(prompt, default=None):
        """Because supybot is pure fail"""
        from supybot.questions import expect
        return expect(prompt, [], default=default)

    PackageInfo = conf.registerPlugin('PackageInfo', True)

    enabled = yn("Enable this plugin in all channels?", default=True)

    if enabled and advanced:
        prefixchar = something(
            "Which prefix character should be bot respond to?",
            default=PackageInfo.prefixchar._default)
        defaultRelease = something(
            "What should be the default distrobution when not specified?",
            default=PackageInfo.defaultRelease._default)
        aptdir = something(
            "Which directory should be used for the apt cache when looking up packages?",
            default=PackageInfo.aptdir._default)

        # People tend to thing this should be /var/cache/apt
        while aptdir.startswith(
                '/var'
        ):  #NOTE: This is not a good hack. Maybe just blacklist /var/cache/apt (or use apt to report back the cache dir)
            output("NO! Do not use your systems apt directory")
            aptdir = something(
                "Which directory should be used for the apt cache when looking up packages?",
                default=PackageInfo.aptdir._default)

    else:
        prefixchar = PackageInfo.prefixchar._default
        defaultRelease = PackageInfo.defaultRelease._default
        aptdir = PackageInfo.aptdir._default

    PackageInfo.enabled.setValue(enabled)
    PackageInfo.aptdir.setValue(aptdir)
    PackageInfo.prefixchar.setValue(prefixchar)
    PackageInfo.defaultRelease.setValue(defaultRelease)

    default_dists = set(
        ['dapper', 'hardy', 'lucid', 'maveric', 'natty', 'oneiric'])
    pluginDir = os.path.abspath(os.path.dirname(__file__))
    update_apt = os.path.join(pluginDir, 'update_apt')
    update_apt_file = os.path.join(pluginDir, 'update_apt_file')

    default_dists.add(defaultRelease)

    ## Create the aptdir
    try:
        os.makedirs(aptdir)
    except OSError:  # The error number would be OS dependant (17 on Linux 2.6, ?? on others). So just pass on this
        pass

    for release in default_dists:
        filename = os.path.join(aptdir, "%s.list" % release)
        try:
            output("Creating %s" % filename)
            fd = open(filename, 'wb')
            fd.write("# Apt sources list for Ubuntu %s\n" % release)
            fd.write(makeSource(release))
            fd.write(makeSource(release + '-security'))
            fd.write(makeSource(release + '-updates'))
            fd.close()

            for sub in ('backports', 'proposed'):
                sub_release = "%s-%s" % (release, sub)
                filename = os.path.join(aptdir, "%s.list" % sub_release)
                output("Creating %s" % filename)
                fd = open(filename, 'wb')
                fd.write("# Apt sources list for Ubuntu %s\n" % release)
                fd.write(makeSource(sub_release))
                fd.close()
        except Exception as e:
            output("Error writing to %r: %r (%s)" %
                   (filename, str(e), type(e)))

    if yn("In order for the plugin to use these sources, you must run the 'update_apt' script, do you want to do this now?",
          default=True):
        os.environ[
            'DIR'] = aptdir  # the update_apt script checks if DIR is set and uses it if it is
        if subprocess.getstatus(update_apt) != 0:
            output(
                "There was an error running update_apt, please run '%s -v' to get more information"
                % update_apt)

    if subprocess.getstatusoutput('which apt-file') != 0:
        output(
            "You need to install apt-file in order to use the !find command of this plugin"
        )
    else:
        if yn("In order for the !find command to work, you must run the 'update_apt_file' script, do you want to do this now?",
              default=True):
            os.environ[
                'DIR'] = aptdir  # the update_apt_file script checks if DIR is set and uses it if it is
            if subprocess.getstatusoutput(update_apt_file) != 0:
                output(
                    "There was an error running update_apt_file, please run '%s -v' to get more information"
                    % update_apt_file)
Esempio n. 41
0
def configure(advanced):
    from supybot.questions import yn, something, output
    import sqlite
    import re
    import os
    from supybot.utils.str import format

    def anything(prompt, default=None):
        """Because supybot is pure fail"""
        from supybot.questions import expect
        return expect(prompt, [], default=default)

    Bantracker = conf.registerPlugin('Bantracker', True)

    def getReviewTime():
        output("How many days should the bot wait before requesting a ban/quiet review?")
        review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.request.review._default))

        try:
            review = float(review)
            if review < 0:
                raise TypeError
        except TypeError:
            output("%r is an invalid value, it must be an integer or float greater or equal to 0" % review)
            return getReviewTime()
        else:
            return review

    enabled = yn("Enable Bantracker for all channels?")
    database = something("Location of the Bantracker database", default=conf.supybot.directories.data.dirize('bans.db'))
    bansite = anything("URL of the Bantracker web interface, without the 'bans.cgi'. (leave this blank if you don't want to run a web server)")

    request = yn("Enable review and comment requests from bot?", default=False)
    if request and advanced:
        output("Which types would you like the bot to request comments for?")
        output(format("The available request types are %L", Bantracker.request.type._default))
        types = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.type._default))
        type = set([])
        for name in re.split(r',?\s+', types):
            name = name.lower()
            if name in ('removal', 'ban', 'quiet'):
                type.add(name)

        output("Which nicks should be bot not requets comments from?")
        output("Is case insensitive and wildcards '*' and '?' are accepted.")
        ignores = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.ignore._default))
        ignore = set([])
        for name in re.split(r',?\s+', ignores):
            name = name.lower()
            ignore.add(name)

        output("You can set the comment and review requests for some nicks to be forwarded to specific nicks/channels")
        output("Which nicks should these requests be forwarded for?")
        output("Is case insensitive and wildcards '*' and '?' are accepted.")
        forwards = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.forward._default))
        forward = set([])
        for name in re.split(r',?\s+', forwards):
            name = name.lower()
            forward.add(name)

        output("Which nicks/channels should the requests be forwarded to?")
        output("Is case insensitive and wildcards '*' and '?' are accepted.")
        channels_i = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.forward._default))
        channels = set([])
        for name in re.split(r',?\s+', channels_i):
            name = name.lower()
            channels.add(name)

        review = getReviewTime()

    else:
        type = Bantracker.request.type._default
        ignore = Bantracker.request.ignore._default
        forward = Bantracker.request.forward._default
        channels = Bantracker.request.forward.channels._default
        review = Bantracker.request.review._default

    Bantracker.enabled.setValue(enabled)
    Bantracker.database.setValue(database)
    Bantracker.bansite.setValue(bansite)
    Bantracker.request.setValue(request)
    Bantracker.request.type.setValue(type)
    Bantracker.request.ignore.setValue(ignore)
    Bantracker.request.forward.setValue(forward)
    Bantracker.request.forward.channels.setValue(channels)
    Bantracker.request.review.setValue(review)

    # Create the initial database
    db_file = Bantracker.database()
    if not db_file:
        db_file = conf.supybot.directories.data.dirize('bans.db')
        output("supybot.plugins.Bantracker.database will be set to %r" % db_file)
        Bantracker.database.setValue(db_file)

    if os.path.exists(db_file):
        return

    output("Creating an initial database in %r" % db_file)
    con = sqlite.connect(db_file)
    cur = con.cursor()

    try:
        cur.execute("""CREATE TABLE 'bans' (
    id INTEGER PRIMARY KEY,
    channel VARCHAR(30) NOT NULL,
    mask VARCHAR(100) NOT NULL,
    operator VARCHAR(30) NOT NULL,
    time VARCHAR(300) NOT NULL,
    removal DATETIME,
    removal_op VARCHAR(30),
    log TEXT
)""")
#"""

        cur.execute("""CREATE TABLE comments (
    ban_id INTEGER,
    who VARCHAR(100) NOT NULL,
    comment MEDIUMTEXT NOT NULL,
    time VARCHAR(300) NOT NULL
)""")
#"""

        cur.execute("""CREATE TABLE sessions (
    session_id VARCHAR(50) PRIMARY KEY,
    user MEDIUMTEXT NOT NULL,
    time INT NOT NULL
)""")
#"""

        cur.execute("""CREATE TABLE users (
    username VARCHAR(50) PRIMARY KEY,
    salt VARCHAR(8),
    password VARCHAR(50)
)""")
#"""

    except:
        con.rollback()
        raise
    else:
        con.commit()
    finally:
        cur.close()
        con.close()
Esempio n. 42
0
def configure(advanced):
    # This will be called by supybot to configure this module.  advanced is
    # a bool that specifies whether the user identified himself as an advanced
    # user or not.  You should effect your configuration by manipulating the
    # registry as appropriate.
    def makeSource(release):
        return """deb http://archive.ubuntu.com/ubuntu/ %s main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ %s main restricted universe multiverse
""" % (release, release)
#"""

    from supybot.questions import output, expect, something, yn
    import subprocess
    import os

    def anything(prompt, default=None):
        """Because supybot is pure fail"""
        from supybot.questions import expect
        return expect(prompt, [], default=default)

    PackageInfo = conf.registerPlugin('PackageInfo', True)

    enabled = yn("Enable this plugin in all channels?", default=True)

    if enabled and advanced:
        prefixchar = something("Which prefix character should be bot respond to?", default=PackageInfo.prefixchar._default)
        defaultRelease = something("What should be the default distrobution when not specified?", default=PackageInfo.defaultRelease._default)
        aptdir = something("Which directory should be used for the apt cache when looking up packages?", default=PackageInfo.aptdir._default)

        # People tend to thing this should be /var/cache/apt
        while aptdir.startswith('/var'): #NOTE: This is not a good hack. Maybe just blacklist /var/cache/apt (or use apt to report back the cache dir)
            output("NO! Do not use your systems apt directory")
            aptdir = something("Which directory should be used for the apt cache when looking up packages?", default=PackageInfo.aptdir._default)

    else:
        prefixchar = PackageInfo.prefixchar._default
        defaultRelease = PackageInfo.defaultRelease._default
        aptdir = PackageInfo.aptdir._default


    PackageInfo.enabled.setValue(enabled)
    PackageInfo.aptdir.setValue(aptdir)
    PackageInfo.prefixchar.setValue(prefixchar)
    PackageInfo.defaultRelease.setValue(defaultRelease)

    default_dists = set(['dapper', 'hardy', 'lucid', 'maveric', 'natty', 'oneiric'])
    pluginDir = os.path.abspath(os.path.dirname(__file__))
    update_apt = os.path.join(pluginDir, 'update_apt')
    update_apt_file = os.path.join(pluginDir, 'update_apt_file')

    default_dists.add(defaultRelease)

    ## Create the aptdir
    try:
        os.makedirs(aptdir)
    except OSError: # The error number would be OS dependant (17 on Linux 2.6, ?? on others). So just pass on this
        pass

    for release in default_dists:
        filename = os.path.join(aptdir, "%s.list" % release)
        try:
            output("Creating %s" % filename)
            fd = open(filename, 'wb')
            fd.write("# Apt sources list for Ubuntu %s\n" % release)
            fd.write(makeSource(release))
            fd.write(makeSource(release + '-security'))
            fd.write(makeSource(release + '-updates'))
            fd.close()

            for sub in ('backports', 'proposed'):
                sub_release = "%s-%s" % (release, sub)
                filename = os.path.join(aptdir, "%s.list" % sub_release)
                output("Creating %s" % filename)
                fd = open(filename, 'wb')
                fd.write("# Apt sources list for Ubuntu %s\n" % release)
                fd.write(makeSource(sub_release))
                fd.close()
        except Exception as e:
            output("Error writing to %r: %r (%s)" % (filename, str(e), type(e)))

    if yn("In order for the plugin to use these sources, you must run the 'update_apt' script, do you want to do this now?", default=True):
        os.environ['DIR'] = aptdir # the update_apt script checks if DIR is set and uses it if it is
        if subprocess.getstatus(update_apt) != 0:
            output("There was an error running update_apt, please run '%s -v' to get more information" % update_apt)

    if subprocess.getstatusoutput('which apt-file') != 0:
        output("You need to install apt-file in order to use the !find command of this plugin")
    else:
        if yn("In order for the !find command to work, you must run the 'update_apt_file' script, do you want to do this now?", default=True):
            os.environ['DIR'] = aptdir # the update_apt_file script checks if DIR is set and uses it if it is
            if subprocess.getstatusoutput(update_apt_file) != 0:
                output("There was an error running update_apt_file, please run '%s -v' to get more information" % update_apt_file)
Esempio n. 43
0
                if yn('Would you like to load this plugin?', default=True):
                    configurePlugin(module, advanced)
                    clearLoadedPlugins(plugins, conf.supybot.plugins)
            if not yn('Would you like add another plugin?'):
                break
            name = expect('What plugin would you like to look at?', plugins)

    ###
    # Sundry
    ###
    output("""Although supybot offers a supybot-adduser script, with which
    you can add users to your bot's user database, it's *very* important that
    you have an owner user for you bot.""")
    if yn('Would you like to add an owner user for your bot?', default=True):
        import supybot.ircdb as ircdb
        name = something('What should the owner\'s username be?')
        try:
            id = ircdb.users.getUserId(name)
            u = ircdb.users.getUser(id)
            if u._checkCapability('owner'):
                output("""That user already exists, and has owner capabilities
                already.  Perhaps you added it before? """)
                if yn('Do you want to remove its owner capability?',
                      default=False):
                    u.removeCapability('owner')
                    ircdb.users.setUser(id, u)
            else:
                output("""That user already exists, but doesn't have owner
                capabilities.""")
                if yn('Do you want to add to it owner capabilities?',
                      default=False):
Esempio n. 44
0
def configure(advanced):

    from supybot.questions import expect, anything, something, yn
    conf.registerPlugin('Phabricator', True)

    Phabricator.phabricatorURL.setValue(
        something("Specify the URL of the Phabricator location.",
                  default="code.wildfiregames.com"))

    Phabricator.phabricatorToken.setValue(
        something("Specify the token to access the Phabricator conduit API.",
                  default="code.wildfiregames.com"))

    Phabricator.acceptInvalidSSLCert.setValue(
        something("Accept invalid SSL certificates?", default=False))

    Phabricator.httpTimeout.setValue(something("HTTP timeout", default=40))

    Phabricator.channels.setValue(
        anything(
            "On which irc channels the bot should post Phabricator updates. If empty, prints on each joined channel.",
            default="",
            acceptEmpty=True))

    Phabricator.storyLimit.setValue(
        something("Number of stories to pull at most per HTTP request",
                  default=5))

    Phabricator.historyForwards.setValue(
        yn("Traverse history chronologically forwards (or backwards)?",
           default=True))

    Phabricator.timestampAfter.setValue(
        anything("To ignore messages after this date, type a timestamp",
                 default=0))

    Phabricator.timestampBefore.setValue(
        anything("To ignore messages before this date, type a timestamp",
                 default=0))

    Phabricator.sleepTime.setValue(
        something(
            "Number of seconds between consecutive HTTP request for phabricator stories",
            default=30))

    Phabricator.newsPrefix.setValue(
        anything("Enter string to be preceeeded with Phabricator updates"),
        default="News from the project:")

    Phabricator.printDate.setValue(yn(
        "Whether to print a human readable timestamp in front of each update notification"
    ),
                                   default=False)

    Phabricator.chronokeyFile.setValue(
        something(
            "Filename to store the most recently processed chronological key",
            default="chronokey.txt"))

    Phabricator.ignoredUsers.setValue(
        anything("Updates of these usernames will remain hidden.",
                 default="Harbormaster Vulcan",
                 acceptEmpty=True))

    Phabricator.filteredUsers.setValue(
        anything("Only updates of these usernames will be shown.",
                 default="Harbormaster Vulcan",
                 acceptEmpty=True))

    Phabricator.notifyRetitle.setValue(
        yn("Notify if differentials are retitled?", default=True))

    Phabricator.notifyCommit.setValue(
        yn("Notify if a developer committed a patch?", default=True))

    Phabricator.obscureUsernames.setValue(
        yn("Prevent the bot from pinging irc users in updates by inserting invisible whitespace in the username?",
           default=True))

    Phabricator.verbose.setValue(
        yn("Display spammy, verbose debug output?", default=False))
Esempio n. 45
0
 def configure(self, plugin, advanced):
     if yn(_('Enable for Twitter links? (needs API key)')):
         plugin.twitter_enabled.setValue(True)
         token = something(_('Enter Twitter OAuth Bearer token'))
         plugin.twitter_api_token.setValue(token)
Esempio n. 46
0
def main():
    import supybot.log as log
    import supybot.conf as conf
    log._stdoutHandler.setLevel(100)  # *Nothing* gets through this!
    parser = optparse.OptionParser(usage='Usage: %prog [options]',
                                   version='Supybot %s' % conf.version)
    parser.add_option('',
                      '--allow-root',
                      action='store_true',
                      dest='allowRoot',
                      help='Determines whether the wizard will be allowed to '
                      'run as root.  You don\'t want this.  Don\'t do it.'
                      '  Even if you think you want it, you don\'t.  '
                      'You\'re probably dumb if you do this.')
    parser.add_option('',
                      '--no-network',
                      action='store_false',
                      dest='network',
                      help='Determines whether the wizard will be allowed to '
                      'run without a network connection.')
    (options, args) = parser.parse_args()
    if os.name == 'posix':
        if (os.getuid() == 0 or os.geteuid() == 0) and not options.allowRoot:
            error('Please, don\'t run this as root.')

    filename = ''
    if args:
        parser.error('This program takes no non-option arguments.')
    output("""This is a wizard to help you start running supybot.  What it
    will do is create the necessary config files based on the options you
    select here.  So hold on tight and be ready to be interrogated :)""")

    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
    questions that you actually have to answer.""")
    if yn('Would you like to try this bolding?', default=True):
        questions.useBold = True
        if not yn('Do you see this in bold?'):
            output("""Sorry, it looks like your terminal isn't ANSI compliant.
            Try again some other day, on some other terminal :)""")
            questions.useBold = False
        else:
            output("""Great!""")

    ###
    # Preliminary questions.
    ###
    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
    bot is going to be like.""")

    # Advanced?
    output("""We want to know if you consider yourself an advanced Supybot
    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
    time.""")
    advanced = yn('Are you an advanced Supybot user?', default=False)

    ### Directories.
    # We set these variables in cache because otherwise conf and log will
    # create directories for the default values, which might not be what the
    # user wants.
    if advanced:
        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
        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 give answers to these questions and we'll create the
        directories we need right here in this directory.""")

        # conf.supybot.directories.log
        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 a directory named "logs" right here.""")
        (logDir, basedir) = getDirectoryName('logs')
        conf.supybot.directories.log.setValue(logDir)

        # conf.supybot.directories.data
        output("""Your bot will need to put various data somewhere.  Things
        like 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 a directory named "data" right here.""")
        (dataDir, basedir) = getDirectoryName('data', basedir=basedir)
        conf.supybot.directories.data.setValue(dataDir)

        # conf.supybot.directories.conf
        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.  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. """)
        (confDir, basedir) = getDirectoryName('conf', basedir=basedir)
        conf.supybot.directories.conf.setValue(confDir)

        # conf.supybot.directories.backup
        output("""Your bot must know where to place backups of its conf and
        data files.  Where should that place be?  If you don't care, just press
        enter and we'll make a directory right here named "backup" where it'll
        store his stuff.""")
        (backupDir, basedir) = getDirectoryName('backup', basedir=basedir)
        conf.supybot.directories.backup.setValue(backupDir)

        # pluginDirs
        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 your own personal plugins that you write for will probably be
        somewhere else.""")
        pluginDirs = conf.supybot.directories.plugins()
        output("""Currently, the bot knows about the following directories:""")
        output(format('%L', pluginDirs + [plugin._pluginsDir]))
        while yn(
                'Would you like to add another plugin directory?  '
                'Adding a local plugin directory is good style.',
                default=True):
            (pluginDir, _) = getDirectoryName('plugins', basedir=basedir)
            if pluginDir not in pluginDirs:
                pluginDirs.append(pluginDir)
        conf.supybot.directories.plugins.setValue(pluginDirs)
    else:
        output("""Your bot needs to create some directories in order to store
        the various log, config, and data files.""")
        basedir = something("""Where would you like to create these
                            directories?""",
                            default=os.curdir)
        # conf.supybot.directories.log
        (logDir, basedir) = getDirectoryName('logs', prompt=False)
        conf.supybot.directories.log.setValue(logDir)
        # conf.supybot.directories.data
        (dataDir, basedir) = getDirectoryName('data',
                                              basedir=basedir,
                                              prompt=False)
        conf.supybot.directories.data.setValue(dataDir)
        # conf.supybot.directories.conf
        (confDir, basedir) = getDirectoryName('conf',
                                              basedir=basedir,
                                              prompt=False)
        conf.supybot.directories.conf.setValue(confDir)
        # conf.supybot.directories.backup
        (backupDir, basedir) = getDirectoryName('backup',
                                                basedir=basedir,
                                                prompt=False)
        conf.supybot.directories.backup.setValue(backupDir)
        # pluginDirs
        pluginDirs = conf.supybot.directories.plugins()
        (pluginDir, _) = getDirectoryName('plugins',
                                          basedir=basedir,
                                          prompt=False)
        if pluginDir not in pluginDirs:
            pluginDirs.append(pluginDir)
        conf.supybot.directories.plugins.setValue(pluginDirs)

    output("Good!  We're done with the directory stuff.")

    ###
    # Bot stuff
    ###
    output("""Now we're going to ask you things that actually relate to the
    bot you'll be running.""")

    network = None
    while not network:
        output("""First, we need to know the name of the network you'd like to
        connect to.  Not the server host, mind you, but the name of the
        network.  If you plan to connect to irc.freenode.net, for instance, you
        should answer this question with 'freenode' (without the quotes).""")
        network = something('What IRC network will you be connecting to?')
        if '.' in network:
            output("""There shouldn't be a '.' in the network name.  Remember,
            this is the network name, not the actual server you plan to connect
            to.""")
            network = None
        elif not registry.isValidRegistryName(network):
            output(
                """That's not a valid name for one reason or another.  Please
            pick a simpler name, one more likely to be valid.""")
            network = None

    conf.supybot.networks.setValue([network])
    network = conf.registerNetwork(network)

    defaultServer = None
    server = None
    ip = None
    while not ip:
        serverString = something('What server would you like to connect to?',
                                 default=defaultServer)
        if options.network:
            try:
                output("""Looking up %s...""" % serverString)
                ip = socket.gethostbyname(serverString)
            except:
                output("""Sorry, I couldn't find that server.  Perhaps you
                misspelled it?  Also, be sure not to put the port in the
                server's name -- we'll ask you about that later.""")
        else:
            ip = 'no network available'

    output("""Found %s (%s).""" % (serverString, ip))
    output("""IRC Servers almost always accept connections on port
    6667.  They can, however, accept connections anywhere their admin
    feels like he wants to accept connections from.""")
    if yn('Does this server require connection on a non-standard port?',
          default=False):
        port = 0
        while not port:
            port = something('What port is that?')
            try:
                i = int(port)
                if not (0 < i < 65536):
                    raise ValueError
            except ValueError:
                output("""That's not a valid port.""")
                port = 0
    else:
        port = 6667
    server = ':'.join([serverString, str(port)])
    network.servers.setValue([server])

    # conf.supybot.nick
    # Force the user into specifying a nick if he didn't have one already
    while True:
        nick = something('What nick would you like your bot to use?',
                         default=None)
        try:
            conf.supybot.nick.set(nick)
            break
        except registry.InvalidRegistryValue:
            output("""That's not a valid nick.  Go ahead and pick another.""")

    # conf.supybot.user
    if advanced:
        output("""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
        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.""")
        user = ''
        user = something('What would you like your bot\'s full name to be?',
                         default=nick)
        conf.supybot.user.set(user)
    # conf.supybot.ident (if advanced)
    defaultIdent = 'supybot'
    if advanced:
        output("""IRC servers also allow you to set your ident, which they
        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 use
        'supybot'.  In fact, we prefer that you do this, because it provides
        free advertising for Supybot when users /whois your bot.  But, of
        course, it's your call.""")
        while True:
            ident = something('What would you like your bot\'s ident to be?',
                              default=defaultIdent)
            try:
                conf.supybot.ident.set(ident)
                break
            except registry.InvalidRegistryValue:
                output("""That was not a valid ident.  Go ahead and pick
                another.""")
    else:
        conf.supybot.ident.set(defaultIdent)

    if advanced:
        # conf.supybot.networks.<network>.ssl
        output("""Some servers allow you to use a secure connection via SSL.
        This requires having pyOpenSSL installed.  Currently, you also need
        Twisted installed as only the Twisted drivers supports SSL
        connections.""")
        if yn('Do you want to use an SSL connection?', default=False):
            network.ssl.setValue(True)

    # conf.supybot.networks.<network>.password
    output("""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
    reason it just won't work, it might be that you need to set a
    password.""")
    if yn('Do you want to set such a password?', default=False):
        network.password.set(getpass())

    # conf.supybot.networks.<network>.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.""")
    if yn('Do you want your bot to join some channels when he connects?',
          default=True):
        defaultChannels = ' '.join(network.channels())
        output("""Separate channels with spaces.  If the channel is locked
                  with a key, follow the channel name with the key separated
                  by a comma. For example:
                  #supybot-bots #mychannel,mykey #otherchannel""")
        while True:
            channels = something('What channels?', default=defaultChannels)
            try:
                network.channels.set(channels)
                break
            except registry.InvalidRegistryValue, e:
                output(""""%s" is an invalid IRC channel.  Be sure to prefix
                the channel with # (or +, or !, or &, but no one uses those
                channels, really).  Be sure the channel key (if you are
                supplying one) does not contain a comma.""" % e.channel)
Esempio n. 47
0
                if yn('Would you like to load this plugin?', default=True):
                    configurePlugin(module, advanced)
                    clearLoadedPlugins(plugins, conf.supybot.plugins)
            if not yn('Would you like add another plugin?'):
                break
            name = expect('What plugin would you like to look at?', plugins)

    ###
    # Sundry
    ###
    output("""Although supybot offers a supybot-adduser script, with which
    you can add users to your bot's user database, it's *very* important that
    you have an owner user for you bot.""")
    if yn('Would you like to add an owner user for your bot?', default=True):
        import supybot.ircdb as ircdb
        name = something('What should the owner\'s username be?')
        try:
            id = ircdb.users.getUserId(name)
            u = ircdb.users.getUser(id)
            if u._checkCapability('owner'):
                output("""That user already exists, and has owner capabilities
                already.  Perhaps you added it before? """)
                if yn('Do you want to remove its owner capability?',
                      default=False):
                    u.removeCapability('owner')
                    ircdb.users.setUser(id, u)
            else:
                output("""That user already exists, but doesn't have owner
                capabilities.""")
                if yn('Do you want to add to it owner capabilities?',
                      default=False):
Esempio n. 48
0
def configure(advanced):
    from supybot.questions import yn, something, output
    from supybot.utils.str import format
    import os
    import sqlite
    import re

    def anything(prompt, default=None):
        """Because supybot is pure fail"""
        from supybot.questions import expect
        return expect(prompt, [], default=default)

    Encyclopedia = conf.registerPlugin('Encyclopedia', True)

    enabled = yn("Enable Encyclopedia for all channels?", default=Encyclopedia.enabled._default)
    if advanced:
        datadir = something("Which directory should the factoids database be in?", default=Encyclopedia.datadir._default)
        database = something("What should be the name of the default database (without the .db extension)?", default=Encyclopedia.database._default)
        prefixchar = something("What prefix character should the bot respond to factoid requests with?", default=Encyclopedia.prefixchar._default)
        ignores = set([])
        output("This plugin can be configured to always ignore certain factoid requests, this is useful when you want another plugin to handle them")
        output("For instance, the PackageInfo plugin responds to !info and !find, so those should be ignored in Encyclopedia to allow this to work")
        ignores_i = anything("Which factoid requets should the bot always ignore?", default=', '.join(Encyclopedia.ignores._default))
        for name in re.split(r',?\s', ignores_i):
            ignores.add(name.lower())

        curStable = something("What is short name of the current stable release?", default=Encyclopedia.curStable._default)
        curStableLong = something("What is long name of the current stable release?", default=Encyclopedia.curStableLong._default)
        curStableNum = something("What is version number of the current stable release?", default=Encyclopedia.curStableNum._default)

        curDevel = something("What is short name of the current development release?", default=Encyclopedia.curDevel._default)
        curDevelLong = something("What is long name of the current development release?", default=Encyclopedia.curDevelLong._default)
        curDevelNum = something("What is version number of the current development release?", default=Encyclopedia.curDevelNum._default)

        curLTS = something("What is short name of the current LTS release?", default=Encyclopedia.curLTS._default)
        curLTSLong = something("What is long name of the current LTS release?", default=Encyclopedia.curLTSLong._default)
        curLTSNum = something("What is version number of the current LTS release?", default=Encyclopedia.curLTSNum._default)
    else:
        datadir = Encyclopedia.datadir._default
        database = Encyclopedia.database._default
        prefixchar = Encyclopedia.prefixchar._default
        ignores = Encyclopedia.ignores._default
        curStable = Encyclopedia.curStable._default
        curStableLong = Encyclopedia.curStableLong._default
        curStableNum = Encyclopedia.curStableNum._default
        curDevel = Encyclopedia.curDevel._default
        curDevelLong = Encyclopedia.curDevelLong._default
        curDevelNum = Encyclopedia.curDevelNum._default
        curLTS = Encyclopedia.curLTS._default
        curLTSLong = Encyclopedia.curLTSLong._default
        curLTSNum = Encyclopedia.curLTSNum._default

    relaychannel = anything("What channel/nick should the bot forward alter messages to?", default=Encyclopedia.relaychannel._default)
    output("What message should the bot reply with when a factoid can not be found?")
    notfoundmsg = something("If you include a '%s' in the message, it will be replaced with the requested factoid", default=Encyclopedia.notfoundmsg._default)
    output("When certain factoids are called an alert can be forwarded to a channel/nick")
    output("Which factoids should the bot forward alert calls for?")
    alert = set([])
    alert_i = anything("Separate types by spaces or commas:", default=', '.join(Encyclopedia.alert._default))
    for name in re.split(r',?\s+', alert_i):
        alert.add(name.lower())
    remotedb = anything("Location of a remote database to sync with (used with @sync)", default=Encyclopedia.remotedb._default)
    privateNotFound = yn("Should the bot reply in private when a factoid is not found, as opposed to in the channel?", default=Encyclopedia.privateNotFound._default)
    ignorePrefix = yn('Should the bot respond to factoids whether or not its nick or the prefix character is mentioned?', default=Encyclopedia.ignorePrefix._default)

    Encyclopedia.enabled.setValue(enabled)
    Encyclopedia.datadir.setValue(datadir)
    Encyclopedia.database.setValue(database)
    Encyclopedia.prefixchar.setValue(prefixchar)
    Encyclopedia.ignores.setValue(ignores)
    Encyclopedia.curStable.setValue(curStable)
    Encyclopedia.curStableLong.setValue(curStableLong)
    Encyclopedia.curStableNum.setValue(curStableNum)
    Encyclopedia.curDevel.setValue(curDevel)
    Encyclopedia.curDevelLong.setValue(curDevelLong)
    Encyclopedia.curDevelNum.setValue(curDevelNum)
    Encyclopedia.curLTS.setValue(curLTS)
    Encyclopedia.curLTSLong.setValue(curLTSLong)
    Encyclopedia.curLTSNum.setValue(curLTSNum)
    Encyclopedia.relaychannel.setValue(relaychannel)
    Encyclopedia.notfoundmsg.setValue(notfoundmsg)
    Encyclopedia.alert.setValue(alert)
    Encyclopedia.privateNotFound.setValue(privateNotFound)
    Encyclopedia.ignorePrefix.setValue(ignorePrefix)

    # Create the initial database
    db_dir = Encyclopedia.datadir()
    db_file = Encyclopedia.database()

    if not db_dir:
        db_dir = conf.supybot.directories.data()
        output("supybot.plugins.Encyclopedia.datadir will be set to %r" % db_dir)
        Encyclopedia.datadir.setValue(db_dir)

    if not db_file:
        db_file = 'ubuntu'
        output("supybot.plugins.Encyclopedia.database will be set to %r" % db_file)
        Encyclopedia.database.setValue(db_dir)

    if os.path.exists(os.path.join(db_dir, db_file + '.db')):
        return

    con = sqlite.connect(os.path.join(db_dir, db_file + '.db'))
    cur = con.cursor()

    try:
        cur.execute("""CREATE TABLE facts (
    id INTEGER PRIMARY KEY,
    author VARCHAR(100) NOT NULL,
    name VARCHAR(20) NOT NULL,
    added DATETIME,
    value VARCHAR(200) NOT NULL,
    popularity INTEGER NOT NULL DEFAULT 0
)""")
#"""
        cur.execute("""CREATE TABLE log (
    id INTEGER PRIMARY KEY,
    author VARCHAR(100) NOT NULL,
    name VARCHAR(20) NOT NULL,
    added DATETIME,
    oldvalue VARCHAR(200) NOT NULL
)""")

    except:
        con.rollback()
        raise
    else:
        con.commit()
    finally:
        cur.close()
        con.close()
Esempio n. 49
0
def configure(advanced):
    from supybot.questions import something
    conf.registerPlugin('Redmine', True)
    url = something(
        """please specify the domain to the Redmine instance to query""")
    Redmine.globalRedmineDomain.setValue(url)