Пример #1
0
def init():
    global lastline
    lastline = LastLine()
    callbacks.add('PRIVMSG', lastline.privmsgcb, lastline.precb)
    callbacks.add('CONSOLE', lastline.privmsgcb, lastline.precb)
    callbacks.add('Message', lastline.privmsgcb, lastline.precb)
    cmnds.add(sed_expression, handle_sed, 'USER', regex=True)
    examples.add('s', 'Perform substitution on last message spoken.', 's/foo/bar/')
    return 1
Пример #2
0
def init():
  """ Init """
  if cfg.enable:
    inputmorphs.add(fishin)
    outputmorphs.add(fishout)
    callbacks.add("NOTICE", dh1080_exchange)
    cmnds.add("fish", handle_fish, "OPER")
    examples.add("fish", "command that handles fish enrypting over IRC", "fish help")
  else: logging.warn("fish plugin is not enabled - use fish-cfg enable 1")
Пример #3
0
def init():
    global lastline
    lastline = LastLine()
    callbacks.add('PRIVMSG', lastline.privmsgcb, lastline.precb)
    callbacks.add('CONSOLE', lastline.privmsgcb, lastline.precb)
    callbacks.add('Message', lastline.privmsgcb, lastline.precb)
    cmnds.add(sed_expression, handle_sed, 'USER', regex=True)
    examples.add('s', 'Perform substitution on last message spoken.',
                 's/foo/bar/')
    return 1
Пример #4
0
def init():
    """ Init """
    if cfg.enable:
        inputmorphs.add(fishin)
        outputmorphs.add(fishout)
        callbacks.add("NOTICE", dh1080_exchange)
        cmnds.add("fish", handle_fish, "OPER")
        examples.add("fish", "command that handles fish enrypting over IRC",
                     "fish help")
    else:
        logging.warn("fish plugin is not enabled - use fish-cfg enable 1")
Пример #5
0
 def __init__(self):
     self.hide = []
     modname = whichplugin()
     logging.debug("persistconfig - module name is %s" % modname)
     self.plugname = modname.split('.')[-1]
     Config.__init__(self, 'plugs' + os.sep + modname, "config")
     self.modname = modname
     cmndname = "%s-cfg" % self.plugname
     logging.debug('persistconfig - added command %s (%s)' % (cmndname, self.plugname))
     from jsb.lib.commands import cmnds, Command
     cmnds[cmndname] = Command(self.modname, cmndname, self.cmnd_cfg, ['OPER', ])
     examples.add(cmndname, "%s configuration" % self.plugname, cmndname)
     cmndnamesave = cmndname + "save"
     cmnds[cmndnamesave] = Command(self.modname, cmndname, self.cmnd_cfgsave, ['OPER',])
     examples.add(cmndnamesave, "save %s configuration" % self.plugname, cmndnamesave)
Пример #6
0
## defines

URL = "http://www.deanclatworthy.com/imdb/?q=%s"

## imdb command

def handle_imdb(bot, event):
    """ arguments: <query> - query the imdb databae at http://www.deanclatworthy.com/imdb/ """
    if not event.rest:  event.missing("<query>") ; return
    query = event.rest.strip()
    urlquery = query.replace(" ", "+")
    result = {}
    rawresult = getjson().loads(geturl2(URL % urlquery))
    # the API are limited to 30 query per hour, so avoid querying it just for testing purposes
    # rawresult = {u'ukscreens': 0, u'rating': u'7.7', u'genres': u'Animation,&nbsp;Drama,Family,Fantasy,Music', u'title': u'Pinocchio', u'series': 0, u'country': u'USA', u'votes': u'23209', u'languages': u'English', u'stv': 0, u'year': None, u'usascreens': 0, u'imdburl': u'http://www.imdb.com/title/tt0032910/'}
    if not rawresult: event.reply("couldn't look up %s" % query) ; return
    if 'error' in rawresult: event.reply("%s" % rawresult['error']) ; return
    print rawresult
    for key in rawresult.keys():
        if not rawresult[key]: result[key] = u"n/a"
        else: result[key] = rawresult[key]
    for key in result.keys():
        try: result[key] = striphtml(decode_html_entities(rawresult[key]))
        except AttributeError: pass
    if "year" in rawresult.keys(): event.reply("%(title)s (%(country)s, %(year)s): %(imdburl)s | rating: %(rating)s (out of %(votes)s votes) | Genres %(genres)s | Language: %(languages)s" % result )
    else: event.reply("%(title)s (%(country)s): %(imdburl)s | rating: %(rating)s (out of %(votes)s votes) | Genres %(genres)s | Language: %(languages)s" % result )

cmnds.add("imdb", handle_imdb, ["OPER", "USER", "GUEST"])
examples.add("imdb", "query the imdb database.", "imdb the matrix")
Пример #7
0
Файл: tail.py Проект: code2u/jsb
#
#

""" tail bot results. """

## jsb imports

from jsb.utils.generic import waitforqueue
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples

## tail command

def handle_tail(bot, ievent):
    """ no arguments - show last <nr> elements, use this command in a pipeline. """
    if not ievent.inqueue:
        ievent.reply("use tail in a pipeline")
        return
    try: nr = int(ievent.args[0])
    except (ValueError, IndexError):
        ievent.reply('tail <nr>')
        return
    result = waitforqueue(ievent.inqueue, 3000)
    if not result:
        ievent.reply('no data to tail')
        return
    ievent.reply('results: ', result[-nr:])
    
cmnds.add('tail', handle_tail, ['OPER', 'USER', 'GUEST'])
examples.add('tail', 'show last <nr> lines of pipeline output', 'list ! tail 5')
Пример #8
0
""" show system configuration stuff. """

## jsb imports

from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.exception import handle_exception

## basic imports

import os

## sysconf command

def handle_sysconf(bot, event):
    if bot.type != "console": event.reply("this command only works on the console bot") ; return
    if not event.rest: event.missing("<item>") ; return
    target = event.rest.upper()
    todo = []
    for item in os.sysconf_names:
        if target in item: todo.append(item)
    result = {}
    for t in todo:
        try: result[t] = os.sysconf(t)
        except Exception, ex: pass
    if result: event.reply("sysinfo found for %s" % target, result)
    else: event.reply("no result found for %s" % target)

cmnds.add("sysconf", handle_sysconf, "OPER")
examples.add("sysconf", "show sysconf information", "sysconf")
 
Пример #9
0
        bot.putevent(event.userhost, event.channel, event.txt, event)
        #if event.txt == 'wer ist da?':
        #    event.txt = '!ul'
        #    bot.putevent(event)
        print 'DONE'
        return True
    return False

## pr callbacks

def prcb(bot, event):
    event.bind(bot)

    return 0

callbacks.add('PRIVMSG', prcb, prepr)
callbacks.add('MESSAGE', prcb, prepr)
callbacks.add('CONSOLE', prcb, prepr)

## pr command

def handle_pr(bot, event):
    if not event.rest: event.missing("<what>") ; return
    k = event.rest.lower()
    item = PRItem(event.channel.lower() + "-" + k)
    if item.data.count: event.reply("pr of %s is %s" % (k, item.data.count))
    else: event.reply("%s doesn't have pr yet." % k)

cmnds.add('pr', handle_pr, ['USER', ])
examples.add('pr', 'show pr', 'pr jsb')
Пример #10
0
            ievent.reply("only one character is allowed")
            return
        try: ievent.chan.data.cc = what
        except (KeyError, TypeError):
            ievent.reply("no channel %s in database" % chan)
            return
        ievent.chan.save()
        ievent.reply('control char set to %s' % what)
    except IndexError:
        try:
            cchar = ievent.getcc()
            ievent.reply('controlchar are/is %s' % cchar)
        except (KeyError, TypeError): ievent.reply("default cc is %s" % bot.cfg['defaultcc'])

cmnds.add('cc', handle_cc, 'USER')
examples.add('cc', 'set control char of channel or show control char of channel','1) cc ! 2) cc')

## cc-add command

def handle_ccadd(bot, ievent):
    """ arguments: <character> - add a control char to the channels cc list. """
    try:
        what = ievent.args[0]
        if not bot.users.allowed(ievent.userhost, 'OPER'): return
        if len(what) > 1:
            ievent.reply("only one character is allowed")
            return
        try: ievent.chan.data.cc += what
        except (KeyError, TypeError):
            ievent.reply("no channel %s in database" % ievent.channel)
            return
Пример #11
0
def handle_nsadd(bot, ievent):
    """ arguments: <password> [<nickserv nick>] [<identify command>] - add a bot to the nickserv. """
    if bot.jabber: return
    if len(ievent.args) < 1:
        ievent.missing('<password> [<nickserv nick>] [<identify command>]')
        return
    if nsauth.has(bot): ievent.reply('replacing previous configuration')
    options = {}
    if len(ievent.args) >= 1: options.update({'password': ievent.args[0]})
    if len(ievent.args) >= 2: options.update({'nickserv': ievent.args[1]})
    if len(ievent.args) >= 3: options.update({'identify': ' '.join(ievent.args[2:])})
    nsauth.add(bot, **options)
    ievent.reply('ok')

cmnds.add('ns-add', handle_nsadd, 'OPER', threaded=True)
examples.add('ns-add', 'ns-add <password> [<nickserv nick>] [<identify command>] .. add nickserv', 'ns-add mekker')

## ns-del command

def handle_nsdel(bot, ievent):
    """ arguments: <botname> - remove a bot from nickserv. """
    if bot.jabber: return
    if len(ievent.args) != 1:
        ievent.missing('<botname>')
        return
    botname = ievent.args[0]
    fbot = getfleet().byname(botname)
    if not fbot:
        ievent.reply('fleet bot %s not found' % botname)
        return
    if not nsauth.has(fbot):
Пример #12
0
        windangle = float(data[26]) + 11.25
        winddir = ''
        if windangle > 0 and windangle <= 22.5: winddir = 'N'
        if windangle > 22.5 and windangle <= 45: winddir = 'NNE'
        if windangle > 45 and windangle <= 67.5: winddir = 'NE'
        if windangle > 67.5 and windangle <= 90: winddir = 'ENE'
        if windangle > 90 and windangle <= 112.5: winddir = 'E'
        if windangle > 112.5 and windangle <= 135: winddir = 'ESE'
        if windangle > 135 and windangle <= 157.5: winddir = 'SE'
        if windangle > 157.5 and windangle <= 180: winddir = 'SSE'
        if windangle > 180 and windangle <= 202.5: winddir = 'S'
        if windangle > 202.5 and windangle <= 225: winddir = 'SSW'
        if windangle > 225 and windangle <= 247.5: winddir = 'SW'
        if windangle > 247.5 and windangle <= 270: winddir = 'WSW'
        if windangle > 270 and windangle <= 292.5: winddir = 'W'
        if windangle > 292.5 and windangle <= 315: winddir = 'WNW'
        if windangle > 315 and windangle <= 337.5: winddir = 'NW'
        if windangle > 337.5 and windangle <= 360: winddir = 'NNW'
        if windangle > 360 and windangle <= 382.5: winddir = 'N'
        ievent.reply(temp + ' C, ' + humid + '% humidity, ' + windspeed +
                     ' m/s ' + winddir + ', ' + precip +
                     ' mm precipitation, ' + pressure + ' kPa.')
    except urllib2.URLError:
        ievent.reply('Cannot read from server.')
    except:
        ievent.reply('What is this madness? ' + str(sys.exc_info()[0]))


cmnds.add("wau-temp", get_temp, ["OPER", "USER", "GUEST"])
examples.add("wau-temp", "Get temperature from the WAU service.", "wau-temp")
Пример #13
0
    if len(ievent.args) < 1:
        ievent.missing('<password> [<nickserv nick>] [<identify command>]')
        return
    if nsauth.has(bot): ievent.reply('replacing previous configuration')
    options = {}
    if len(ievent.args) >= 1: options.update({'password': ievent.args[0]})
    if len(ievent.args) >= 2: options.update({'nickserv': ievent.args[1]})
    if len(ievent.args) >= 3:
        options.update({'identify': ' '.join(ievent.args[2:])})
    nsauth.add(bot, **options)
    ievent.reply('ok')


cmnds.add('ns-add', handle_nsadd, 'OPER', threaded=True)
examples.add(
    'ns-add',
    'ns-add <password> [<nickserv nick>] [<identify command>] .. add nickserv',
    'ns-add mekker')

## ns-del command


def handle_nsdel(bot, ievent):
    """ remove a bot from nickserv. """
    if bot.jabber: return
    if len(ievent.args) != 1:
        ievent.missing('<fleetbot name>')
        return
    botname = ievent.args[0]
    fbot = getfleet().byname(botname)
    if not fbot:
        ievent.reply('fleet bot %s not found' % botname)
Пример #14
0
            urls.append(striphtml(line.strip()).split('[Open')[0])
    if len(urls) == 3: urls.pop(0)
    set(url, json.dumps(urls), namespace='tinyurl')
    return urls


## tinyurl command


def handle_tinyurl(bot, ievent):
    """ arguments: <url> - get tinyurl from provided url. """
    if not ievent.rest and (not urlcache.has_key(bot.cfg.name) or
                            not urlcache[bot.cfg.name].has_key(ievent.target)):
        ievent.missing('<url>')
        return
    elif not ievent.rest:
        url = urlcache[bot.cfg.name][ievent.target]
    else:
        url = ievent.rest
    url = valid_url(url)
    if not url:
        ievent.reply('invalid or bad URL')
        return
    tinyurl = get_tinyurl(url)
    if tinyurl: ievent.reply(' .. '.join(tinyurl))
    else: ievent.reply('failed to create tinyurl')


cmnds.add('tinyurl', handle_tinyurl, ['OPER', 'USER', 'GUEST'], threaded=True)
examples.add('tinyurl', 'show a tinyurl', 'tinyurl http://jsonbbot.org')
Пример #15
0
from jsb.lib.aliases import setalias
from jsb.lib.config import getmainconfig
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples

## data-event command


def handle_dataevent(bot, event):
    """ no arguments - dump event to json. """
    event.reply(event.fordisplay())


cmnds.add("data-event", handle_dataevent, "OPER")
examples.add('data-event', 'dump event data', 'data-event')

## data-chan command


def handle_datachan(bot, event):
    """ no arguments - dump channel data to json. """
    event.reply(event.chan.data.fordisplay())


cmnds.add("data-chan", handle_datachan, "OPER")
examples.add('data-chan', 'dump channel data', 'data-chan')

## data-bot command

Пример #16
0
def init():
    if cfg['enable']: startserver()

def shutdown():
    if cfg['enable']: stopserver()

## rest-start command

def handle_rest_start(bot, event):
    """ no arguments - start the rest server. """
    cfg['enable'] = 1
    cfg.save()
    startserver()
    event.done()

cmnds.add('rest-start', handle_rest_start, 'OPER')
examples.add('rest-start', 'start the REST server', 'rest-start')

## rest-stop command

def handle_rest_stop(bot, event):
    """ no arguments - stop the rest server. """
    cfg['enable'] = 0
    cfg.save()
    stopserver()
    event.done()

cmnds.add('rest-stop', handle_rest_stop, 'OPER')
examples.add('rest-stop', 'stop the REST server', 'rest-stop')
Пример #17
0
        for i in state['urls'][bot.cfg.name][ievent.channel]:
            if ievent.rest in i: result.append(i)
    except KeyError:
        ievent.reply('no urls known for channel %s' % ievent.channel)
        return
    except Exception, ex:
        ievent.reply(str(ex))
        return
    if result: ievent.reply('results matching %s: ' % ievent.rest, result)
    else:
        ievent.reply('no result found')
        return


cmnds.add('url-search', handle_urlsearch, ['OPER', 'USER', 'GUEST'])
examples.add('url-search', 'search matching url entries', 'url-search jsonbot')

## url-searchall command


def handle_urlsearchall(bot, ievent):
    """ arguments: <searchtxt> - search all urls. """
    if not state:
        ievent.reply('rss state not initialized')
        return
    if not ievent.rest:
        ievent.missing('<searchtxt>')
        return
    result = []
    try:
        for i in state['urls'].values():
Пример #18
0
    try:
        (options, rest) = getopt.getopt(ievent.args, 'r')
    except getopt.GetoptError, ex:
        ievent.reply(str(ex))
        return
    result = waitforqueue(ievent.inqueue, 3000)
    if not result:
        ievent.reply('no data to grep on')
        return
    doregex = False
    for i, j in options:
        if i == '-r': doregex = True
    res = []
    if doregex:
        try:
            reg = re.compile(' '.join(rest))
        except Exception, ex:
            ievent.reply("can't compile regex: %s" % str(ex))
            return
        for i in result:
            if not re.search(reg, i): res.append(i)
    else:
        for i in result:
            if ievent.rest not in str(i): res.append(i)
    if not res: ievent.reply('no result')
    else: ievent.reply('results', res)


cmnds.add('not', handle_not, ['USER', 'GUEST'])
examples.add('not', 'reverse grep used in pipelines', 'list | not todo')
Пример #19
0
    if event and not event.bottype == "irc": return txt
    splitted = txt.split()
    for s in splitted:
        for t, color in state.data.colormapping.iteritems():
            try: c = int(color)
            except: logging.warn("color - %s is not a digit" % color) ; continue
            if t in s: txt = txt.replace(s, "\003%s%s\003" % (c, s))
    return txt

## color-list command

def handle_colorlist(bot, event):
    event.reply("colors set: ", state.data.colormapping)

cmnds.add("color-list", handle_colorlist, ["OPER"])
examples.add("color-list", "show color mapping", "color-list")

## color-add command

def handle_coloradd(bot, event):
    try: (txt, color) = event.rest.rsplit(" ", 1)
    except (TypeError, ValueError): event.missing("<txt> <color>") ; return
    state.data.colormapping[txt] = color.upper()
    state.save()
    event.reply("color of %s set to %s" % (txt, color))

cmnds.add("color-add", handle_coloradd, ["OPER"])
examples.add("color-add", "add a text color replacement to the morphs", "color-add dunker 8")

## color-del command
Пример #20
0
from jsb.lib.boot import savecmndtable, savepluginlist, boot, plugin_packages, clear_tables, getcmndtable, getcallbacktable
from jsb.lib.plugins import plugs
from jsb.lib.botbase import BotBase
from jsb.lib.exit import globalshutdown
from jsb.utils.generic import stringsed

## admin-boot command

def handle_adminboot(bot, ievent):
    """ boot the bot .. do some initialisation. """
    if 'saveperms' in ievent.rest: boot(force=True, saveperms=True)
    else: boot(force=True, saveperms=False)
    ievent.done()

cmnds.add('admin-boot', handle_adminboot, 'OPER')
examples.add('admin-boot', 'initialize the bot .. cmndtable and pluginlist', 'admin-boot')

## admin-commands

def handle_admincommands(bot, ievent):
    """ load all available plugins. """
    cmnds = getcmndtable()
    if not ievent.rest: ievent.reply("commands: ", cmnds)
    else:
        try: ievent.reply("%s command is found in %s " % (ievent.rest, cmnds[ievent.rest]))
        except KeyError: ievent.reply("no such commands available") 

cmnds.add('admin-commands', handle_admincommands, 'OPER')
examples.add('admin-commands', 'show runtime command table', 'admin-commands')

## admin-callbacks
Пример #21
0
        return
    result = []
    res = []
    aliases = ievent.chan.data.aliases
    if aliases:
        for i, j in aliases.iteritems():
            if what in i or what in j: result.append((i, j))
    if not result: ievent.reply('no %s found' % what)
    else:
        for i in result:
            res.append("%s => %s" % i)
        ievent.reply("aliases matching %s: " % what, res)


cmnds.add('alias-search', handle_aliassearch, 'USER')
examples.add('alias-search', 'search aliases', ' alias-search web')

## alias-set command


def handle_aliasset(bot, ievent):
    """ alias-set <from> <to> .. set alias. """
    try:
        (aliasfrom, aliasto) = (ievent.args[0], ' '.join(ievent.args[1:]))
    except IndexError:
        ievent.missing('<from> <to>')
        return
    if not aliasto:
        ievent.missing('<from> <to>')
        return
    if cmnds.has_key(aliasfrom):
Пример #22
0
first_callbacks.add('TORNADO', watchcallback, prewatchcallback)

## watcher-start command

def handle_watcherstart(bot, event):
    """ arguments: [<channel>] - start watching a target channel. """
    target = event.rest or event.channel
    watched.subscribe(bot.cfg.name, bot.type, target, event.channel)
    if not target in event.chan.data.watched:
        event.chan.data.watched.append(target)
        event.chan.save()
    event.done()

cmnds.add('watcher-start', handle_watcherstart, 'OPER')
cmnds.add('watch', handle_watcherstart, 'USER')
examples.add('watcher-start', 'start watching a channel. ', 'watcher-start <channel>')

## watcher-reset command

def handle_watcherreset(bot, event):
    """ no arguments - reset all watcher for a channel. """
    watched.reset(event.channel)
    event.done()

cmnds.add('watcher-reset', handle_watcherreset, ['OPER', 'USER', 'GUEST'])
examples.add('watcher-reset', 'stop watching', 'watcher-reset')

## watcher-stop command

def handle_watcherstop(bot, event):
    """ arguments: [<channel>] - stop watching a channel. """
Пример #23
0
            % os.path.basename(__file__)[:-3])
        return
    result = []
    for name in sorted(watcher.data.keys()):
        if watcher.data[name]:
            result.append('on %s:' % name)
        for channel in sorted(watcher.data[name].keys()):
            result.append(channel)
    if result:
        ievent.reply(' '.join(result))
    else:
        ievent.reply('no watchers running')


cmnds.add('mpd-jump', handle_mpd_jump, 'MPD', threaded=True)
examples.add('mpd-jump', 'jump to the specified playlist id', 'mpd-jump 666')
cmnds.add('mpd-watch-start', handle_mpd_watch_start, 'MPD', threaded=True)
cmnds.add('mpd-watch-stop', handle_mpd_watch_stop, 'MPD', threaded=True)
cmnds.add('mpd-watch-list', handle_mpd_watch_list, 'MPD', threaded=True)

#mpd                                           Display status
cmnds.add('mpd', handle_mpd, 'USER', threaded=True)
examples.add('mpd', 'Display mpd status', 'mpd')

#mpd-add <file>                                Add a song to the current playlist
cmnds.add('mpd-add', handle_mpd_add, 'MPD', threaded=True)
cmnds.add('mpd-queue', handle_mpd_add, 'MPD', threaded=True)
examples.add(
    'mpd-add', 'Add a song to the current playlist',
    'mpd-add mp3/bigbeat/fatboy slim/fatboy slim - everybody needs a 303.mp3')
Пример #24
0
## irccat2_add_alias command

def handle_irccat2_add_alias(bot, ievent):
    if len(ievent.args) != 1:
        ievent.reply("syntax: irccat2_add_alias <alias> (where <alias> is the channel you want notifications for)")
        return
    dest = ievent.args[0]
    if not cfg.aliases: cfg.aliases = {}
    if dest not in cfg["aliases"]:
        cfg["aliases"][dest] = []
    if ievent.channel not in cfg["aliases"][dest]:
        cfg["aliases"][dest].append(ievent.channel)
    cfg.save()
    ievent.reply("%s will now receive irccat2 messages directed at %s" % (ievent.channel, dest))
cmnds.add("irccat2_add_alias", handle_irccat2_add_alias, ['OPER'])
examples.add("irccat2_add_alias", "add an alias to the current channel from the specified one", "irccat2_add_alias #firebreath")

## irccat2_list_aliases command

def handle_irccat2_list_aliases(bot, ievent):
    """ List all aliases defined for the current channel """
    aliases = [dest for dest, chanlist in cfg["aliases"].iteritems() if ievent.channel in chanlist]

    ievent.reply("%s is receiving irccat2 messages directed at: %s" % (ievent.channel, ", ".join(aliases)))
cmnds.add("irccat2_list_aliases", handle_irccat2_list_aliases, ['OPER'])
examples.add("irccat2_list_aliases", "lists the aliases for the current channel", "irccat2_list_aliases")

## irccat2_del_alias command

def handle_irccat2_del_alias(bot, ievent):
    if len(ievent.args) != 1:
Пример #25
0
        >>> net.has_key('192.168.2.0')
        False
        >>> net.has_key('192.0.2.42')
        True
        '''
        return self.__contains__(ip)

    def size(self):
        '''
        Number of ip's within the network.
        '''
        return 2 ** ((self.version() == 4 and 32 or 128) - self.mask)

## ipcalc command

def handle_ipcalc(bot, ievent):
    """ arguments: <ip>[</size>] .. calculate IP subnets. """
    if not ievent.args:
        ievent.missing('<ip>[/<size>]')
        return
    try:
        net = Network(ievent.args[0])
    except ValueError, e:
        ievent.reply('error: %s' % e)
        return
    ievent.reply('version: %d, address: %s, network size: %d, network address: %s, netmask: %s, first host in network: %s, last host in network: %s, network info: %s' % \
        (net.version(), str(net), net.mask, net.network(), net.netmask(), net.host_first(), net.host_last(), net.info()))

cmnds.add('ipcalc', handle_ipcalc, ['OPER', 'USER', 'GUEST'])
examples.add('ipcalc', 'ip calculator', 'ipcalc 127.0.0.1/12')
Пример #26
0
        (what, description) = event.rest.split(" is ", 1)
    except ValueError:
        event.missing("<item> is <description>")
        return
    what = what.lower()
    items = GlobalPersist("learndb")
    if not items.data: items.data = LazyDict()
    if not items.data.has_key(what): items.data[what] = []
    if description not in items.data[what]:
        items.data[what].append(description)
    items.save()
    event.reply("%s item added to global database" % what)


cmnds.add('learn', handle_learn, ['OPER', 'USER', 'GUEST'])
examples.add('learn', 'learn the bot a description of an item.',
             "learn dunk is botpapa")

## learn-chan command


def handle_learnchan(bot, event):
    """" arguments: <item> is <description> - set an information item. """
    if not event.rest:
        event.missing("<item> is <description>")
        return
    try:
        (what, description) = event.rest.split(" is ", 1)
    except ValueError:
        event.missing("<item> is <description>")
        return
    what = what.lower()
Пример #27
0
    project = {
        "name": ievent.args[0],
        "url": ievent.args[1].strip("/"),
        "username": ievent.args[2],
        "password": ievent.args[3],
    }

    if not cfg.data.has_key("projects"):
        cfg.data["projects"] = {}
    cfg.data["projects"][project["name"]] = project
    cfg.save()

    ievent.reply("Added fisheye project %s" % project["name"])
cmnds.add("add_fisheye_project", handle_add_fisheye_project, ["OPER"])
examples.add("add_fisheye_project", "add a fisheye project", "add_fisheye_project FireBreath http://code.firebreath.org myuser mypassword")

## fisheye_commit_loopup_enable command

def handle_fisheye_commit_lookup_enable(bot, ievent):
    """ enable fisheye commit lookups in a channel. """
    if len(ievent.args) != 1:
        ievent.reply("syntax: fisheye_commit_lookup_enable project (e.g. firebreath")
        return
    if not cfg.data.has_key(ievent.channel):
        cfg.data[ievent.channel] = []
    project = ievent.args[0]

    if "projects" not in cfg.data or project not in cfg.data["projects"]:
        ievent.reply("Unknown fisheye project %s" % project)
        return
Пример #28
0
        if not gid in state.data.watch or not target in state.data.ids[gid]:
            state.data.ids[gid].append(target)
            state.data.watch.append(gid)
        else:
            event.reply("we are already monitoring %s in %s" %
                        (gid, str(target)))
    state.save()
    sync()
    event.done()


cmnds.add("overflow-start", handle_overflowstart, [
    "OPER",
])
examples.add("overflow-start",
             "start monitoring a stackoverflow id into the channel",
             "overflow-start bthate:625680")

## overflow-stop command


def handle_overflowstop(bot, event):
    if not event.args:
        event.missing("<stackoveflow id")
        return
    global state
    id = event.args[0]
    try:
        del state.data.ids[id]
        del state.data.names[id]
        state.save()
Пример #29
0
import logging

## admin-save command

def handle_adminsave(bot, ievent):
    """ no arguments - boot the bot .. do some initialisation. """
    ievent.reply("saving mainconfig")
    getmainconfig().save()
    ievent.reply("saving fleet bots")
    getfleet().save()
    ievent.reply("saving all plugins")
    plugs.save()
    ievent.done()

cmnds.add('admin-save', handle_adminsave, 'OPER')
examples.add('admin-save', 'initialize the bot', 'admin-boot')

## admin-boot command

def handle_adminboot(bot, ievent):
    """ no arguments - boot the bot .. do some initialisation. """
    ievent.reply("reloading all plugins")
    if 'saveperms' in ievent.rest: boot(force=True, saveperms=True, clear=True)
    else: boot(force=True, saveperms=False, clear=True)
    ievent.done()

cmnds.add('admin-boot', handle_adminboot, 'OPER')
examples.add('admin-boot', 'initialize the bot', 'admin-boot')

## admin-bootthreaded command
Пример #30
0
    try: return bans[bot.cfg.name][channel]
    except KeyError: return []

def get_bothost(bot):
    return getwho(bot, bot.cfg.nick).split('@')[-1].lower()

## ban-list command

def handle_ban_list(bot, ievent):
    """ no arguments - list all bans. """
    banslist = get_bans(bot, ievent.channel)
    if not banslist: ievent.reply('the ban list for %s is empty' % ievent.channel)
    else: ievent.reply('bans on %s: ' % ievent.channel, banslist)

cmnds.add('ban-list', handle_ban_list, 'OPER', threaded=True)
examples.add("ban-list", "list all bans.", "ban-list")

## ban-remove command

def handle_ban_remove(bot, ievent):
    """ arguments: <banlistindex> - remove a ban. """
    channel = ievent.channel.lower()
    if len(ievent.args) != 1 or not ievent.args[0].isdigit(): ievent.missing('<banlistindex>') ; return
    if not bot.cfg.name in bans or not channel in bans[bot.cfg.name]:
        banslist = get_bans(bot, ievent.channel)
    else:
        banslist = bans[bot.cfg.name][channel]
        index = int(ievent.args[0])-1
        if len(banslist) <= index: ievent.reply('ban index out of range')
        else:
            unban = banslist[index]
Пример #31
0
## chatlog-on command


def handle_chatlogon(bot, ievent):
    """ enable chatlog. """
    chan = ievent.channel
    enablelogging(bot.name, chan)
    if [bot.name, chan] not in cfg.get('channels'):
        cfg['channels'].append([bot.name, chan])
        cfg.save()
    ievent.reply('chatlog enabled on (%s,%s)' % (bot.name, chan))


cmnds.add('chatlog-on', handle_chatlogon, 'OPER')
examples.add(
    'chatlog-on',
    'enable chatlog on <channel> or the channel the commands is given in',
    '1) chatlog-on 2) chatlog-on #dunkbots')

## chatlog-off command


def handle_chatlogoff(bot, ievent):
    """ disable chatlog. """
    try:
        cfg['channels'].remove([bot.name, ievent.channel])
        cfg.save()
    except ValueError:
        ievent.reply('chatlog is not enabled in (%s,%s)' %
                     (bot.name, ievent.channel))
        return
    try:
Пример #32
0
        event.blip.append(element.Gadget(url))
        return True
    else: event.reply("can't find root blip.") ; return False

## gadget-load command

def handle_gadgetload(bot, event):
    if event.bottype != "wave": event.reply("this command only works in google wave.") ; return
    if not event.rest: event.missing('<gadgetname>') ; return
    try:
        url = gadgeturls.data[event.rest]
        if load(event, url): event.reply('loaded %s' % url)
    except KeyError: event.reply("we don't have a url for %s" % event.rest)

cmnds.add("gadget-load", handle_gadgetload, 'USER')
examples.add("gadget-load", "load a gadget into a blip", "gadget-load")

## gadget-loadroot command

def handle_gadgetloadroot(bot, event):
    if event.bottype != "wave": event.reply("this command only works in google wave.") ; return
    if not event.rest: event.missing('<gadgetname>') ; return
    try:
        url = gadgeturls.data[event.rest]
        if loadroot(event, url): event.reply('loaded %s' % url)
    except KeyError: event.reply("we don't have a url for %s" % event.rest)

cmnds.add("gadget-loadroot", handle_gadgetloadroot, 'USER')
examples.add("gadget-loadroot", "load a gadget into the root blip", "gadget-loadroot")

## gadget-iframe command
Пример #33
0
Файл: more.py Проект: code2u/jsb
## basic imports

import logging

## more command


def handle_more(bot, ievent):
    """ no arguments - pop message from the output cache. """
    if ievent.msg and bot.type == "irc":
        target = ievent.nick
    else:
        target = ievent.channel
    try:
        txt, size = outcache.more(u"%s-%s" % (bot.cfg.name, target))
    except IndexError:
        txt = None
    if not txt:
        ievent.reply("no more data available for %s" % target)
        return
    txt = bot.outputmorphs.do(txt, ievent)
    if size:
        txt += "<b> - %s more</b>" % str(size)
    bot.outnocb(target, txt, response=ievent.response, event=ievent)
    bot.outmonitor(ievent.origin or ievent.userhost, ievent.channel, txt)


cmnds.add("more", handle_more, ["USER", "GUEST"])
examples.add("more", "return txt from output cache", "more")
Пример #34
0
            if ievent.rest in i:
                result.append(i)
    except KeyError:
        ievent.reply('no urls known for channel %s' % ievent.channel)
        return
    except Exception, ex:
        ievent.reply(str(ex))
        return
    if result:
        ievent.reply('results matching %s: ' % ievent.rest, result)
    else:
        ievent.reply('no result found')
        return

cmnds.add('url-search', handle_urlsearch, ['USER', 'WEB', 'GUEST'])
examples.add('url-search', 'search matching url entries', 'url-search jsonbot')

## url-searchall command

def handle_urlsearchall(bot, ievent):
    if not state:
        ievent.reply('rss state not initialized')
        return
    if not ievent.rest:
        ievent.missing('<what>')
        return
    result = []
    try:
        for i in state['urls'].values():
            for urls in i.values():
                for url in urls:
Пример #35
0
    txt = re.sub('\s+', ' ', txt)
    txt = txt.replace('|', ' - ')
    return txt


## commands


def handle_wikipedia(bot, ievent):
    """ <what> .. search wikipedia. """
    if not ievent.rest:
        ievent.missing('<what>')
        return
    res = searchwiki(ievent.rest)
    if not res[0]:
        ievent.reply('no result found')
        return
    result = splittxt(res[0])
    if result:
        prefix = u'%s ===> ' % res[1]
        ievent.reply(prefix, result, dot="<br><br>")
    else:
        ievent.reply("no data found on %s" % event.rest)


cmnds.add('wikipedia', handle_wikipedia, ['USER', 'GUEST'])
examples.add(
    'wikipedia',
    'wikipedia ["-" <countrycode>] <what> .. search wikipedia for <what>',
    '1) wikipedia gozerbot 2) wikipedia -nl bot')
Пример #36
0

def handle_set(bot, ievent):
    """ let the user manage its own state. """
    try:
        (item, value) = ievent.args
    except ValueError:
        ievent.missing("<item> <value>")
        return
    ievent.user.state.data[item.lower()] = value
    ievent.user.state.save()
    ievent.reply("%s set to %s" % (item.lower(), value))


cmnds.add('set', handle_set, ['OPER', 'USER', 'GUEST'])
examples.add('set', 'set userstate', 'set place heerhugowaard')

## get command


def handle_get(bot, ievent):
    """ get state of a user. """
    target = ievent.rest
    if target: target = target.lower()
    userstate = ievent.user.state
    result = []
    for i, j in userstate.data.iteritems():
        if target == i or not target: result.append("%s=%s" % (i, j))
    if result: ievent.reply("state: ", result)
    else: ievent.reply('no userstate of %s known' % ievent.userhost)
Пример #37
0
    name = ievent.channel
    if not name:
        ievent.reply("can't find username for %s" % ievent.auth)
        return
    ttime = strtotime(what)
    nr = 0
    todo = TodoList(name)
    if not ttime == None:
        ievent.reply('time detected ' + time.ctime(ttime))
        nr = todo.add(what, ttime)
    else:
        nr = todo.add(what)
    ievent.reply('todo item %s added' % nr)

cmnds.add('todo', handle_todo, ['USER', 'GUEST'])
examples.add('todo', 'todo [<item>] .. show todo items or add a todo item', \
'1) todo 2) todo program the bot 3) todo 22:00 sleep')

def handle_tododone(bot, ievent):
    """ todo-done <listofnrs> .. remove todo items """
    if len(ievent.args) == 0:
        ievent.missing('<list of nrs>')
        return
    try:
        nrs = []
        for i in ievent.args:
            nrs.append(int(i))
        nrs.sort()
    except ValueError:
        ievent.reply('%s is not an integer' % i)
        return
    name = ievent.channel
Пример #38
0
callbacks.add('MESSAGE', catchUrls, catchHasUrls, threaded=True)
callbacks.add('DISPATCH', catchUrls, catchHasUrls, threaded=True)
callbacks.add('TORNADO', catchUrls, catchHasUrls, threaded=True)

## urlinfo-enable command


def handle_urlinfo_enable(bot, ievent):
    """ no arguments - enable urlinfo in a channel. """
    cfg.data[ievent.channel] = True
    cfg.save()
    ievent.reply('urlinfo enabled')


cmnds.add('urlinfo-enable', handle_urlinfo_enable, ['OPER'])
examples.add('urlinfo-enable', 'enable urlinfo in the channel',
             'urlinfo-enable')

## urlinfo-disable command


def handle_urlinfo_disable(bot, ievent):
    """ no arguments - disable urlinfo in a channel. """
    cfg.data[ievent.channel] = False
    cfg.save()
    ievent.reply('urlinfo disabled')


cmnds.add('urlinfo-disable', handle_urlinfo_disable, 'OPER')
examples.add('urlinfo-disable', 'disable urlinfo in the channel',
             'urlinfo-disable')
Пример #39
0
    else: bot.say(ievent.channel, txt, event=ievent)

## koffie command

def handle_koffie(bot, ievent):
    """ arguments: [<nick>] - get/give a coffee """
    rand = random.randint(0,len(koffie)-1)
    try:
        input = ievent.args[0]
        nick = '%s' % input
    except:
        if len('%s') >= 0: nick = ievent.nick
    do(bot, ievent, koffie[rand] + " " + nick)

cmnds.add('koffie', handle_koffie, 'USER')
examples.add('koffie', 'get a koffie quote', 'koffie')

## thee command

def handle_thee(bot, ievent):
    """ arguments: [<nick>] - get/give a thee """
    rand = random.randint(0,len(thee)-1)
    try:
        input = ievent.args[0]
        nick = '%s' % input
    except:
        if len('%s') >= 0: nick = ievent.nick
    do(bot, ievent, thee[rand] + " " + nick)

cmnds.add('thee', handle_thee, 'USER')
examples.add('thee', 'get an thee', 'thee')
Пример #40
0
        else: r.append("%s (%s)" % (url, count))
    first.extend(r)
    return first

## search command

def handle_search(bot, event):
    if not event.options: event.makeoptions()
    all = event.options.all
    res = []
    target = event.args
    if not target: event.missing("<search words seperated by space>") ; return
    coll = PersistCollection(getdatadir() + os.sep + 'spider' + os.sep + "data")
    files = coll.filenames(target)
    if files:
        for f in files:
            try: res.append(Persist(f).data.url)
            except AttributeError, ex: continue
    objs = coll.search('txt', event.rest)
    if not objs: objs = coll.objects().values()
    stats = makestats(objs, target, res)
    urls = stats_response(stats, target)
    res.extend(urls)
    if res:
        if len(res) < 4 or all: event.reply("found %s urls: " % len(res), res, dot=" -or- ")
        else: event.reply("found %s urls, use --all for more: " % len(res), res[:3], dot=" -or- ")
    else: event.reply("no urls found")

cmnds.add("search", handle_search, ["OPER", "USER", "GUEST"])
examples.add("search", "search scanned sites by the spider", "search license")
Пример #41
0
""" data dumper commands. """

## jsb imports

from jsb.lib.commands import cmnds
from jsb.lib.examples import examples

## data-event command

def handle_dataevent(bot, event):
    """ dump event to json. """
    event.reply(event.tojson())

cmnds.add("data-event", handle_dataevent, "OPER")
examples.add('data-event', 'dump event data', 'data-event')

## data-chan command

def handle_datachan(bot, event):
    """ dump channel data to json. """
    event.reply(event.chan.data.tojson())

cmnds.add("data-chan", handle_datachan, "OPER")
examples.add('data-chan', 'dump channel data', 'data-chan')

## data-bot command

def handle_databot(bot, event):
    """ dump bot as json dict. """
    event.reply(bot.tojson())
Пример #42
0
# jsb/plugs/core/count.py
#
#

""" count number of items in result queue. """

## jsb imports

from jsb.lib.commands import cmnds
from jsb.utils.generic import waitforqueue
from jsb.lib.examples import examples

## basic imports

import time

## count command

def handle_count(bot, ievent):
    """ no arguments - show nr of elements in result list .. use this command in a pipeline. """
    #if ievent.prev: ievent.prev.wait()
    a = ievent.inqueue
    size = len(a)
    ievent.reply(size)

cmnds.add('count', handle_count, ['OPER', 'USER', 'GUEST'])
examples.add('count', 'count nr of items', 'list ! count')
Пример #43
0
        return
    url = event.args[0]
    try:
        depth = int(event.args[1])
    except ValueError:
        event.reply("depth need to be an integer")
        return
    except IndexError:
        depth = 3
    spider = Spider(url)
    if not spider in running: running.append(spider)
    thr = spider.start()
    event.reply("calling fetcher on %s" % time.ctime(spider.sTime))
    spider.put(5, event, url, depth, 9)


cmnds.add("spider", handle_spider, "OPER", threaded="backend")
examples.add("spider", "run the spider on a site.",
             "spider http://jsonbot.org/handbook")


def handle_spiderstop(bot, event):
    r = len(running)
    for spider in running:
        spider.stop()
    event.reply("stopped %s spiders" % r)


cmnds.add("spider-stop", handle_spiderstop, "OPER")
examples.add("spider-stop", "stop running spiders", "spider-stop")
Пример #44
0
""" do a tour of the bot. """

eventlist = ["!welcome", "JSONBOT provides functionality through the use of plugins, you can use the !list comamnd to see what plugins are available =>", "!list"]

## jsb imports

from jsb.lib.commands import cmnds
from jsb.lib.examples import examples

## basic imports

import time

## dotour command

def handle_dotour(bot, event):
    if event.user.state.data.notour: event.reply("the tour is disabled for %s" % event.userhost) ; return
    event.reply("will say something every 5 seconds. you can disable this tour by typing !set notour 1")
    time.sleep(5)
    for txt in eventlist:
        if event.user.state.data.notour: break 
        if txt.startswith("!"):
            e = bot.make_event(event.userhost, event.channel, txt[1:], 0, event)
            e.execute()
        else: event.reply(txt)
        time.sleep(5)
    event.done()

cmnds.add("tour", handle_dotour, ["OPER", "USER", "GUEST"], threaded=True)
examples.add("tour", "show a tour of the bot", "tour")
Пример #45
0
               'what':    'entrando na sala %s' % ievent.channel,
               }

  
    def size(self):
        return len(self.data.keys())

## init

seen = Seen()

## callbacks and commands register

callbacks.add('PRIVMSG', seen.privmsgcb)
callbacks.add('JOIN', seen.joincb)
callbacks.add('PART', seen.partcb)
callbacks.add('QUIT', seen.quitcb)
#callbacks.add('Presence', seen.xmppcb)
cmnds.add('seen', seen.handle_seen, ['USER', 'GUEST'])
examples.add('seen', 'show last spoken txt of <nikc>', 'seen dunker')

## shutdown

def shutdown():
    seen.save()

## size

def size():
    return seen.size()
Пример #46
0
    except urllib2.HTTPError, e: logging.warn('tinyurl - %s - HTTP error: %s' % (url, str(e))) ; return
    except Exception, ex:
        if "DownloadError" in str(ex): logging.warn('tinyurl - %s - DownloadError: %s' % (url, str(e)))
        else: handle_exception()
        return
    urls = []
    for line in res:
        if line.startswith('<blockquote><b>'): urls.append(striphtml(line.strip()).split('[Open')[0])
    if len(urls) == 3: urls.pop(0)
    set(url, json.dumps(urls), namespace='tinyurl')
    return urls

def handle_tinyurl(bot, ievent):
    """ get tinyurl from provided url. """
    if not ievent.rest and (not urlcache.has_key(bot.name) or not urlcache[bot.name].has_key(ievent.target)):
        ievent.missing('<url>')
        return
    elif not ievent.rest: url = urlcache[bot.name][ievent.target]
    else: url = ievent.rest
    url = valid_url(url)
    if not url: ievent.reply('invalid or bad URL') ; return
    tinyurl = get_tinyurl(url)
    if tinyurl: ievent.reply(' .. '.join(tinyurl))
    else: ievent.reply('failed to create tinyurl')

cmnds.add('tinyurl', handle_tinyurl, ['USER', 'GUEST'], threaded=True)
examples.add('tinyurl', 'show a tinyurl', 'tinyurl http://jsonbot.googlecode.com')

def init():
    plugcfg.save()
Пример #47
0
    if not listname or not item:
        ievent.missing("<listname> [',' <item>]")
        return
    ok = 0
    try:
        ok = addtolist(username, listname, item)
    except Exception, ex:
        handle_exception()
        ievent.reply('ERROR: %s' % str(ex))
        return
    if ok: ievent.reply('%s added to %s list' % (item, listname))
    else: ievent.reply('add failed')


cmnds.add('lists', handle_lists, 'USER')
examples.add('lists', "show content of list or add item to list",
             '1) lists bla 2) lists bla, mekker')

## lists-del command


def handle_listsdel(bot, ievent):
    """ list-del <listname> ',' <listofnrs> .. remove items with indexnr from list """
    if not ievent.rest:
        ievent.missing('<listofnrs>')
        return
    try:
        nrs = []
        for i in ievent.rest.split():
            nrs.append(int(i))
    except ValueError:
        ievent.reply('%s is not an integer' % i)
Пример #48
0
from jsb.lib.examples import examples
from jsb.lib.callbacks import callbacks, first_callbacks, last_callbacks

## basic imports

import logging

## echo-callback

def echopre(bot, event):
    """ test whether we should echo. """
    if event.how != "background" and bot.type in ["tornado", "web"] and not event.forwarded and not event.cbtype == "OUTPUT": return True
    return False

def echocb(bot, event):
    """ do the echo. """
    bot.outnocb(event.channel, event.txt, event=event)

#first_callbacks.add("TORNADO", echocb, echopre)
#first_callbacks.add("DISPATCH", echocb, echopre)

## echo command

def handle_echo(bot, event):
    """ argumetnts: <txt> - echo txt to channel. """
    if event.how != "background" and not event.isremote():
        if not event.isdcc: bot.saynocb(event.channel, u"%s" % event.rest, event=event)
            
cmnds.add("echo", handle_echo, ['OPER', 'USER'])
examples.add("echo", "echo input", "echo yoooo dudes")
Пример #49
0
    """ arguments: [<item>] - show shop list or add <item> """
    if len(ievent.args) != 0: handle_shop2(bot, ievent) ; return
    if ievent.user.state.data.shops: sayshop(bot, ievent, ievent.user.state.data.shops)
    else: ievent.reply("no shops")

def handle_shop2(bot, ievent):
    """ add items to shop list """
    if not ievent.rest: ievent.missing('<shopitem>') ; return
    else: what = ievent.rest
    if not ievent.user.state.data.shops: ievent.user.state.data.shops = []
    ievent.user.state.data.shops.append(what)
    ievent.user.state.save()
    ievent.reply('shop item added')

cmnds.add('shop', handle_shop, ['OPER', 'USER', 'GUEST'])
examples.add('shop', 'show shop items or add a shop item', '1) shop 2) shop bread')

## got command

def handle_got(bot, ievent):
    """ arguments: <list of shop nrs> - remove items from shoplist """
    if len(ievent.args) == 0: ievent.missing('<list of nrs>') ; return
    try:
        nrs = []
        for i in ievent.args: nrs.append(int(i))
    except ValueError: ievent.reply('%s is not an integer' % i) ; return
    try: shop = ievent.user.state.data.shops
    except KeyError: ievent.reply('nothing to shop ;]') ; return
    if not shop: ievent.reply("nothing to shop ;]") ; return
    nrs.sort()
    nrs.reverse()
Пример #50
0
        return
    if "@" in event.rest:
        forward.data.outs[event.rest] = event.user.data.name
        forward.save()
        if not event.rest in event.chan.data.forwards:
            event.chan.data.forwards.append(event.rest)
    else:
        event.reply("arguments must be a JID (Jabber ID).")
        return
    if event.rest:
        event.chan.save()
        event.done()


cmnds.add("forward-add", handle_forwardadd, "OPER")
examples.add("forward-add", "add a bot JID to forward to", "forward-add [email protected]")

## forward-del command


def handle_forwarddel(bot, event):
    """ arguments: <bot JID> - delete a forward. """
    if not event.rest:
        event.missing("<bot JID>")
        return
    try:
        del forward.data.outs[event.rest]
    except KeyError:
        event.reply("no forward out called %s" % event.rest)
        return
    forward.save()
Пример #51
0
    try:
        nr = int(event.rest)
    except ValueError:
        nr = None
    if bot.type == "irc": printto = event.nick
    else: printto = event.userhost
    if event.msg and bot.type == "irc": target = event.nick
    else: target = event.channel
    target = "%s-%s" % (bot.cfg.name, target)
    res = outcache.copy(target)
    if res:
        nr = nr or len(res)
        event.reply("sending %s lines from %s to %s" % (nr, target, printto))
        if bot.type in ["xmpp", "sxmpp"]:
            bot.saynocb(printto,
                        "lines from %s" % target,
                        res,
                        event=event,
                        showall=True)
        else:
            for i in res:
                bot.outnocb(printto, i, event=event, showall=True)
    else:
        event.reply("no data in outputcache of %s (%s)" %
                    (event.channel, bot.cfg.name))


cmnds.add("all", handle_all, ["OPER", "USER", "GUEST"], threaded=True)
examples.add("all", "show all of the output cache (in /msg)",
             "1) all 2) all 7")
def handle_dire(bot, event):
    if not event.rest:  event.missing("<text-to-speak>") ; return
    if event.nick not in user_settings.data:
        generate_settings(event.nick)
    v = user_settings.data[event.nick]['voice']
    s = user_settings.data[event.nick]['speed']
    p = user_settings.data[event.nick]['pitch']
    a = str(100)
    k = str(50)
    if '+' in v:
        v = 'fr'+'+'+v.split('+')[-1]
    else:
        v = 'fr'
    speechline = event.rest
    try:
        logging.warning(v+' '+s+' '+p+' '+a+' '+k+' '+speechline)
        conn_send(v+'\t'+s+'\t'+p+'\t'+a+'\t'+k+'\t'+event.nick+'\t'+speechline)
    except:
        event.reply("Cannot connect to host " + HOST + " on port " + str(PORT) )

cmnds.add("espeak", handle_speech, ["SPACE","SPEAK"])
examples.add("espeak", "use espeak to output sound!", "espeak I use espeak.") 
cmnds.add("espreek", handle_spreek, ["SPACE","SPEAK"])
examples.add("espreek", "gebruik espeak om te irritieren!", "espreek Ik gebruik espeak.") 
cmnds.add("esprech", handle_sprech, ["SPACE","SPEAK"])
examples.add("esprech", "benutzen espeak zur Ausgangrauschen!", "esprech Ich benutze espeak.") 
cmnds.add("edire", handle_dire, ["SPACE","SPEAK"])
examples.add("edire", "utilize espeak pour generer du son!", "esprech Je utilise espeak.") 
cmnds.add("espeak-settings", handle_settings, ["SPACE","SPEAK"])
examples.add("espeak-settings", "modify espeak settings", "espeak-settings voice=en+f3") 
Пример #53
0
    if not ttime == None:
        ievent.reply('time detected ' + time.ctime(ttime))
        what = striptime(what)
        alarms = plugs.get("jsb.plugs.common.alarm")
        if alarms:
            alarmnr = alarms.alarms.add(bot.name, ievent.nick, ttime, what)
        else:
            alarmnr = None
        nr = todo.add(name, what, ttime, alarmnr)
    else:
        nr = todo.add(name, what, None)
    ievent.reply('todo item %s added' % nr)


cmnds.add('t', handle_todo, 'USER')
examples.add('t', 'todo [<item>] .. show todo items or add a todo item',
             '1) todo 2) todo program the bot 3) todo 22:00 sleep')

## t-done command


def handle_tododone(bot, ievent):
    """ t-done <listofnrs> .. remove todo items """
    if len(ievent.args) == 0:
        ievent.missing('<list of nrs>')
        return
    try:
        nrs = []
        for i in ievent.args:
            nrs.append(int(i))
    except ValueError:
        ievent.reply('%s is not an integer' % i)
Пример #54
0
callbacks.add('MESSAGE', karmacb, prekarma)
callbacks.add('CONSOLE', karmacb, prekarma)
callbacks.add('TORNADO', karmacb, prekarma)

## karma command

def handle_karma(bot, event):
    """ arguments: <item> - show karma of item. """
    if not event.rest: event.missing("<item>") ; return
    k = event.rest.lower()
    item = KarmaItem(event.channel.lower() + "-" + k)
    if item.data.count: event.reply("karma of %s is %s" % (k, item.data.count))
    else: event.reply("%s doesn't have karma yet." % k)

cmnds.add('karma', handle_karma, ['OPER', 'USER', 'GUEST'])
examples.add('karma', 'show karma', 'karma jsb')

## karma-whyup command

def handle_karmawhyup(bot, event):
    """ arguments: <item> - show reason for karma increase. """
    k = event.rest.lower()
    item = KarmaItem(event.channel + "-" + k)
    if item.data.whyup: event.reply("reasons for karma up are: ", item.data.whyup)
    else: event.reply("no reasons for karmaup of %s known yet" % k)

cmnds.add("karma-whyup", handle_karmawhyup, ['OPER', 'USER', 'GUEST'])
examples.add("karma-whyup", "show why a karma item is upped", "karma-whyup jsb")

## karma-whoup command
Пример #55
0
## jsb imports

from jsb.utils.exception import handle_exception
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples

## basic imports

import sys

## size command


def handle_size(bot, event):
    res = []
    mods = dict(sys.modules)
    for name, mod in mods.iteritems():
        if not 'jsb' in name: continue
        try:
            res.append("<i><%s></i> %s" %
                       (name.split(".")[-1], unicode(getattr(mod, 'size')())))
        except (TypeError, AttributeError):
            continue
        except Exception, ex:
            handle_exception()
    event.reply("sizes in %s modules scanned: " % len(res), res, dot="<br>")


cmnds.add("size", handle_size, "OPER")
examples.add("size", "call size() functions in all available modules", "size")