Example #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
Example #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")
Example #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
Example #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")
Example #5
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')
Example #6
0
            return False
        elif event.channel == "#c-base-bots":
            if "c-beam" in event.txt:
                return True
            else:
                return False
        else:
            return True
        return False
    return False

## cbeam callbacks

def cbeamcb(bot, event):
    event.bind(bot)
    time.sleep(1)
    if event.txt.find('help') != -1:
        event.reply('http://bit.ly/c-beam')
    else:
        event.reply(random.choice(messages))
    return 0

callbacks.add('PRIVMSG', cbeamcb, precbeam)
callbacks.add('MESSAGE', cbeamcb, precbeam)
callbacks.add('CONSOLE', cbeamcb, precbeam)

def handle_cbeam(bot, event):
    event.reply(random.choice(messages))

cmnds.add('c-beam', handle_cbeam, ['GUEST', ])
Example #7
0
    """ 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):
    """ remove a bot from nickserv. """
    if bot.jabber: return
    if len(ievent.args) != 1:
        ievent.missing('<fleetbot name>')
        return
    botname = ievent.args[0]
Example #8
0
    try:
        (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>")
Example #9
0
        event.missing("<bot JID>")
        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
Example #10
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()
Example #11
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')
Example #12
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')
Example #13
0
            'watcher not enabled, use "!%s-cfg watcher-enabled 1" to enable and reload the plugin'
            % 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')
Example #14
0
        ievent.missing('<what>')
        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
Example #15
0
    if not txt: return txt
    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
Example #16
0
    try:
        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:
Example #17
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")
Example #18
0
    global hosts
    random.shuffle(hosts)
    got = ""
    r = None
    logging.warn("error hosts is %s" % str(errorhosts))
    if len(hosts) == len(errorhosts):
        event.reply("no alive server found")
        return
    for h in prio1 + hosts:
        if h in errorhosts: continue
        try:
            r = json.loads(
                getresults(queryurl % (h, urllib.quote_plus(event.rest))))
            if r:
                got = h
                break
        except Exception, ex:
            errorhosts.append(h)
            handle_exception()
            continue
    result = []
    for channel in r['channels']:
        for item in channel['items']:
            result.append("%s - %s (%s)" %
                          (item['title'], item['link'], item['size']))
    if result: event.reply("results from %s: " % got, result, dot=" || ")
    else: event.reply("no result")


cmnds.add("yacy", handle_yacy, ["OPER", "USER"])
Example #19
0
        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" % 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)
Example #20
0
from jsb.lib.persist import Persist
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')
Example #21
0
        return

    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)
Example #22
0
    query = parse_pair(event.rest.strip())
    if not query:
        event.missing("<from> <to> <text>")
        return
#    event.reply(URL % query)
    rawresult = {}
    try:
        rawresult = getjson().loads(geturl2(URL % query))
    except:
        event.reply("Query to Google failed")
        return


# debug
#     rawresult = {"responseData": {"translatedText":"test"}, "responseDetails": None, "responseStatus": 201}
# logging.warn(URL % query)
# logging.warn(rawresult)
    if rawresult['responseStatus'] != 200:
        event.reply("Error in the query: ", rawresult)
        return
    if 'responseData' in rawresult:
        if 'translatedText' in rawresult['responseData']:
            translation = rawresult['responseData']['translatedText']
            event.reply(translation)
        else:
            event.reply("No text available")
    else:
        event.reply("Something is wrong, probably the API changed")

cmnds.add("translate", handle_translate, ["OPER", "USER", "GUEST"])
Example #23
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)' %
Example #24
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")
Example #25
0
    except Queue.Empty: pass
    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:
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") 
Example #27
0
File: gadget.py Project: code2u/jsb
        from waveapi import element
        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")
Example #28
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')
Example #29
0
        for i in state['urls'][bot.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, ['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():
Example #30
0
## jsb imports

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
Example #31
0
        what = ievent.rest
    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)
Example #32
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')
Example #33
0
    if bot.type == "irc" and not bot.allowall: bot.action(ievent.channel, txt, event=ievent)
    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')
Example #34
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
Example #35
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. """
Example #36
0
## set command


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)
Example #37
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")
Example #38
0
callbacks.add('CONSOLE', catchUrls, catchHasUrls, threaded=True)
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',
Example #39
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()
Example #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")
Example #41
0
    item = item.strip()
    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))
Example #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')
Example #43
0
# -*- coding: utf-8 -*-

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

import os


def handle_ddate(bot, ievent):
        message = os.system('ddate')
        #bot.say('#c-base', message)
        ievent.reply(message)


cmnds.add("ddate", handle_ddate, ['OPER', 'USER', 'GUEST'])
Example #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")
Example #45
0
def handle_shop(bot, ievent):
    """ 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()
Example #46
0
first_callbacks.add('WEB', watchcallback, prewatchcallback)
first_callbacks.add('DISPATCH', watchcallback, prewatchcallback)
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
Example #47
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")
Example #48
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")
 
Example #49
0
    nr = 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))
Example #50
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):
Example #51
0
def handle_c_out(bot, ievent):
    """ text to speech synthesis. """
    if not ievent.args:
        sound = random.choice(server.sounds())
    else:
        sound = ievent.rest
    try:
        ievent.reply(server.play(sound))
        #f = open(c_outlog, 'a')
        #f.write('%s: %s: %s (%s)\n' % (datetime.datetime.now(), getuser(ievent), sound))
        #f.close()
    except:
        ievent.reply(str(sys.exc_info()[0]))

cmnds.add('c_out', handle_c_out, ['USER', 'GUEST'])

def handle_c_out_list(bot, ievent):
    return ievent.reply(" ".join(server.sounds()['result']))

cmnds.add('c_out-list', handle_c_out_list, ['USER', 'GUEST'])

def tail(f, n, offset=0):
    """Reads a n lines from f with an offset of offset lines."""
    avg_line_length = 74
    to_read = n + offset
    while 1:
        try:
            f.seek(-(avg_line_length * to_read), 2)
        except IOError:
            # woops.  apparently file is smaller than what we want
Example #52
0
File: tail.py Project: 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')
Example #53
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")
Example #54
0
    if not bot.jabber and not checktopicmode(bot, ievent): return
    result = bot.gettopic(ievent.channel)
    what = result[0]
    #what += " | %s" % ievent.rest
    # remopve old events
    what = re.sub(r' \| heute an bord\: .* \|', ' |', what)
    what = re.sub(r' \| heute an bord\: .*', '', what)
    events = server.events()['result']
    if len(events) > 0:
        what += " | heute an bord: %s" % ", ".join(events) 
    if what != result[0]:
        bot.settopic(ievent.channel, what)
    else:
        ievent.reply('das topic ist bereits auf dem aktuellen stand.')

cmnds.add('event-topic', handle_event_topic, ['OPER'])

def settopic(bot, channel):
    """ event-topic .. add todays events to the topic """
    result = bot.gettopic(channel)
    if not result: return 'topic connte nicht ausgelesen werden'
    what = result[0]
    what = re.sub(r' \| heute an bord\: .* \|', ' |', what)
    what = re.sub(r' \| heute an bord\: .*', '', what)
    events = server.events()['result']
    if len(events) > 0:
        what += " | heute an bord: %s" % ", ".join(events) 
    if what != result[0]:
        bot.settopic(channel, what)
    else:
        return 'das topic ist bereits auf dem aktuellen stand.'
Example #55
0
        state.data.names[gid] = name
        target = [bot.cfg.name, event.channel]
        if not state.data.ids.has_key(gid): state.data.ids[gid] = []
        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:
Example #56
0
callbacks.add('PRIVMSG', karmacb, prekarma)
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
Example #57
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")