code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# jsb/gae/xmpp/bot.py
#
#
""" XMPP bot. """
## jsb imports
from jsb.lib.botbase import BotBase
from jsb.drivers.xmpp.presence import Presence
from jsb.utils.generic import strippedtxt
## xmpp import
from jsb.contrib.xmlstream import NodeBuilder, XMLescape, XMLunescape
## basic imports
import types
import logging
## XMPPBot class
class XMPPBot(BotBase):
""" XMPPBot just inherits from BotBase for now. """
def __init__(self, cfg=None, users=None, plugs=None, botname="gae-xmpp", *args, **kwargs):
BotBase.__init__(self, cfg, users, plugs, botname, *args, **kwargs)
assert self.cfg
self.isgae = True
self.type = "xmpp"
def out(self, jids, txt, how="msg", event=None, origin=None, groupchat=None, *args, **kwargs):
""" output xmpp message. """
if type(jids) != types.ListType: jids = [jids, ]
self.outnocb(jids, txt, how, event, origin)
for jid in jids:
self.outmonitor(self.cfg.nick, jid, txt)
def outnocb(self, jids, txt, how="msg", event=None, origin=None, from_jid=None, message_type=None, raw_xml=False, groupchat=False, *args, **kwargs):
""" output xmpp message. """
from google.appengine.api import xmpp
if not message_type: message_type = xmpp.MESSAGE_TYPE_CHAT
if type(jids) != types.ListType: jids = [jids, ]
txt = self.normalize(txt)
logging.info(u"%s - xmpp - out - %s - %s" % (self.cfg.name, unicode(jids), txt))
xmpp.send_message(jids, txt, from_jid=from_jid, message_type=message_type, raw_xml=raw_xml)
def invite(self, jid):
""" send an invite to another jabber user. """
from google.appengine.api import xmpp
xmpp.send_invite(jid)
def normalize(self, what):
""" remove markup code as its not yet supported by our GAE XMPP bot. """
what = strippedtxt(unicode(what))
what = what.replace("<b>", "")
what = what.replace("</b>", "")
what = what.replace("<b>", "")
what = what.replace("</b>", "")
what = what.replace("<i>", "")
what = what.replace("</i>", "")
what = what.replace("<i>", "")
what = what.replace("</i>", "")
return what
| Python |
# jsb common plugins
#
#
""" this package contains all the plugins common to all drivers. """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb common plugins
#
#
""" this package contains all the plugins common to all drivers. """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb common plugins
#
#
""" this package contains all the plugins common to all drivers. """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb common plugins
#
#
""" this package contains all the plugins common to all drivers. """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb/plugs/socket/dns.py
#
#
""" do a fqdn loopup. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
from socket import gethostbyname
from socket import getfqdn
import re
## dns command
def handle_dns(bot, event):
""" do a dns lookup. """
if not event.rest: event.missing("<ip> or <hostname>") ; return
query = event.rest.strip()
ippattern = re.match(r"^([0-9]{1,3}\.){3}[0-9]{1,3}$", query)
hostpattern = re.match(r"(\w+://)?(?P<hostname>\S+\.\w+)", query)
if ippattern:
try:
answer = getfqdn(ippattern.group(0))
event.reply("%(hostname)s is %(answer)s" % {"hostname": query, "answer": answer})
except: event.reply("Couldn't lookup ip")
elif hostpattern:
try:
answer = gethostbyname(hostpattern.group('hostname'))
event.reply("%(ip)s is %(answer)s" % {"ip": query, "answer": answer})
except: event.reply("Couldn't look up the hostname")
else: return
cmnds.add("dns", handle_dns, ["OPER", "USER", "GUEST"])
examples.add("dns", "resolve the ip or the hostname", "dns google.com")
| Python |
# jsb/plugs/socket/chatlog.py
#
#
"""
log irc channels to [hour:min] <nick> txt format, only
logging to files is supported right now.
"""
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.callbacks import callbacks, remote_callbacks, last_callbacks, first_callbacks
from jsb.lib.persistconfig import PersistConfig
from jsb.utils.locking import lockdec
from jsb.utils.timeutils import hourmin
from jsb.lib.examples import examples
from jsb.utils.exception import handle_exception
from jsb.utils.lazydict import LazyDict
from jsb.lib.datadir import getdatadir
from jsb.utils.name import stripname
from jsb.utils.url import striphtml
from jsb.utils.format import formatevent, format_opt
## basic imports
import time
import os
import logging
import thread
from os import path
from datetime import datetime
## locks
outlock = thread.allocate_lock()
outlocked = lockdec(outlock)
## defines
cfg = PersistConfig()
cfg.define('channels', [])
cfg.define('format', 'log')
cfg.define('basepath', getdatadir())
cfg.define('nologprefix', '[nolog]')
cfg.define('nologmsg', '-= THIS MESSAGE NOT LOGGED =-')
cfg.define('backend', 'log')
logfiles = {}
backends = {}
stopped = False
db = None
eventstolog = ["OUTPUT", "PRIVMSG", "CONSOLE", "PART", "JOIN", "QUIT", "PRESENCE", "MESSAGE", "NOTICE", "MODE", "TOPIC", "KICK", "CONVORE"]
## logging part
# BHJTW 21-02-2011 revamped to work with standard python logger
loggers = {}
try: LOGDIR = os.path.expanduser("~") + os.sep + ".jsb" + os.sep + "chatlogs"
except ImportError: LOGDIR = os.getcwd() + os.sep + ".jsb" + os.sep + "chatlogs"
try:
ddir = os.sep.join(LOGDIR.split(os.sep)[:-1])
if not os.path.isdir(ddir): os.mkdir(ddir)
except: pass
try:
if not os.path.isdir(LOGDIR): os.mkdir(LOGDIR)
except: pass
format = "%(message)s"
def timestr(dt):
return dt.strftime(format_opt('timestamp_format'))
## enablelogging function
def enablelogging(botname, channel):
""" set loglevel to level_name. """
global loggers
logging.warn("chatlog - enabling on (%s,%s)" % (botname, channel))
channel = stripname(channel)
logname = "%s_%s" % (botname, channel)
#if logname in loggers: logging.warn("chatlog - there is already a logger for %s" % logname) ; return
try:
filehandler = logging.handlers.TimedRotatingFileHandler(LOGDIR + os.sep + logname + ".log", 'midnight')
formatter = logging.Formatter(format)
filehandler.setFormatter(formatter)
except IOError:
filehandler = None
chatlogger = logging.getLoggerClass()(logname)
chatlogger.setLevel(logging.INFO)
if chatlogger.handlers:
for handler in chatlogger.handlers: chatlogger.removeHandler(handler)
if filehandler: chatlogger.addHandler(filehandler) ; logging.info("%s - logging enabled on %s" % (botname, channel))
else: logging.warn("chatlog - no file handler found - not enabling logging.")
global lastlogger
lastlogger = chatlogger
loggers[logname] = lastlogger
## do tha actual logging
@outlocked
def write(m):
"""
m is a dict with the following properties:
datetime
type : (comment, nick, topic etc..)
target : (#channel, bot etc..)
txt : actual message
network
"""
backend_name = cfg.get('backend', 'log')
backend = backends.get(backend_name, log_write)
if m.txt.startswith(cfg.get('nologprefix')): m.txt = cfg.get('nologmsg')
backend(m)
def log_write(m):
if stopped: return
logname = "%s_%s" % (m.botname, stripname(m.target))
timestamp = timestr(m.datetime)
m.type = m.type.upper()
line = '%(timestamp)s%(separator)s%(txt)s\n'%({
'timestamp': timestamp,
'separator': format_opt('separator'),
'txt': m.txt,
'type': m.type
})
global loggers
try: loggers[logname].info(line.strip())
except KeyError: logging.warn("no logger available for channel %s" % logname)
except Exception, ex: handle_exception()
backends['log'] = log_write
## log function
def log(bot, event):
m = formatevent(bot, event, cfg.get("channels"))
if m["txt"]: write(m)
## chatlog precondition
def prechatlogcb(bot, ievent):
"""
Check if event should be logged. QUIT and NICK are not channel
specific, so we will check each channel in log().
"""
if bot.isgae: return False
if not cfg.channels: return False
if not [bot.cfg.name, ievent.channel] in cfg.get('channels'): return False
if not ievent.cbtype in eventstolog: return False
if not ievent.msg: return True
if ievent.cmnd in ('QUIT', 'NICK'): return True
if ievent.cmnd == 'NOTICE':
if [bot.cfg.name, ievent.arguments[0]] in cfg.get('channels'): return True
return False
## chatlog callbacks
def chatlogcb(bot, ievent):
log(bot, ievent)
## plugin-start
def init():
global stopped
stopped = False
global loggers
for (botname, channel) in cfg.get("channels"):
enablelogging(botname, channel)
callbacks.add("PRIVMSG", chatlogcb, prechatlogcb)
callbacks.add("JOIN", chatlogcb, prechatlogcb)
callbacks.add("PART", chatlogcb, prechatlogcb)
callbacks.add("NOTICE", chatlogcb, prechatlogcb)
callbacks.add("QUIT", chatlogcb, prechatlogcb)
callbacks.add("NICK", chatlogcb, prechatlogcb)
callbacks.add("PRESENCE", chatlogcb, prechatlogcb)
callbacks.add("MESSAGE", chatlogcb, prechatlogcb)
callbacks.add("CONSOLE", chatlogcb, prechatlogcb)
callbacks.add("CONVORE", chatlogcb, prechatlogcb)
first_callbacks.add("OUTPUT", chatlogcb, prechatlogcb)
return 1
## plugin-stop
def shutdown():
global stopped
stopped = True
for file in logfiles.values():
file.close()
return 1
## chatlog-on command
def handle_chatlogon(bot, ievent):
""" enable chatlog. """
chan = ievent.channel
enablelogging(bot.cfg.name, chan)
if [bot.cfg.name, chan] not in cfg.get('channels'):
cfg['channels'].append([bot.cfg.name, chan])
cfg.save()
ievent.reply('chatlog enabled on (%s,%s)' % (bot.cfg.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.cfg.name, ievent.channel]) ; cfg.save()
except ValueError: ievent.reply('chatlog is not enabled in (%s,%s)' % (bot.cfg.name, ievent.channel)) ; return
try: del loggers["%s-%s" % (bot.cfg.name, stripname(ievent.channel))]
except KeyError: pass
except Exception, ex: handle_exception()
ievent.reply('chatlog disabled on (%s,%s)' % (bot.cfg.name, ievent.channel))
cmnds.add('chatlog-off', handle_chatlogoff, 'OPER')
examples.add('chatlog-off', 'disable chatlog on <channel> or the channel the commands is given in', '1) chatlog-off 2) chatlog-off #dunkbots')
| Python |
# jsb/plugs/socket/kickban.py
#
#
""" kickban functionality for IRC. """
## jsb imports
from jsb.utils.generic import getwho
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.callbacks import callbacks
## basic imports
import Queue
import time
import logging
## defines
bans = {}
cachetime = 300
timeout = 10
## callbacks
def handle_367(bot, ievent):
logging.debug('kickban - 367 - %s' % str(ievent))
channel = ievent.arguments[1].lower()
if not bot.cfg.name in bans or not channel in bans[bot.cfg.name]:
return # not requested by this plugin
bans[bot.cfg.name][channel].append(ievent.txt.split()[0])
def handle_mode(bot, ievent):
logging.debug('kick-ban - mode - %s' % ievent.dump())
# [18 Jan 2008 13:41:29] (mode) cmnd=MODE prefix=maze!wijnand@2833335b.cc9dd561.com.hmsk postfix=#eth0-test +b *!*@je.moeder.ook arguments=[u'#eth0-test', u'+b', u'*!*@je.moeder.ook'] nick=maze user=wijnand userhost=wijnand@2833335b.cc9dd561.com.hmsk channel=#eth0-test txt= command= args=[] rest= speed=5 options={}
callbacks.add('367', handle_367)
callbacks.add('MODE', handle_mode)
## functions
def get_bans(bot, channel):
# :ironforge.sorcery.net 367 basla #eth0 *!*@71174af5.e1d1a3cf.net.hmsk eth0!eth0@62.212.76.127 1200657224
# :ironforge.sorcery.net 367 basla #eth0 *!*@6ca5f0a3.14055a38.89.123.imsk eth0!eth0@62.212.76.127 1200238584
# :ironforge.sorcery.net 368 basla #eth0 :End of Channel Ban List
channel = channel.lower()
if not bot.cfg.name in bans:
bans[bot.cfg.name] = {}
bans[bot.cfg.name][channel] = []
queue368 = Queue.Queue()
if not bot.wait:
return
bot.wait.register('368', channel, queue368)
bot.sendraw('MODE %s +b' % (channel, ))
# wait for End of Channel Ban List
try:
res = queue368.get(1, timeout)
except Queue.Empty:
return None
return bans[bot.name][channel]
def get_bothost(bot):
return getwho(bot, bot.cfg.nick).split('@')[-1].lower()
## ban-list command
def handle_ban_list(bot, ievent):
""" 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, nr=True)
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):
""" remove a ban. """
channel = ievent.channel.lower()
if len(ievent.args) != 1 or not ievent.args[0].isdigit(): ievent.missing('<banlist index>') ; 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]
banslist.remove(unban)
bot.sendraw('MODE %s -b %s' % (channel, unban))
ievent.reply('unbanned %s' % (unban, ))
cmnds.add('ban-remove', handle_ban_remove, 'OPER', threaded=True)
examples.add('ban-remove', 'removes a host from the ban list', 'ban-remove 1')
## ban-add command
def handle_ban_add(bot, ievent):
""" add a ban. """
if not ievent.args: ievent.missing('<nick>') ; return
if bot.cfg.nick and ievent.args[0].lower() == bot.cfg.nick.lower():
ievent.reply('not going to ban myself')
return
userhost = getwho(bot, ievent.args[0])
if userhost:
host = userhost.split('@')[-1].lower()
if host == get_bothost(bot): ievent.reply('not going to ban myself') ; return
bot.sendraw('MODE %s +b *!*@%s' % (ievent.channel, host))
ievent.reply('banned %s' % (host, ))
else: ievent.reply('can not get userhost of %s' % ievent.args[0])
cmnds.add('ban-add', handle_ban_add, 'OPER')
examples.add('ban-add', 'adds a host to the ban list', 'ban-add *!*@lamers.are.us')
## ban-kickban command
def handle_kickban_add(bot, ievent):
""" add a kickban. """
if not ievent.args: ievent.missing('<nick> [<reason>]') ; return
if bot.cfg.nick and ievent.args[0].lower() == bot.cfg.nick.lower():
ievent.reply('not going to kickban myself')
return
userhost = getwho(bot, ievent.args[0])
reason = len(ievent.args) > 1 and ' '.join(ievent.args[1:]) or 'Permban requested, bye'
if userhost:
host = userhost.split('@')[-1].lower()
if host == get_bothost(bot): ievent.reply('not going to kickban myself') ; return
bot.sendraw('MODE %s +b *!*@%s' % (ievent.channel, host))
bot.sendraw('KICK %s %s :%s' % (ievent.channel, ievent.args[0], reason))
else: ievent.reply('can not get userhost of %s' % ievent.args[0])
cmnds.add('ban-kickban', handle_kickban_add, 'OPER')
examples.add('ban-kickban', 'kickbans the given nick', 'kickban Lam0r Get out of here')
| Python |
# jsb/plugs/socket/udp.py
#
#
"""
the bot has the capability to listen for udp packets which it will use
to /msg a given nick or channel.
1) setup
* do !reload udp to enable the udp plugin
* call !udp-cfgsave to generate a config file in gozerdata/plugs/udp/config
* edit this file .. esp. look at the udpallowednicks list
* run ./bin/jsb-udp -s to generate clientside config file "udp-send"
* edit this file
* test with:
::
echo "YOOO" | ./bin/jsb-udp
2) limiter
on IRC the bot's /msg to a user/channel are limited to 1 per 3 seconds so the
bot will not excessflood on the server. you can use partyudp if you need no
delay between sent messages, this will use dcc chat to deliver the message.
on jabber bots there is no delay
"""
## jsb imports
from jsb.lib.fleet import fleet
from jsb.utils.exception import handle_exception
from jsb.utils.generic import strippedtxt
from jsb.utils.locking import lockdec
from jsb.lib.partyline import partyline
from jsb.lib.threads import start_new_thread
from jsb.contrib.rijndael import rijndael
from jsb.lib.persistconfig import PersistConfig
from jsb.lib.callbacks import first_callbacks
## basic imports
import socket
import re
import time
import Queue
import logging
# defines
udplistener = None
cfg = PersistConfig()
cfg.define('udp', 0) # set to 0 to disnable
cfg.define('udpparty', 0)
cfg.define('udpipv6', 0)
cfg.define('udpmasks', ['192.168*', ])
cfg.define('udphost', "localhost")
cfg.define('udpport', 5500)
cfg.define('udpallow', ["127.0.0.1", ])
cfg.define('udpallowednicks', ["#dunkbots", "#jsb", "dunk_"])
cfg.define('udppassword', "mekker", exposed=False)
cfg.define('udpseed', "blablablablablaz", exposed=False) # needs to be 16 chars wide
cfg.define('udpstrip', 1) # strip all chars < char(32)
cfg.define('udpsleep', 0) # sleep in sendloop .. can be used to delay pack
cfg.define('udpdblog', 0)
cfg.define('udpbots', [cfg['udpbot'] or 'default-irc', ])
## functions
def _inmask(addr):
""" check if addr matches a mask. """
if not cfg['udpmasks']:
return False
for i in cfg['udpmasks']:
i = i.replace('*', '.*')
if re.match(i, addr):
return True
## Udplistener class
class Udplistener(object):
""" listen for udp messages and relay them to channel/nick/JID. """
def __init__(self):
self.outqueue = Queue.Queue()
self.queue = Queue.Queue()
self.stop = 0
if cfg['udpipv6']: self.sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
else: self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except: pass
self.sock.setblocking(1)
self.sock.settimeout(1)
self.loggers = []
def _outloop(self):
""" loop controling the rate of outputted messages. """
logging.info('udp - starting outloop')
while not self.stop:
(printto, txt) = self.outqueue.get()
if self.stop: return
self.dosay(printto, txt)
logging.info('udp - stopping outloop')
def _handleloop(self):
""" handle incoming udp data. """
while not self.stop:
(input, addr) = self.queue.get()
if not input or not addr: continue
if self.stop: break
self.handle(input, addr)
if cfg['udpsleep']: time.sleep(cfg['udpsleep'] or 0.01)
logging.info('udp - shutting down udplistener')
def _listen(self):
""" listen for udp messages .. /msg via bot"""
if not cfg['udp']: return
for botname in cfg['udpbots']:
if not fleet.byname(botname): logging.info("udp - can't find %s bot" % botname)
try:
fleet.startok.wait(5)
self.sock.bind((cfg['udphost'], cfg['udpport']))
logging.warn('udp listening on %s %s' % (cfg['udphost'], cfg['udpport']))
self.stop = 0
except IOError:
handle_exception()
self.sock = None
self.stop = 1
return
# loop on listening udp socket
while not self.stop:
try: input, addr = self.sock.recvfrom(64000)
except socket.timeout: continue
except Exception, ex:
try: (errno, errstr) = ex
except ValueError: errno = 0 ; errstr = str(ex)
if errno == 4: logging.warn("udp - %s - %s" % (self.name, str(ex))) ; break
if errno == 35: continue
else: handle_exception() ; break
if self.stop: break
self.queue.put((input, addr))
logging.info('udp - shutting down main loop')
def handle(self, input, addr):
""" handle an incoming udp packet. """
if cfg['udpseed']:
data = ""
for i in range(len(input)/16):
try: data += crypt.decrypt(input[i*16:i*16+16])
except Exception, ex:
logging.warn("udp - can't decrypt: %s" % str(ex))
data = input
break
else: data = input
if cfg['udpstrip']: data = strippedtxt(data)
# check if udp is enabled and source ip is in udpallow list
if cfg['udp'] and (addr[0] in cfg['udpallow'] or _inmask(addr[0])):
# get printto and passwd data
header = re.search('(\S+) (\S+) (.*)', data)
if header:
# check password
if header.group(1) == cfg['udppassword']:
printto = header.group(2) # is the nick/channel
# check if printto is in allowednicks
if not printto in cfg['udpallowednicks']:
logging.warn("udp - udp denied %s" % printto )
return
logging.debug('udp - ' + str(addr[0]) + " - udp allowed")
text = header.group(3) # is the text
self.say(printto, text)
else: logging.warn("udp - can't match udppasswd from " + str(addr))
else: logging.warn("udp - can't match udp from " + str(addr[0]))
else: logging.warn('udp - denied udp from ' + str(addr[0]))
def say(self, printto, txt):
""" send txt to printto. """
self.outqueue.put((printto, txt))
def dosay(self, printto, txt):
""" send txt to printto .. do some checks. """
if cfg['udpparty'] and partyline.is_on(printto): partyline.say_nick(printto, txt) ; return
if not cfg['udpbots']: bots = [cfg['udpbot'], ]
else: bots = cfg['udpbots']
for botname in bots:
bot = fleet.byname(botname)
if not bot: logging.warn("udp - can't find %s bot in fleet" % botname) ; continue
bot.connectok.wait()
bot.say(printto, txt)
for i in self.loggers: i.log(printto, txt)
## init
# the udplistener object
if cfg['udp']: udplistener = Udplistener()
# initialize crypt object if udpseed is set in config
if cfg['udp'] and cfg['udpseed']: crypt = rijndael(cfg['udpseed'])
def init():
""" init the udp plugin. """
if cfg['udp']:
global udplistener
start_new_thread(udplistener._listen, ())
start_new_thread(udplistener._handleloop, ())
start_new_thread(udplistener._outloop, ())
return 1
## shutdown
def shutdown():
""" shutdown the udp plugin. """
global udplistener
if udplistener:
udplistener.stop = 1
udplistener.outqueue.put_nowait((None, None))
udplistener.queue.put_nowait((None, None))
return 1
## start
def onSTART(bot, event):
pass
first_callbacks.add("START", onSTART)
| Python |
# jsb/plugs/socket/mpd.py
#
#
# interact with (your) Music Player Daemon
# (c) Wijnand 'tehmaze' Modderman - http://tehmaze.com
# BSD License
#
# CHANGELOG
# 2011-02-20
# * sMiLe - changed methods to be similar to the mpc commands
# 2011-02-13
# * sMiLe - added several new functions
# 2011-01-16
# * BHJTW - adapted to jsonbot
# 2008-10-30
# * fixed "Now playing" when having a password on MPD
# 2007-11-16
# * added watcher support
# * added formatting options ('song-status')
# * added more precision to duration calculation
# 2007-11-10
# * initial version
#
# REFERENCES
#
# The MPD wiki is a great resource for MPD information, especially:
# * http://mpd.wikia.com/wiki/MusicPlayerDaemonCommands
#
""" music player daemon control. """
__version__ = '2007111601'
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.datadir import getdatadir
from jsb.lib.examples import examples
from jsb.lib.fleet import fleet
from jsb.utils.pdod import Pdod
from jsb.lib.persistconfig import PersistConfig
from jsb.lib.threads import start_new_thread
## basic imports
import os
import socket
import time
## defines
cfg = PersistConfig()
cfg.define('server-host', '127.0.0.1')
cfg.define('server-port', 6600)
cfg.define('server-pass', '')
cfg.define('socket-timeout', 15)
cfg.define('watcher-interval', 10)
cfg.define('watcher-enabled', 0)
cfg.define('song-status', 'now playing: %(artist)s - %(title)s on "%(album)s" (duration: %(time)s)')
## classes
class MPDError(Exception): pass
class MPDDict(dict):
def __getitem__(self, item):
if not dict.has_key(self, item):
return '?'
else:
return dict.__getitem__(self, item)
class MPDWatcher(Pdod):
def __init__(self):
Pdod.__init__(self, os.path.join(getdatadir() + os.sep + 'plugs' + os.sep + 'jsb.plugs.sockets.mpd', 'mpd'))
self.running = False
self.lastsong = -1
def add(self, bot, ievent):
if not self.has_key2(bot.cfg.name, ievent.channel):
self.set(bot.cfg.name, ievent.channel, True)
self.save()
def remove(self, bot, ievent):
if self.has_key2(bot.cfg.name, ievent.channel):
del self.data[bot.cfg.name][ievent.channel]
self.save()
def start(self):
self.running = True
start_new_thread(self.watch, ())
def stop(self):
self.running = False
def watch(self):
if not cfg.get('watcher-enabled'):
raise MPDError('watcher not enabled, use "!%s-cfg watcher-enabled 1" to enable' % os.path.basename(__file__)[:-3])
while self.running:
if self.data:
try:
status = MPDDict(mpd('currentsong'))
songid = int(status['id'])
if songid != self.lastsong:
self.lastsong = songid
self.announce(status)
except MPDError:
pass
except KeyError:
pass
time.sleep(cfg.get('watcher-interval'))
def announce(self, status):
if not self.running or not cfg.get('watcher-enabled'):
return
status['time'] = mpd_duration(status['time'])
song = cfg.get('song-status') % status
for name in self.data.keys():
bot = fleet.byname(name)
if bot:
for channel in self.data[name].keys():
bot.say(channel, song)
## init
watcher = MPDWatcher()
if not watcher.data:
watcher = MPDWatcher()
def init():
if cfg.get('watcher-enabled'):
watcher.start()
return 1
def shutdown():
if watcher.running:
watcher.stop()
return 1
## mpd-function
def mpd(command):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(cfg.get('socket-timeout'))
s.connect((cfg.get('server-host'), cfg.get('server-port')))
except socket.error, e:
raise MPDError, 'Failed to connect to server: %s' % str(e)
m = s.makefile('r')
l = m.readline()
if not l.startswith('OK MPD '): s.close() ; raise MPDError, 'Protocol error'
if cfg.get('server-pass') and cfg.get('server-pass') != 'off':
s.send('password %s\n' % cfg.get('server-pass'))
l = m.readline()
if not l.startswith('OK'):
s.close()
raise MPDError, 'Protocol error'
s.send('%s\n' % command)
s.send('close\n')
d = []
while True:
l = m.readline().strip()
if not l or l == 'OK':
break
if ': ' in l:
l = l.split(': ', 1)
l[0] = l[0].lower()
d.append(tuple(l))
s.close()
return d
def mpd_duration(timespec):
try:
timespec = int(timespec)
except ValueError:
return 'unknown'
timestr = ''
m = 60
h = m * 60
d = h * 24
w = d * 7
if timespec > w:
w, timespec = divmod(timespec, w)
timestr = timestr + '%02dw' % w
if timespec > d:
d, timespec = divmod(timespec, d)
timestr = timestr + '%02dd' % d
if timespec > h:
h, timespec = divmod(timespec, h)
timestr = timestr + '%02dh' % h
if timespec > m:
m, timespec = divmod(timespec, m)
timestr = timestr + '%02dm' % m
return timestr + '%02ds' % timespec
## mpd command
def handle_mpd(bot, ievent):
""" display mpd status. """
try:
result = []
song = MPDDict(mpd('currentsong'))
status = MPDDict(mpd('status'))
status['time'] = mpd_duration(status['time'])
reply = ''
if status['state'] == 'play':
status['state'] = 'playing'
reply += '%s: %s\n[%s] #%s/%s %s (%s)\n' % (song['name'], song['title'], status['state'], status['song'], status['playlistlength'], status['time'], '0')
if status['state'] == 'stop': status['state'] = 'stopped'
reply += 'volume: %s | repeat: %s | random: %s | single: %s | consume: %s' % (status['volume'], status['repeat'], status['random'], status['single'], status['consume'])
ievent.reply(reply)
except MPDError, e: ievent.reply(str(e))
#mpd Display status
cmnds.add('mpd', handle_mpd, 'USER', threaded=True)
examples.add('mpd', 'Display mpd status', 'mpd')
## mpd-outputs command
def handle_mpd_outputs(bot, ievent):
""" show mpd outputs. """
# Output 1 (My ALSA Device) is enabled
# [('outputid', '0'), ('outputname', 'My ALSA Device'), ('outputenabled', '1')]
try:
outputs = mpd('outputs')
outputid = '?'
outputname = '?'
outputenabled = '?'
result = []
for item in outputs:
if item[0] == 'outputid': outputid = int(item[1])+1
if item[0] == 'outputname': outputname = item[1]
if item[0] == 'outputenabled':
if item[1] == '1': outputenabled = 'enabled'
else: outputenabled = 'disabled'
result.append('Output %d (%s) is %s' % (outputid, outputname, outputenabled))
outputid = '?'
outputname = '?'
outputenabled = '?'
ievent.reply("\n".join(result))
except MPDError, e:
ievent.reply(str(e))
## mpd-enable command
def handle_mpd_enable(bot, ievent):
try:
try: output = int(ievent.args[0])-1
except: ievent.missing('<output #>') ; return
result = mpd('enableoutput %d' % output)
ievent.reply(result)
except MPDError, e:
ievent.reply(str(e))
## mpd-disable command
def handle_mpd_disable(bot, ievent):
try:
try: output = int(ievent.args[0])-1
except: ievent.missing('<output #>') ; return
result = mpd('disableoutput %d' % output)
ievent.reply(result)
except MPDError, e:
ievent.reply(str(e))
## mpd-playlist command
def handle_mpd_playlist(bot, ievent):
try:
playlist = mpd('playlistinfo')
tmp = ''
result = []
for item in playlist:
if item[0] == 'file':
if not tmp == '': result.append(tmp)
tmp = item[1]
if item[0] == 'title': tmp = item[1]
if item[0] == 'name': tmp = '%s: %s' % (item[1], tmp)
ievent.reply("\n".join(result))
except MPDError, e:
ievent.reply(str(e))
## mpd-lsplaylists command
def handle_mpd_lsplaylists(bot, ievent):
try:
playlists = mpd('lsinfo')
result = []
for item in playlists:
if item[0] == 'playlist':
result.append(item[1])
ievent.reply("\n".join(result))
except MPDError, e:
ievent.reply(str(e))
## mpd-playlistmanipulation command
def handle_mpd_playlist_manipulation(bot, ievent, command):
try:
if not ievent.args:
ievent.missing('<playlist>')
return
playlist = str(ievent.args[0])
result = mpd('%s %s' % (command, playlist))
ievent.reply('Playlist %s loaded.' % playlist)
except MPDError, e:
ievent.reply(str(e))
## mpd-load command
def handle_mpd_load(bot, ievent):
handle_mpd_playlist_manipulation(bot, ievent, 'load')
## mpd-save command
def handle_mpd_save(bot, ievent):
handle_mpd_playlist_manipulation(bot, ievent, 'save')
## mpd-rm command
def handle_mpd_rm(bot, ievent):
handle_mpd_playlist_manipulation(bot, ievent, 'rm')
## mpd-np command
def handle_mpd_np(bot, ievent):
try:
status = MPDDict(mpd('currentsong'))
status['time'] = mpd_duration(status['time'])
ievent.reply(cfg.get('song-status') % status)
except MPDError, e:
ievent.reply(str(e))
#mpd-current Show the currently playing song
cmnds.add('mpd-current', handle_mpd_np, 'USER', threaded=True)
cmnds.add('mpd-np', handle_mpd_np, 'USER', threaded=True)
examples.add('mpd-current', 'Show the currently playing song', 'mpd-current')
## mpd-simpleseek command
def handle_mpd_simple_seek(bot, ievent, command):
try:
mpd(command)
#handle_mpd_np(bot, ievent)
handle_mpd(bot, ievent)
except MPDError, e:
ievent.reply(str(e))
## mpd-next command
handle_mpd_next = lambda b,i: handle_mpd_simple_seek(b,i,'next')
#mpd-next Play the next song in the current playlist
cmnds.add('mpd-next', handle_mpd_next, 'MPD', threaded=True)
examples.add('mpd-next', 'Play the next song in the current playlist', 'mpd-next')
## mpd-prev command
handle_mpd_prev = lambda b,i: handle_mpd_simple_seek(b,i,'prev')
#mpd-prev Play the previous song in the current playlist
cmnds.add('mpd-prev', handle_mpd_prev, 'MPD', threaded=True)
examples.add('mpd-prev', 'Play the previous song in the current playlist', 'mpd-prev')
## mpd-play command
handle_mpd_play = lambda b,i: handle_mpd_simple_seek(b,i,'play')
#mpd-play [<position>] Start playing at <position> (default: 1)
cmnds.add('mpd-play', handle_mpd_play, 'MPD', threaded=True)
examples.add('mpd-play', 'Start playing at <position> (default: 1)', 'mpd-play')
## mpd-stop command
handle_mpd_stop = lambda b,i: handle_mpd_simple_seek(b,i,'stop')
## mpd-pause command
handle_mpd_pause = lambda b,i: handle_mpd_simple_seek(b,i,'pause')
#mpd-pause Pauses the currently playing song
cmnds.add('mpd-pause', handle_mpd_pause, 'MPD', threaded=True)
examples.add('mpd-pause', 'Pauses the currently playing song', 'mpd-pause')
## mpd-clear command
handle_mpd_clear = lambda b,i: handle_mpd_simple_seek(b,i,'clear')
## mpd-crop command
handle_mpd_crop = lambda b,i: handle_mpd_simple_seek(b,i,'crop')
#mpd-crop Remove all but the currently playing song
cmnds.add('mpd-crop', handle_mpd_crop, 'MPD', threaded=True)
examples.add('mpd-crop', 'Remove all but the currently playing song', 'mpd-crop')
## mpd-shuffle command
handle_mpd_shuffle = lambda b,i: handle_mpd_simple_seek(b,i,'shuffle')
## mpd-repeat command
handle_mpd_repeat = lambda b,i: handle_mpd_toggle_option(b,i,'repeat')
## mpd-random command
handle_mpd_random = lambda b,i: handle_mpd_toggle_option(b,i,'random')
## mpd-single command
handle_mpd_single= lambda b,i: handle_mpd_toggle_option(b,i,'single')
## mpd-consume command
handle_mpd_consume= lambda b,i: handle_mpd_toggle_option(b,i,'consume')
## mpd-crossfade command
handle_mpd_crossfade= lambda b,i: handle_mpd_set_option(b,i,'crossfade')
## mpd-find command
def handle_mpd_find(bot, ievent):
type = 'title'
args = ievent.args
if args and args[0].lower() in ['title', 'album', 'artist']: type = args[0].lower() ; args = args[1:]
if not args: ievent.missing('[<type>] <what>') ; return
try:
find = mpd('search %s "%s"' % (type, ' '.join(args)))
show = []
for item, value in find:
if item == 'file': show.append(value)
if show: ievent.reply("results: ", show)
else: ievent.reply('no result')
except MPDError, e: ievent.reply(str(e))
## mpd-add command
def handle_mpd_add(bot, ievent):
if not ievent.args:
ievent.missing('<file>')
return
try:
addid = MPDDict(mpd('addid "%s"' % ievent.rest))
if not addid.has_key('id'):
ievent.reply('failed to load song "%s"' % ievent.rest)
else:
ievent.reply('added song with id "%s", use "mpd-jump %s" to start playback' % (addid['id'], addid['id']))
except MPDError, e:
ievent.reply(str(e))
#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')
## mpd-del command
def handle_mpd_del(bot, ievent):
if not ievent.args: ievent.missing('<position>') ; return
try: result = mpd('delete %d' % int(ievent.args[0])) ; ievent.reply(result)
except MPDError, e: ievent.reply(str(e))
#mpd-del <position> Remove a song from the current playlist
cmnds.add('mpd-del', handle_mpd_del, 'MPD', threaded=True)
examples.add('mpd-del', 'Remove a song from the current playlist', 'mpd-del 1')
## mpd-jump command
def handle_mpd_jump(bot, ievent):
pos = 0
try: pos = int(ievent.args[0])
except: pass
if not pos: ievent.missing('<playlist id>') ; return
try:
mpd('playid %d' % pos)
handle_mpd_np(bot, ievent)
except MPDError, e: ievent.reply(str(e))
cmnds.add('mpd-jump', handle_mpd_jump, 'MPD', threaded=True)
examples.add('mpd-jump', 'jump to the specified playlist id', 'mpd-jump 777')
## mpd-stats command
def handle_mpd_stats(bot, ievent):
try:
status = MPDDict(mpd('stats'))
status['total playtime'] = mpd_duration(status['playtime'])
status['total database playtime'] = mpd_duration(status['db_playtime'])
status['uptime'] = mpd_duration(status['uptime'])
del status['playtime']
del status['db_playtime']
del status['db_update']
result = []
for item in sorted(status.keys()):
result.append('%s: %s' % (item, status[item]))
ievent.reply(" | ".join(result))
except MPDError, e:
ievent.reply(str(e))
#mpd-stats Display statistics about MPD
cmnds.add('mpd-stats', handle_mpd_stats, 'USER', threaded=True)
examples.add('mpd-stats', 'Display statistics about MPD', 'mpd-stats')
## mpd-volume command
def handle_mpd_volume(bot, ievent):
volume = 0
try: volume = int(ievent.args[0])
except: pass
if not volume:
status = MPDDict(mpd('status'))
ievent.reply('Current volume: %s' % status['volume'])
return
try:
mpd('setvol %d' % volume)
ievent.reply('Volume set to %d' % volume)
except MPDError, e:
ievent.reply(str(s))
## mpd-toggleoption command
def handle_mpd_toggle_option(bot, ievent, option):
if ievent.args:
val = 'on'
try: val = ievent.args[0]
except: pass
if val == '0' or val == 'off': val = '0'
else: val = '1'
else:
status = MPDDict(mpd('status'))
if status[option] == '0': val = '1'
else: val = '0'
try:
mpd('%s %s' % (option, val))
handle_mpd(bot, ievent)
except MPDError, e:
ievent.reply(str(e))
## mpd-setoption command
def handle_mpd_set_option(bot, ievent, option):
try:
if ievent.args:
val = -1
try: val = int(ievent.args[0])
except: pass
if val > 0:
mpd('%s %s' % (option, val))
else:
ievent.reply('"off" is not 0 or positive integer' % ievent.args[0])
return
else:
status = MPDDict(mpd('status'))
ievent.reply("%s %s" % (option, status['xfade']))
except MPDError, e:
ievent.reply(str(e))
## mpd-watchstart command
def handle_mpd_watch_start(bot, ievent):
if not cfg.get('watcher-enabled'):
ievent.reply('watcher not enabled, use "!%s-cfg watcher-enabled 1" to enable and reload the plugin' % os.path.basename(__file__)[:-3])
return
watcher.add(bot, ievent)
ievent.reply('ok')
cmnds.add('mpd-watch-start', handle_mpd_watch_start, 'MPD', threaded=True)
## mpd-watchstop command
def handle_mpd_watch_stop(bot, ievent):
if not cfg.get('watcher-enabled'):
ievent.reply('watcher not enabled, use "!%s-cfg watcher-enabled 1" to enable and reload the plugin' % os.path.basename(__file__)[:-3])
return
watcher.remove(bot, ievent)
ievent.reply('ok')
cmnds.add('mpd-watch-stop', handle_mpd_watch_stop, 'MPD', threaded=True)
## mpd-watchlist command
def handle_mpd_watch_list(bot, ievent):
if not cfg.get('watcher-enabled'):
ievent.reply('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-watch-list', handle_mpd_watch_list, 'MPD', threaded=True)
## register command and exmaples
#mpd-toggle Toggles Play/Pause, plays if stopped
cmnds.add('mpd-toggle', handle_mpd_pause, 'MPD', threaded=True)
examples.add('mpd-toggle', 'Toggles Play/Pause, plays if stopped', 'mpd-toggle')
#mpd-stop Stop the currently playing playlists
cmnds.add('mpd-stop', handle_mpd_stop, 'MPD', threaded=True)
examples.add('mpd-stop', 'Stop the currently playing playlists', 'mpd-stop')
# TODO mpd-seek [+-][HH:MM:SS]|<0-100>% Seeks to the specified position
# cmnds.add('mpd-seek', handle_mpd_seek, 'MPD')
#mpd-clear Clear the current playlist
cmnds.add('mpd-clear', handle_mpd_clear, 'MPD', threaded=True)
examples.add('mpd-clear', 'Clear the current playlist', 'mpd-clear')
#mpd-outputs Show the current outputs
cmnds.add('mpd-outputs', handle_mpd_outputs, 'MPD', threaded=True)
examples.add('mpd-outputs', 'Show the current outputs', 'mpd-outputs')
#mpd-enable <output #> Enable a output
cmnds.add('mpd-enable', handle_mpd_enable, 'MPD', threaded=True)
examples.add('mpd-enable', 'Enable a output', 'mpd-enable <output #>')
#mpd-disable <output #> Disable a output
cmnds.add('mpd-disable', handle_mpd_disable, 'MPD', threaded=True)
examples.add('mpd-disable', 'Disable a output', 'mpd-disable <output #>')
#mpd-shuffle Shuffle the current playlist
cmnds.add('mpd-shuffle', handle_mpd_shuffle, 'MPD', threaded=True)
examples.add('mpd-shuffle', 'Shuffle the current playlist', 'mpd-shuffle')
# TODO mpd move <from> <to> Move song in playlist
#cmnds.add('mpd-move', handle_mpd_move, 'MPD')
#examples.add('mpd-move', 'Move song in playlist', 'mpd-move <from> <to>')
#mpd-playlist Print the current playlist
cmnds.add('mpd-playlist', handle_mpd_playlist, 'USER', threaded=True)
examples.add('mpd-playlist', 'Print the current playlist', 'mpd-playlist')
# TODO mpd listall [<file>] List all songs in the music dir
#cmnds.add('mpd-listall', handle_mpd_listall, 'USER')
#examples.add('mpd-listall', 'List all songs in the music dir', 'mpd-listall [<file>]')
# TODO mpd ls [<directory>] List the contents of <directory>
#cmnds.add('mpd-ls', handle_mpd_ls, 'USER')
#examples.add('mpd-ls', 'List the contents of <directory>', 'mpd-ls [<directory>]')
#mpd-lsplaylists List currently available playlists
cmnds.add('mpd-lsplaylists', handle_mpd_lsplaylists, 'USER', threaded=True)
examples.add('mpd-lsplaylists', 'List currently available playlists', 'mpd-lsplaylists')
#mpd-load <file> Load <file> as a playlist
cmnds.add('mpd-load', handle_mpd_load, 'MPD', threaded=True)
examples.add('mpd-load', 'Load <file> as a playlist', 'mpd-load <file>')
#mpd-save <file> Save a playlist as <file>
cmnds.add('mpd-save', handle_mpd_save, 'MPD', threaded=True)
examples.add('mpd-save', 'Save a playlist as <file>', 'mpd-save <file>')
#mpd-rm <file> Remove a playlist
cmnds.add('mpd-rm', handle_mpd_rm, 'MPD', threaded=True)
examples.add('mpd-rm', 'Remove a playlist', 'mpd-rm <file>')
#mpd-volume [+-]<num> Set volume to <num> or adjusts by [+-]<num>
# TODO [+-]
cmnds.add('mpd-volume', handle_mpd_volume, 'MPD', threaded=True)
examples.add('mpd-volume', 'Set volume to <num> or adjusts by [+-]<num>', 'mpd-volume 42')
#mpd-repeat <on|off> Toggle repeat mode, or specify state
cmnds.add('mpd-repeat', handle_mpd_repeat, 'MPD', threaded=True)
examples.add('mpd-volume', 'Toggle repeat mode, or specify state', 'mpd-repeat off')
#mpd-random <on|off> Toggle random mode, or specify state
cmnds.add('mpd-random', handle_mpd_random, 'MPD', threaded=True)
examples.add('mpd-random', 'Toggle random mode, or specify state', 'mpd-random <on|off>')
#mpd-single <on|off> Toggle single mode, or specify state
cmnds.add('mpd-single', handle_mpd_single, 'MPD', threaded=True)
examples.add('mpd-single', 'Toggle single mode, or specify state', 'mpd-single <on|off>')
#mpd-consume <on|off> Toggle consume mode, or specify state
cmnds.add('mpd-consume', handle_mpd_consume, 'MPD', threaded=True)
examples.add('mpd-consume', 'Toggle consume mode, or specify state', 'mpd-consume <on|off>')
# TODO mpd search <type> <query> Search for a song
#cmnds.add('mpd-search', handle_mpd_search, 'MPD')
#examples.add('mpd-search', 'Search for a song', 'mpd-search <type> <query>')
#mpd-find <type> <query> Find a song (exact match)
cmnds.add('mpd-find', handle_mpd_find, 'MPD', threaded=True)
examples.add('mpd-find', 'Find a song (exact match)', 'mpd-find title love')
# TODO mpd-findadd <type> <query> Find songs and add them to the current playlist
# cmnds.add('mpd-findadd', handle_mpd_findadd, 'MPD')
#examples.add('mpd-findadd', 'Find songs and add them to the current playlist', 'mpd-findadd <type> <query>')
# TODO mpd-list <type> [<type> <query>] Show all tags of <type>
# cmnds.add('mpd-list', handle_mpd_list, 'MPD')
#examples.add('mpd-list', 'Show all tags of <type>', 'mpd-list <type> [<type> <query>]')
#mpd-crossfade [<seconds>] Set and display crossfade settings
cmnds.add('mpd-crossfade', handle_mpd_crossfade, 'MPD', threaded=True)
examples.add('mpd-crossfade', 'Set and display crossfade settings', 'mpd-crossfade 42')
#mpd-update [<path>] Scan music directory for updates
#cmnds.add('mpd-update', handle_mpd_update, 'MPD')
#mpd-sticker <uri> <get|set|list|del> <args..> Sticker management
#cmnds.add('mpd-sticker', handle_mpd_sticker, 'MPD')
#mpd-version Report version of MPD
#cmnds.add('mpd-version', handle_mpd_version, 'USER')
#mpd-idle [events] Idle until an event occurs
#cmnds.add('mpd-idle', handle_mpd_idle, 'MPD')
#mpd-idleloop [events] Continuously idle until an event occurs
#cmnds.add('mpd-idleloop', handle_mpd_idleloop, 'MPD')
# TODO mpd-replaygain [off|track|ablum] Set or display the replay gain mode
# cmnds.add('mpd-replaygain', handle_mpd_replaygain, 'MPD')
#examples.add('mpd-replaygain', 'Set or display the replay gain mode', 'mpd-replaygain')
| Python |
# jsb socket related plugins
#
#
""" this package contains all the socket related plugins. """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb/plugs/socket/restserver.py
#
#
## jsb imports
from jsb.lib.callbacks import callbacks
from jsb.utils.url import posturl, getpostdata
from jsb.lib.persistconfig import PersistConfig
from jsb.lib.commands import cmnds
from jsb.lib.rest.server import RestServer, RestRequestHandler
from jsb.lib.eventbase import EventBase
from jsb.utils.exception import handle_exception
from jsb.lib.examples import examples
## basic imports
import socket
import re
import logging
## defines
enable = False
try:
cfg = PersistConfig()
cfg.define('enable', 0)
cfg.define('host' , socket.gethostbyname(socket.getfqdn()))
cfg.define('name' , socket.getfqdn())
cfg.define('port' , 11111)
cfg.define('disable', [])
hp = "%s:%s" % (cfg.get('host'), cfg.get('port'))
url = "http://%s" % hp
if cfg.enable: enable = True
except AttributeError: enable = False # we are on GAE
## server part
server = None
## functions
def startserver(force=False):
""" start the rest server. """
if not enable: logging.debug("rest server is disabled") ; return
global server
if server and not force: logging.debug("REST server is already running. ") ; return server
try:
server = RestServer((cfg.get('host'), cfg.get('port')), RestRequestHandler)
if server:
server.start()
logging.warn('restserver - running at %s:%s' % (cfg.get('host'), cfg.get('port')))
for mount in cfg.get('disable'): server.disable(mount)
else: logging.error('restserver - failed to start server at %s:%s' % (cfg.get('host'), cfg.get('port')))
except socket.error, ex: logging.warn('restserver - start - socket error: %s' % str(ex))
except Exception, ex: handle_exception()
return server
def stopserver():
""" stop server. """
try:
if not server: logging.debug('restserver - server is already stopped') ; return
server.shutdown()
except Exception, ex: handle_exception()
## plugin init
def init():
if cfg['enable']: startserver()
def shutdown():
if cfg['enable']: stopserver()
## rest-start command
def handle_rest_start(bot, event):
""" 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):
""" 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')
| Python |
# jsb/plugs/socket/geo.py
#
#
""" This product includes GeoLite data created by MaxMind, available from http://maxmind.com/ """
## jsb imports
from jsb.lib.callbacks import callbacks
from jsb.lib.examples import examples
from jsb.lib.commands import cmnds
from jsb.utils.url import geturl2
from jsb.utils.exception import handle_exception
from jsb.imports import getjson
## basic imports
from socket import gethostbyname
import re
## defines
URL = "http://geoip.pidgets.com/?ip=%s&format=json"
## querygeoipserver function
def querygeoipserver(ip):
ipinfo = getjson().loads(geturl2(URL % ip))
return ipinfo
## host2ip function
def host2ip(query):
ippattern = re.match(r"^([0-9]{1,3}\.){3}[0-9]{1,3}$", query)
hostpattern = re.match(r"(\w+://)?(?P<hostname>\S+\.\w+)", query)
ip = ""
if ippattern: ip = ippattern.group(0)
elif hostpattern:
try: ip = gethostbyname(hostpattern.group('hostname'))
except: pass
return ip
## geo command
def handle_geo(bot, event):
""" do a geo lookup. """
if not event.rest:
event.missing("<ip>")
return
query = event.rest.strip()
ip = host2ip(query)
if not ip: event.reply("Couldn't look up the hostname") ; return
event.reply("geo of %s is: " % ip, querygeoipserver(ip))
cmnds.add("geo", handle_geo, ["OPER", "GEO"])
examples.add("geo", "do a geo lookup on ip nr", "geo 127.0.0.1")
## callbacks
def handle_geoPRE(bot, event):
if "." in event.hostname and event.chan and event.chan.data.dogeo: return True
def handle_geoJOIN(bot, event):
event.reply("geo - doing query on %s" % event.hostname)
try:
result = querygeoipserver(host2ip(event.hostname))
if result: event.reply("%s lives in %s, %s (%s)" % (event.nick, result['city'], result['country_name'], result['country_code']))
else: event.reply("no result")
except: handle_exception()
callbacks.add("JOIN", handle_geoJOIN, handle_geoPRE)
## geo-on command
def handle_geoon(bot, event):
""" enable geo lookup on JOIN. """
event.chan.data.dogeo = True
event.chan.save()
event.done()
cmnds.add("geo-on", handle_geoon, ["OPER"])
examples.add("geo-on", "enable geo loopups.", "geo-on")
## geo-off command
def handle_geooff(bot, event):
""" disable geo lookup on JOIN. """
event.chan.data.dogeo = False
event.chan.save()
event.done()
cmnds.add("geo-off", handle_geooff, ["OPER"])
examples.add("geo-off", "disable geo loopups.", "geo-off")
| Python |
# jsb/plugs/wave/wave.py
#
#
""" wave related commands. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.exception import handle_exception
from jsb.lib.persist import PlugPersist
from jsb.lib.callbacks import callbacks
from jsb.lib.plugins import plugs
from jsb.drivers.gae.wave.waves import Wave
## basic imports
import logging
## wave-start command
def handle_wavestart(bot, event):
""" start a protected wave. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
wave = event.chan
event.reply("cloning ...")
newwave = wave.clone(bot, event, participants=["jsb@appspot.com", event.userhost])
if not newwave:
event.reply("can't create new wave")
return
newwave.data.protected = True
newwave.data.owner = event.userhost
newwave.save()
event.reply("done")
cmnds.add('wave-start', handle_wavestart, 'USER')
examples.add('wave-start', 'start a new wave', 'wave-start')
## wave-clone commnad
def handle_waveclone(bot, event):
""" clone wave into a new one, copying over particpants and feeds. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
wave = event.chan
event.reply("cloning ...")
newwave = wave.clone(bot, event, event.root.title.strip(), True)
if not newwave:
event.reply("can't create new wave")
return
plugs.load('jsb.plugs.common.hubbub')
feeds = plugs['jsb.plugs.common.hubbub'].watcher.clone(bot.name, bot.type, newwave.data.waveid, event.waveid)
event.reply("this wave is continued to %s with the following feeds: %s" % (newwave.data.url, feeds))
cmnds.add('wave-clone', handle_waveclone, 'USER')
examples.add('wave-clone', 'clone the wave', 'wave-clone')
## wave-new command
def handle_wavenew(bot, event):
""" make a new wave. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
parts = ['jsb@appspot.com', event.userhost]
newwave = bot.newwave(event.domain, parts)
if event.rest:
newwave.SetTitle(event.rest)
event.done()
cmnds.add('wave-new', handle_wavenew, 'USER')
examples.add('wave-new', 'make a new wave', 'wave-new')
## wave-public command
def handle_wavepublic(bot, event):
""" make the wave public. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
event.root.participants.add('public@a.gwave.com')
event.done()
cmnds.add('wave-public', handle_wavepublic, 'USER')
examples.add('wave-public', 'make the wave public', 'wave-public')
## wave-invite command
def handle_waveinvite(bot, event):
""" invite a user to the wave. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
if not event.rest:
event.missing('<who>')
return
event.root.participants.add(event.rest)
event.done()
cmnds.add('wave-invite', handle_waveinvite, 'USER')
examples.add('wave-invite', 'invite a user/bot into the wave', 'wave-invite bthate@googlewave.com')
## wave-id command
def handle_waveid(bot, event):
""" get the id of the wave. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
event.reply(event.waveid)
cmnds.add('wave-id', handle_waveid, 'USER')
examples.add('wave-id', 'show the id of the wave the command is given in.', 'wave-id')
## wave-url command
def handle_waveurl(bot, event):
""" get the url of the wave. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
event.reply(event.url)
cmnds.add('wave-url', handle_waveurl, 'USER')
examples.add('wave-url', 'show the url of the wave the command is given in.', 'wave-url')
## wave-participants command
def handle_waveparticipants(bot, event):
""" show participants. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
event.reply("participants: ", list(event.root.participants))
cmnds.add('wave-participants', handle_waveparticipants, 'USER')
examples.add('wave-participants', 'show the participants of the wave the command is given in.', 'wave-participants')
## wave-part command
def handle_wavepart(bot, event):
""" leave a wave. not implemented yet. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
event.reply('bye')
cmnds.add('wave-part', handle_wavepart, 'OPER')
examples.add('wave-part', 'leave the wave', 'wave-part')
## wave-title ocmmand
def handle_wavetitle(bot, event):
""" set title of the wave. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
if not event.rest:
event.missing("<title>")
return
event.set_title(event.rest)
event.reply('done')
cmnds.add('wave-title', handle_wavetitle, 'OPER')
examples.add('wave-title', 'set title of the wave', 'wave-title')
## wave-data command
def handle_wavedata(bot, event):
""" show stored wave data. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
wave = event.chan
if wave:
data = dict(wave.data)
del data['passwords']
del data['json_data']
event.reply(str(data))
else:
event.reply("can't fetch wave data of wave %s" % wave.waveid)
cmnds.add('wave-data', handle_wavedata, 'OPER')
examples.add('wave-data', 'show the waves stored data', 'wave-data')
## wave-threshold command
def handle_wavethreshold(bot, event):
""" set threshold of the wave. after x nr of blips the wave will be cloned. """
if event.bottype != "wave":
event.reply("this command only works in google wave.");
return
try:
nrblips = int(event.rest)
except ValueError:
nrblips = -1
wave = event.chan
if wave:
if nrblips == -1:
event.reply('threshold of "%s" is %s' % (wave.data.title, str(wave.data.threshold)))
return
wave.data.threshold = nrblips
wave.save()
event.reply('threshold of "%s" set to %s' % (wave.data.title, str(wave.data.threshold)))
cmnds.add('wave-threshold', handle_wavethreshold, 'OPER')
examples.add('wave-threshold', 'set nr of blips after which we clone the wave', 'wave-threshold')
## wave-whitelist command
def handle_wavewhitelistadd(bot, event):
""" add a user to the waves whitelist .. allow modifications. """
if not event.rest:
event.missing("<id>")
return
target = event.rest
if not event.chan.data.whitelist:
event.chan.data.whitelist = []
if target not in event.chan.data.whitelist:
event.chan.data.whitelist.append(target)
event.chan.save()
event.reply("done")
cmnds.add("wave-whitelistadd", handle_wavewhitelistadd, "OPER")
examples.add("wave-whitelistadd", "add a user to the waves whitelist", "wave-whitelistadd bthate@googlewave.com")
## wave-whitelistdel command
def handle_wavewhitelistdel(bot, event):
""" remove user from the waves whitelist .. deny modifications. """
if not event.rest:
event.missing("<id>")
return
target = event.rest
if not event.chan.data.whitelist:
event.chan.data.whitelist = []
if target in event.chan.data.whitelist:
event.chan.data.whitelist.remove(target)
event.chan.save()
event.reply("done")
cmnds.add("wave-whitelistdel", handle_wavewhitelistdel, "OPER")
examples.add("wave-whitelistdel", "delete a user from the waves whitelist", "wave-whitelistdel bthate@googlewave.com")
| Python |
# jsb/plugs/wave/gadget.py
#
#
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persist import PlugPersist
## defines
gadgeturls = PlugPersist('gadgeturls')
gadgeturls.data['gadget'] = 'https://jsonbot.appspot.com/gadget.xml'
gadgeturls.data['poll'] = 'https://jsonbot.appspot.com/poll.xml'
gadgeturls.data['iframe'] = 'https://jsonbot.appspot.com/iframe.xml'
gadgeturls.data['loadiframe'] = 'https://jsonbot.appspot.com/loadiframe.xml'
## load functions
def loadroot(event, url):
if event.rootblip:
from waveapi import element
event.rootblip.append(element.Gadget(url))
return True
else: event.reply("can't find root blip.") ; return False
def load(event, url):
if event.blip:
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")
## gadget-iframe command
def handle_gadgetiframe(bot, event):
if event.bottype != "wave": event.reply("this command only works in google wave.") ; return
if not event.rest: event.missing('<url>') ; return
try:
url = gadgeturls.data['loadiframe'] + "?&iframeurl=%s" % event.rest
event.reply('loading %s' % url)
load(event, url)
except KeyError: event.reply("we don't have a iframe url")
cmnds.add("gadget-iframe", handle_gadgetiframe, 'USER')
examples.add("gadget-iframe", "load a url into a iframe", "gadget-iframe")
## gadget-addurl command
def handle_gadgetaddurl(bot, event):
try: (name, url) = event.args
except ValueError: event.missing('<name> <url>') ; return
if not gadgeturls.data.has_key(name):
gadgeturls.data[name] = url
gadgeturls.save()
else: event.reply("we already have a %s gadget" % name)
cmnds.add("gadget-addurl", handle_gadgetaddurl, 'USER')
examples.add("gadget-addurl", "store a gadget url", "gadget-addurl jsb https://jsonbot.appspot.com/iframe.xml")
## gadget-delurl command
def handle_gadgetdelurl(bot, event):
try: (name, url) = event.args
except ValueError: event.missing('<name> <url>') ; return
gadgeturls.data[name] = url
gadgeturls.save()
cmnds.add("gadget-delurl", handle_gadgetdelurl, 'OPER')
examples.add("gadget-delurl", "delete a gadget url", "gadget-delurl mygadget")
## gadget-list command
def handle_gadgetlist(bot, event):
result = []
for name, url in gadgeturls.data.iteritems(): result.append("%s - %s" % (name, url))
event.reply("available gadgets: ", result)
cmnds.add("gadget-list", handle_gadgetlist, 'USER')
examples.add("gadget-list", "list known gadget urls", "gadget-list")
## gadget-console command
def handle_gadgetconsole(bot, event):
if event.bottype != "wave": event.reply("this command only works in google wave.") ; return
wave = event.chan
if wave.data.feeds and wave.data.dotitle:
event.set_title("JSONBOT - %s #%s" % (" - ".join(wave.data.feeds), str(wave.data.nrcloned)))
from waveapi import element
event.append("loading ...\n")
event.append(element.Gadget('http://jsonbot.appspot.com/console.xml?gadget_cache=0'))
cmnds.add("gadget-console", handle_gadgetconsole, 'OPER')
examples.add("gadget-console", "load the console gadget", "gadget-console")
| Python |
# jsb/plugs/wave/clone.py
#
#
""" clone the wave after x blips. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.callbacks import callbacks
from jsb.drivers.gae.wave.waves import Wave
from jsb.lib.plugins import plugs
## basic imports
import logging
## callbacks
def clonepre(bot, event):
if event.bottype == "wave":
return True
def clonecallback(bot, event):
wave = event.chan
if wave.data.threshold != -1 and (wave.data.seenblips > wave.data.threshold):
wave.data.threshold = -1
newwave = wave.clone(bot, event, event.title)
plugs.load('jsb.plugs.common.hubbub')
feeds = plugs['jsb.plugs.common.hubbub'].watcher.clone(bot.name, bot.type, newwave.data.waveid, event.waveid)
event.reply("this wave is continued to %s with the following feeds: %s" % (newwave.data.url, feeds))
#callbacks.add("BLIP_SUBMITTED", clonecallback, clonepre)
#callbacks.add('OUTPUT', clonecallback, clonepre)
| Python |
# jsb wave plugins
#
#
""" this package contains all wave related plugins. """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb/plugs/core/grep.py
#
#
""" grep the output of bot comamnds. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.utils.generic import waitforqueue
from jsb.lib.examples import examples
## basic imports
import getopt
import re
## grep command
def handle_grep(bot, ievent):
""" grep the result list. """
if not ievent.inqueue: ievent.reply('use grep in a pipeline') ; return
if not ievent.rest: ievent.reply('grep <txt>') ; return
try: (options, rest) = getopt.getopt(ievent.args, 'riv')
except getopt.GetoptError, ex: ievent.reply(str(ex)) ; return
result = waitforqueue(ievent.inqueue, 3000)
if not result: ievent.reply('no data to grep on: %s' % ievent.txt) ; return
doregex = False
docasein = False
doinvert = False
for i, j in options:
if i == '-r': doregex = True
if i == '-i': docasein = True
if i == '-v': doinvert = True
res = []
if doregex:
try:
if docasein: reg = re.compile(' '.join(rest), re.I)
else: reg = re.compile(' '.join(rest))
except Exception, ex:
ievent.reply("can't compile regex: %s" % str(ex))
return
if doinvert:
for i in result:
if not re.search(reg, i): res.append(i)
else:
for i in result:
if re.search(reg, i): res.append(i)
else:
if docasein: what = ' '.join(rest).lower()
elif doinvert: what = ' '.join(rest)
else: what = ievent.rest
for i in result:
if docasein:
if what in str(i.lower()): res.append(i)
elif doinvert:
if what not in str(i): res.append(i)
else:
if what in str(i): res.append(i)
if not res: ievent.reply('no result')
else: ievent.reply('results: ', res)
cmnds.add('grep', handle_grep, ['OPER', 'USER', 'GUEST'])
examples.add('grep', 'grep the output of a command', 'list ! grep core')
| Python |
# jsb/plugs/core/data.py
#
#
""" 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())
cmnds.add("data-bot", handle_databot, "OPER")
examples.add('data-bot', 'dump bot data', 'data-bot')
| Python |
# jsb/plugs/core/rc.py
#
#
""" jsonbot resource files .. files with the .jsb extension which consists of commands to be executed. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.url import geturl2
from jsb.utils.exception import handle_exception
from jsb.utils.generic import waitforqueue, waitevents
from jsb.lib.config import getmainconfig
## basic imports
import copy
## defines
cpy = copy.deepcopy
## rc command
def handle_rc(bot, event):
""" import aliases by url. assumes a .RC file. 1 alias per line """
if not event.rest: event.missing("<file>|<url>") ; return
teller = 0
t = event.rest
waiting = []
try:
try:
if getmainconfig().allowremoterc and t.startswith("http"): data = geturl2(t)
else: data = open(t, 'r').read()
except IOError, ex: event.reply("I/O error: %s" % str(ex)) ; return
if not data: event.reply("can't get data from %s" % event.rest) ; return
for d in data.split("\n"):
i = d.strip()
if not i: continue
if i.startswith("#"): continue
e = cpy(event)
e.txt = "%s" % i.strip()
e.direct = True
bot.put(e)
waiting.append(e)
#result = bot.docmnd(event.userhost, event.channel, i, wait=1, event=event)
#if result: result.waitall()
teller += 1
#waitevents(waiting)
event.reply("%s commands executed" % teller)
except Exception, ex: event.reply("an error occured: %s" % str(ex)) ; handle_exception()
cmnds.add("rc", handle_rc, ["OPER"], threaded=True)
examples.add("rc", "execute a file of jsonbot commands .. from file or url", "1) rc resource.jsb 2) rc http://jsonbot.org/resource.jsb")
| Python |
# jsb/plugs/core/nickserv.py
#
#
""" authenticate to NickServ. """
__author__ = "Wijnand 'tehmaze' Modderman - http://tehmaze.com"
__license__ ='BSD'
## jsb imports
from jsb.lib.examples import examples
from jsb.lib.callbacks import callbacks
from jsb.lib.commands import cmnds
from jsb.lib.datadir import getdatadir
from jsb.lib.fleet import getfleet
from jsb.utils.pdod import Pdod
## basic imports
import os
import time
import logging
## NSAuth class
class NSAuth(Pdod):
""" nickserve auth. """
def __init__(self):
self.registered = False
Pdod.__init__(self, getdatadir() + os.sep + 'plugs' + os.sep + 'jsb.plugs.nickserv' + os.sep + 'nickserv')
def add(self, bot, **kwargs):
""" add a nickserv entry. """
options = {
'nickserv': 'NickServ',
'identify': 'identify',
}
options.update(kwargs)
assert options.has_key('password'), 'A password must be set'
for key in options.keys(): Pdod.set(self, bot.cfg.name, key, options[key])
self.save()
def remove(self, bot):
""" remove a nickserv entry. """
if self.has_key(bot.cfg.name):
del self[bot.cfg.name]
self.save()
def has(self, bot):
""" check if a bot is in the nickserv list. """
return self.has_key(bot.cfg.name)
def register(self, bot, passwd):
""" register a bot to nickserv. """
if self.has_key(bot.cfg.name) and self.has_key2(bot.cfg.name, 'nickserv'):
bot.sendraw('PRIVMSG %s :%s %s' % (self.get(bot.cfg.name, 'nickserv'), 'REGISTER', passwd))
logging.warn('nickserv - register sent on %s' % bot.cfg.server)
def identify(self, bot):
""" identify a bot to nickserv. """
if self.has_key(bot.cfg.name):
logging.warn('nickserv - identify sent on %s' % bot.cfg.server)
bot.outnocb(self.get(bot.cfg.name, 'nickserv', ), '%s %s' % (self.get(bot.cfg.name, 'identify'), self.get(bot.cfg.name, 'password')), how="msg")
def listbots(self):
""" list all bots know. """
all = []
for bot in self.data.keys(): all.append((bot, self.data[bot]['nickserv']))
return all
def sendstring(self, bot, txt):
""" send string to nickserver. """
nickservnick = self.get(bot.cfg.name, 'nickserv')
logging.warn('nickserv - sent %s to %s' % (txt, nickservnick))
bot.outnocb(nickservnick, txt, how="msg")
def handle_001(self, bot, ievent):
self.identify(bot)
try:
for i in self.data[bot.cfg.name]['nickservtxt']:
self.sendstring(bot, i)
logging.warn('nickserv - sent %s' % i)
except: pass
## init stuff
nsauth = NSAuth()
if not nsauth.data:
nsauth = NSAuth()
## register callback
callbacks.add('001', nsauth.handle_001, threaded=True)
## ns-add command
def handle_nsadd(bot, ievent):
""" 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]
fbot = getfleet().byname(botname)
if not fbot:
ievent.reply('fleet bot %s not found' % botname)
return
if not nsauth.has(fbot):
ievent.reply('nickserv not configured on %s' % fbot.cfg.name)
return
nsauth.remove(fbot)
ievent.reply('ok')
cmnds.add('ns-del', handle_nsdel, 'OPER', threaded=True)
examples.add('ns-del', 'ns-del <fleetbot name>', 'ns-del test')
## ns-send command
def handle_nssend(bot, ievent):
""" send string to the nickserv. """
if bot.jabber: return
if not ievent.rest:
ievent.missing('<txt>')
return
nsauth.sendstring(bot, ievent.rest)
ievent.reply('send')
cmnds.add('ns-send', handle_nssend, 'OPER', threaded=True)
examples.add('ns-send', 'ns-send <txt> .. send txt to nickserv', 'ns-send identify bla')
## ns-auth command
def handle_nsauth(bot, ievent):
""" perform an auth request. """
if bot.jabber: return
if len(ievent.args) != 1: name = bot.cfg.name
else: name = ievent.args[0]
fbot = getfleet().byname(name)
if not fbot:
ievent.reply('fleet bot %s not found' % name)
return
if not nsauth.has(fbot):
ievent.reply('nickserv not configured on %s' % fbot.cfg.name)
return
nsauth.identify(fbot)
ievent.reply('ok')
cmnds.add('ns-auth', handle_nsauth, 'OPER', threaded=True)
examples.add('ns-auth','ns-auth [<botname>]', '1) ns-auth 2) ns-auth test')
## ns-list command
def handle_nslist(bot, ievent):
""" show a list of all bots know with nickserv. """
if bot.jabber: return
all = dict(nsauth.listbots())
rpl = []
for bot in all.keys(): rpl.append('%s: authenticating through %s' % (bot, all[bot]))
rpl.sort()
ievent.reply(' .. '.join(rpl))
cmnds.add('ns-list', handle_nslist, 'OPER')
examples.add('ns-list', 'list all nickserv entries', 'ns-list')
| Python |
# jsb/plugs/core/core.py
#
#
""" core bot commands. """
## jsb imports
from jsb.utils.statdict import StatDict
from jsb.utils.log import setloglevel, getloglevel
from jsb.utils.timeutils import elapsedstring
from jsb.utils.exception import handle_exception
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.plugins import plugs
from jsb.lib.boot import plugin_packages, getpluginlist, boot, getcmndtable, whatcommands
from jsb.lib.persist import Persist
from jsb.lib.reboot import reboot, reboot_stateful
from jsb.lib.eventhandler import mainhandler
from jsb.lib.fleet import getfleet
from jsb.lib.partyline import partyline
from jsb.lib.exit import globalshutdown
from jsb.lib.runner import defaultrunner, cmndrunner, longrunner
from jsb.lib.errors import NoSuchPlugin
## basic imports
import time
import threading
import sys
import re
import os
import copy
import cgi
## defines
cpy = copy.deepcopy
## reboot command
def handle_reboot(bot, ievent):
""" reboot the bot. """
if bot.isgae:
ievent.reply("this command doesn't work on the GAE")
return
ievent.reply("rebooting")
time.sleep(3)
if ievent.rest == "cold": stateful = False
else: stateful = True
if stateful: mainhandler.put(0, reboot_stateful, bot, ievent, getfleet(), partyline)
else:
getfleet().exit()
mainhandler.put(0, reboot)
cmnds.add("reboot", handle_reboot, "OPER")
examples.add("reboot", "reboot the bot.", "reboot")
## quit command
def handle_quit(bot, ievent):
""" disconnect from the server. """
if bot.isgae:
ievent.reply("this command doesnt work on the GAE")
return
ievent.reply("quiting")
bot.exit()
cmnds.add("quit", handle_quit, "OPER")
examples.add("quit", "quit the bot.", "quit")
## encoding command
def handle_encoding(bot, ievent):
""" show default encoding. """
ievent.reply('default encoding is %s' % bot.encoding or sys.getdefaultencoding())
cmnds.add('encoding', handle_encoding, ['USER', 'GUEST'])
examples.add('encoding', 'show default encoding', 'encoding')
## uptime command
def handle_uptime(bot, ievent):
""" show uptime. """
ievent.reply("<b>uptime is %s</b>" % elapsedstring(time.time()-bot.starttime))
cmnds.add('uptime', handle_uptime, ['USER', 'GUEST'])
examples.add('uptime', 'show uptime of the bot', 'uptime')
## list command
def handle_available(bot, ievent):
""" show available plugins .. to enable use !reload. """
if ievent.rest: ievent.reply("%s plugin has the following commands: " % ievent.rest, whatcommands(ievent.rest))
else: ievent.reply("available plugins: ", getpluginlist(), raw=True) ; return
cmnds.add('list', handle_available, ['USER', 'GUEST'])
examples.add('list', 'list available plugins', 'list')
## commands command
def handle_commands(bot, ievent):
""" show commands of plugin. """
try: plugin = ievent.args[0].lower()
except IndexError: plugin = ""
result = []
cmnds = getcmndtable()
for cmnd, plugname in cmnds.iteritems():
if plugname:
if not plugin or plugin in plugname: result.append(cmnd)
if result:
result.sort()
if not plugin: plugin = "JSONBOT"
ievent.reply('%s has the following commands: ' % plugin, result)
else: ievent.reply('no commands found for plugin %s' % plugin)
cmnds.add('commands', handle_commands, ['USER', 'GUEST'])
examples.add('commands', 'show commands of <plugin>', '1) commands core')
## perm command
def handle_perm(bot, ievent):
""" get permission of command. """
try:cmnd = ievent.args[0]
except IndexError:
ievent.missing("<cmnd>")
return
try: perms = cmnds.perms(cmnd)
except KeyError:
ievent.reply("no %sw command registered")
return
if perms: ievent.reply("%s command needs %s permission" % (cmnd, perms))
else: ievent.reply("can't find perm for %s" % cmnd)
cmnds.add('perm', handle_perm, ['USER', 'GUEST'])
examples.add('perm', 'show permission of command', 'perm quit')
## version command
def handle_version(bot, ievent):
""" show bot's version. """
from jsb.version import getversion
ievent.reply(getversion(bot.type.upper()))
cmnds.add('version', handle_version, ['USER', 'GUEST'])
examples.add('version', 'show version of the bot', 'version')
## whereis command
def handle_whereis(bot, ievent):
""" locate a command. """
try: cmnd = ievent.args[0]
except IndexError:
ievent.missing('<cmnd>')
return
plugin = cmnds.whereis(cmnd)
if plugin: ievent.reply("%s command is in: %s" % (cmnd, plugin))
else: ievent.reply("can't find " + cmnd)
cmnds.add('whereis', handle_whereis, ['USER', 'GUEST'])
examples.add('whereis', 'whereis <cmnd> .. show in which plugins <what> is', 'whereis test')
## help-plug command
def handle_helpplug(bot, ievent):
""" how help on plugin/command or show basic help msg. """
try: what = ievent.args[0]
except (IndexError, TypeError):
ievent.reply("available plugins: ", getpluginlist())
ievent.reply("see !help <plugin> to get help on a plugin.")
return
plugin = None
modname = ""
perms = []
for package in plugin_packages:
try:
modname = "%s.%s" % (package, what)
try:
plugin = plugs.load(modname)
if plugin: break
except NoSuchPlugin: continue
except(KeyError, ImportError): pass
if not plugin:
ievent.reply("no %s plugin loaded" % what)
return
try: phelp = plugin.__doc__
except (KeyError, AttributeError):
ievent.reply('no description of %s plugin available' % what)
return
cmndresult = []
if phelp:
perms = ievent.user.data.perms
if not perms: perms = ['GUEST', ]
counter = 1
for i, j in cmnds.iteritems():
if what == j.plugname:
for perm in j.perms:
if perm in perms:
if True:
try:
descr = j.func.__doc__
if not descr: descr = "no description provided"
try: cmndresult.append(u" <b>!%s</b> - <i>%s</i> - examples: %s" % (i, descr, examples[i].example))
except KeyError: cmndresult.append(u" <b>!%s</b> - <i>%s</i> - no examples" % (i, descr))
except AttributeError: pass
counter += 1
break
if cmndresult and phelp:
res = []
for r in cmndresult:
if bot.type in ['web', ]: res.append("%s<br>" % r)
else: res.append(r)
res.sort()
what = what.upper()
res.insert(0, "%s\n" % phelp.strip())
ievent.reply('HELP ON %s \n\n' % what, res, dot="\n")
else:
if perms: ievent.reply('no commands available for permissions: %s' % ", ".join(perms))
else: ievent.reply("can't find help on %s" % what)
cmnds.add('help-plug', handle_helpplug, ['USER', 'GUEST'], how="msg")
examples.add('help-plug', 'get help on <cmnd> or <plugin>', '1) help-plug 2) help-plug misc')
## help command
def handle_help(bot, event):
""" help commands that gives a pointer to the docs and shows the __doc__ attribute. """
if event.rest:
target = cmnds.whereis(event.rest)
target = target or event.rest
where = bot.plugs.getmodule(target)
if where:
theplace = os.sep.join(where.split(".")[-2:])
event.reply("help for %s is at http://jsonbot.org/plugins/%s.html or http://jsonbot.appspot.com/docs/html/plugins/%s.html" % (event.rest.upper(), theplace, theplace))
else: event.reply("can't find a help url for %s" % event.rest)
else:
event.reply("documentation for jsonbot can be found at http://jsonbot.org or http://jsonbot.appspot.com/docs")
event.reply('see !list for loaded plugins and "!help plugin" for a url to the plugin docs.')
cmndhelp = cmnds.gethelp(event.rest)
if cmndhelp: event.reply("docstring: ", cmndhelp.split("\n"))
cmnds.add("help", handle_help, ["OPER", "USER", "GUEST"])
examples.add("help", "show url pointing to teh docs", "1) help 2) help rss")
## apro command
def handle_apro(bot, ievent):
""" apropos for command. """
try: what = ievent.args[0]
except IndexError:
ievent.missing('<what>')
return
result = []
cmnds = getcmndtable()
for i in cmnds.keys():
if what in i: result.append(i)
result.sort()
if result: ievent.reply("commands matching %s: " % what, result)
else: ievent.reply('no matching commands found for %s' % what)
cmnds.add('apro', handle_apro, ['USER', 'GUEST'])
examples.add('apro', 'apro <what> .. search for commands that contain <what>', 'apro com')
## whatcommands command
def handle_whatcommands(bot, ievent):
""" show all commands with permission. """
if not ievent.rest:
ievent.missing('<perm>')
return
result = cmnds
res = []
for cmnd in result.values():
if cmnd and cmnd.perms and ievent.rest in cmnd.perms:
res.append(cmnd.cmnd)
res.sort()
if not res: ievent.reply('no commands known for permission %s' % ievent.rest)
else: ievent.reply('commands known for permission %s: ' % ievent.rest, res)
cmnds.add('whatcommands', handle_whatcommands, ['USER', 'GUEST'])
examples.add('whatcommands', 'show commands with permission <perm>', 'whatcommands USER')
## versions command
def handle_versions(bot, ievent):
""" show versions of all loaded modules (if available). """
versions = {}
for mod in copy.copy(sys.modules):
try: versions[mod] = sys.modules[mod].__version__
except AttributeError, ex: pass
try: versions['python'] = sys.version
except AttributeError, ex: pass
ievent.reply("versions ==> %s" % unicode(versions))
cmnds.add('versions', handle_versions, ['USER', 'GUEST'])
examples.add('versions', 'show versions of all loaded modules', 'versions')
## loglevel command
def handle_loglevel(bot, event):
""" change loglevel of the bot. """
if not event.rest: event.reply("loglevel is %s" % getloglevel()) ; return
from jsb.lib.config import getmainconfig
mainconfig = getmainconfig()
mainconfig.loglevel = event.rest
mainconfig.save()
mainhandler.put(4, setloglevel, event.rest)
event.done()
cmnds.add("loglevel", handle_loglevel, "OPER")
examples.add("loglevel", "set loglevel ot on of debug, info, warning or error", "loglevel warn")
## threads command
def handle_threads(bot, ievent):
""" show running threads. """
try: import threading
except ImportError:
ievent.reply("threading is not enabled.")
return
stats = StatDict()
threadlist = threading.enumerate()
for thread in threadlist: stats.upitem(thread.getName())
result = []
for item in stats.top(): result.append("%s = %s" % (item[0], item[1]))
result.sort()
ievent.reply("threads running: ", result)
cmnds.add('threads', handle_threads, ['USER', 'GUEST'])
examples.add('threads', 'show running threads', 'threads')
## loaded command
def handle_loaded(bot, event):
""" show plugins in cache. """
event.reply("loaded plugins (cache): ", plugs.keys())
cmnds.add('loaded', handle_loaded, ['USER', 'GUEST'])
examples.add('loaded', 'show list of loaded plugins', 'loaded')
## statusline command
def handle_statusline(bot, event):
""" show a status line. """
event.how = "background"
event.reply("<b>controlchars:</b> %s - <b>perms:</b> %s" % (event.chan.data.cc, ", ".join(event.user.data.perms)))
cmnds.add('statusline', handle_statusline, ['USER', 'GUEST'])
examples.add('statusline', 'show status line', 'statusline')
## topper command
def handle_topper(bot, event):
""" show a 'topper' startus line. """
event.how = "background"
event.reply("<b>forwards:</b> %s - <b>watched:</b> %s - <b>feeds:</b> %s" % (", ".join(event.chan.data.forwards) or "none", ", ".join(event.chan.data.watched) or "none", ", ".join([unicode(x) for x in event.chan.data.feeds]) or "none"))
cmnds.add('topper', handle_topper, ['USER', 'GUEST'])
examples.add('topper', 'show topper line', 'topper')
## running command
def handle_running(bot, event):
""" show running tasks. """
event.how = "background"
event.reply("<b>callbacks:</b> %s - <b>commands:</b> %s - <b>longrunning:</b> %s" % (defaultrunner.running(), cmndrunner.running(), longrunner.running()))
cmnds.add('running', handle_running, ['USER', 'GUEST'])
examples.add('running', "show running tasks", "running")
| Python |
# jsb/plugs/core/gatekeeper.py
#
#
""" gatekeeper commands. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## gatekeeper-allow command
def handle_gatekeeperallow(bot, event):
""" allow user on bot. """
if not event.rest: event.missing("<userhost>") ; return
bot.gatekeeper.allow(event.rest)
event.done()
cmnds.add('gatekeeper-allow', handle_gatekeeperallow, 'OPER')
examples.add('gatekeeper-allow', 'add JID of remote bot that we allow to receice events from', 'gatekeeper-allow jsb@appspot.com')
## gatekeeper-deny command
def handle_gatekeeperdeny(bot, event):
""" deny user on bot. """
if not event.rest: event.missing("<userhost>") ; return
bot.gatekeeper.deny(event.rest)
event.done()
cmnds.add('gatekeeper-deny', handle_gatekeeperdeny, 'OPER')
examples.add('gatekeeper-deny', 'remove JID of remote bot', 'gatekeeper-deny evilfscker@pissof.com')
| Python |
# jsb/plugs/core/reverse.py
#
#
""" reverse pipeline or reverse <txt>. """
__copyright__ = 'this file is in the public domain'
__author__ = 'Hans van Kranenburg <hans@knorrie.org>'
## jsb imports
from jsb.utils.generic import waitforqueue
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
import types
## reverse command
def handle_reverse(bot, ievent):
""" reverse string or pipelined list. """
if not ievent.rest and ievent.inqueue: result = waitforqueue(ievent.inqueue, 5000)
elif not ievent.rest: ievent.missing('<text to reverse>') ; return
else: result = ievent.rest
if type(result) == types.ListType: ievent.reply("results: ", result[::-1])
else: ievent.reply(result[::-1])
cmnds.add('reverse', handle_reverse, ['OPER', 'USER', 'GUEST'])
examples.add('reverse', 'reverse text or pipeline', '1) reverse gozerbot 2) list ! reverse')
| Python |
# jsb/plugs/core/outputcache.py
#
#
""" outputcache used when reply cannot directly be delivered. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.outputcache import get, set, clear
from jsb.lib.callbacks import callbacks
from jsb.lib.examples import examples
## basic imports
import logging
## outputcache command
def handle_outputcache(bot, event):
""" forward the output cache to the user. """
res = get(event.channel)
logging.debug("outputcache - %s - %s" % (bot.type, len(res)))
if res:
for result in res[::-1]:
if result:
try: bot.saynocb(event.channel, result, event=event)
except Exception, ex: logging.error("outputcache - %s - %s" % (str(ex), result))
cmnds.add('outputcache', handle_outputcache, ['OPER', 'USER', 'GUEST'])
examples.add('outputcache', 'forward the outputcache to the user.', 'outputcache')
## outputcache-clear command
def handle_outputcacheclear(bot, event):
""" flush outputcache of a channel. """
clear(event.channel)
event.done()
cmnds.add('outputcache-clear', handle_outputcacheclear, ['OPER', 'USER', 'GUEST'])
examples.add('outputcache-clear', 'flush output cache of a channel', 'outputcache-clear')
| Python |
# jsb/plugs/core/underauth.py
#
#
""" handle non-ident connection on undernet. """
## copyright
__copyright__ = 'this file is in the public domain'
__author__ = 'aafshar@gmail.com'
## jsb imports
from jsb.lib.callbacks import callbacks
## pre_underauth_cb precondition
def pre_underauth_cb(bot, ievent):
"""
Only respond to the message like:
NOTICE AUTH :*** Your ident is disabled or broken, to continue
to connect you must type /QUOTE PASS 16188.
"""
args = ievent.arguments
try: return (args[0] == 'AUTH' and args[-3] == '/QUOTE' and args[-2] == 'PASS')
except Exception, ex: return False
## underauth_cb callback
def underauth_cb(bot, ievent):
""" Send the raw command to the server. """
bot._raw(' '.join(ievent.arguments[-2:]))
callbacks.add('NOTICE', underauth_cb, pre_underauth_cb)
| Python |
# jsb/plugs/core/uniq.py
#
#
""" used in a pipeline .. unique elements. """
__author__ = "Wijnand 'tehmaze' Modderman - http://tehmaze.com"
__license__ = 'BSD'
## jsb imports
from jsb.lib.examples import examples
from jsb.lib.commands import cmnds
from jsb.utils.generic import waitforqueue
## uniq command
def handle_uniq(bot, ievent):
""" uniq the result list """
if not ievent.inqueue:
ievent.reply('use uniq in a pipeline')
return
result = waitforqueue(ievent.inqueue, 3000)
if not result:
ievent.reply('no data')
return
result = list(result)
if not result: ievent.reply('no result')
else: ievent.reply("result: ", result)
cmnds.add('uniq', handle_uniq, ['OPER', 'USER', 'GUEST'])
examples.add('uniq', 'sort out multiple elements', 'list ! uniq')
| Python |
# jsb/plugs/core/alias.py
#
#
"""
this alias plugin allows aliases for commands to be added. aliases are in
the form of <alias> -> <command> .. aliases to aliases are not allowed,
aliases are per channel.
"""
## gozerbot imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
import os
## alias-search command
def handle_aliassearch(bot, ievent):
""" alias-search <what> .. search aliases. """
try: what = ievent.rest
except IndexError:
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
if cmnds.has_key(aliasfrom):
ievent.reply('command with same name already exists.')
return
aliases = ievent.chan.data.aliases
if not aliases: ievent.chan.data.aliases = aliases = {}
if aliases.has_key(aliasto):
ievent.reply("can't alias an alias")
return
ievent.chan.data.aliases[aliasfrom] = aliasto
ievent.chan.save()
ievent.reply('alias added')
cmnds.add('alias', handle_aliasset, 'USER', allowqueue=False)
examples.add('alias', 'alias <alias> <command> .. define alias', 'alias ll list')
## alias-makeglobal command
def handle_aliasmakeglobal(bot, ievent):
""" make channel aliases global. """
aliases = ievent.chan.data.aliases
if not aliases: ievent.chan.data.aliases = aliases = {}
from jsb.lib.aliases import getaliases
galiases = getaliases()
galiases.data.update(ievent.chan.data.aliases)
bot.aliases.data.update(ievent.chan.data.aliases)
galiases.save()
ievent.reply('global aliases updated')
cmnds.add('alias-makeglobal', handle_aliasmakeglobal, 'OPER', allowqueue=False)
examples.add('alias-makeglobal', 'push channel specific aliases into the global aliases', 'alias-makeglobal')
## alias-del command
def handle_delalias(bot, ievent):
""" delete alias. """
try: what = ievent.args[0]
except IndexError:
ievent.missing('<what>')
return
aliases = ievent.chan.data.aliases
try:
if aliases:
del aliases[what]
ievent.chan.save()
ievent.reply('alias deleted')
return
except KeyError: pass
ievent.reply('there is no %s alias' % what)
cmnds.add('alias-del', handle_delalias, 'USER')
examples.add('alias-del', 'alias-del <what> .. delete alias', 'alias-del ll')
## alias-get command
def handle_aliasget(bot, ievent):
""" aliases .. show aliases. (per user) """
aliases = ievent.chan.data.aliases
if aliases: ievent.reply("aliases: %s" % str(aliases))
else: ievent.reply("no aliases yet")
cmnds.add('alias-get', handle_aliasget, 'OPER')
examples.add('alias-get', 'aliases <what> .. get aliases', 'aliases')
| Python |
# jsb/plugs/common/echo.py
#
#
""" echo typed sentences. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.callbacks import callbacks, first_callbacks
## basic imports
import logging
## echo-callback
def echopre(bot, event):
""" test whether we should echo. """
if event.how != "background" and bot.type == "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, u"[%s] %s" % (event.nick, event.txt), event=event)
first_callbacks.add("DISPATCH", echocb, echopre)
## echo command
def handle_echo(bot, event):
""" echo txt to channel. """
if event.how != "background" and not event.iscmnd() and not event.isremote:
if not event.isdcc: bot.saynocb(event.channel, u"[%s] %s" % (event.nick, event.txt))
cmnds.add("echo", handle_echo, ['OPER', 'USER'])
examples.add("echo", "echo input", "echo yoooo dudes")
| Python |
# jsb/plugs/core/userstate.py
#
#
""" userstate is stored in jsondata/state/users/<username>. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persiststate import UserState
from jsb.lib.errors import NoSuchUser
## 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)
cmnds.add('get', handle_get, ['OPER', 'USER', 'GUEST'])
examples.add('get', 'get your userstate', 'get')
## unset command
def handle_unset(bot, ievent):
""" remove value from user state of the user giving the command. """
try:
item = ievent.args[0].lower()
except (IndexError, TypeError):
ievent.missing('<item>')
return
try: del ievent.user.state.data[item]
except KeyError:
ievent.reply('no such item')
return
ievent.user.state.save()
ievent.reply('item %s deleted' % item)
cmnds.add('unset', handle_unset, ['USER', 'GUEST'])
examples.add('unset', 'delete variable from your state', 'unset TZ')
| Python |
# jsb/plugs/core/nickcapture.py
#
#
""" nick recapture callback. """
## jsb imports
from jsb.lib.callbacks import callbacks
## callbacks
def ncaptest(bot, ievent):
""" test if user is splitted. """
if '*.' in ievent.txt or bot.cfg.server in ievent.txt: return 0
if ievent.chan.data.wantnick and ievent.chan.data.wantnick.lower() == ievent.nick.lower(): return 1
if bot.cfg.nick.lower() == ievent.nick.lower(): return 1
return 0
def ncap(bot, ievent):
""" recapture the nick. """
bot.donick(ievent.chan.data.wantnick or bot.cfg.nick)
callbacks.add('QUIT', ncap, ncaptest, threaded=True)
| Python |
# jsb/plugs/core/irc.py
#
#
""" irc related commands. """
## jsb imports
from jsb.lib.callbacks import callbacks
from jsb.lib.partyline import partyline
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.fleet import getfleet
from jsb.lib.wait import waiter
import jsb.lib.threads as thr
## basic imports
import Queue
import sets
import time
## define
ignorenicks = []
## broadcast command
def handle_broadcast(bot, ievent):
""" broadcast txt to all joined channels. """
if not ievent.rest:
ievent.missing('<txt>')
return
ievent.reply('broadcasting')
getfleet().broadcast(ievent.rest)
partyline.say_broadcast(ievent.rest)
ievent.reply('done')
cmnds.add('broadcast', handle_broadcast, 'OPER')
examples.add('broadcast', 'send a message to all channels and dcc users', 'broadcast good morning')
## jump command
def handle_jump(bot, ievent):
""" change server. """
if bot.jabber:
ievent.reply('jump only works on irc bots')
return
if len(ievent.args) != 2:
ievent.missing('<server> <port>')
return
(server, port) = ievent.args
ievent.reply('changing to server %s' % server)
bot.shutdown()
bot.cfg.server = server
bot.cfg.port = port
bot.connect()
ievent.done()
cmnds.add('jump', handle_jump, 'OPER')
examples.add('jump', 'jump <server> <port> .. switch server', 'jump localhost 6667')
## nick command
def handle_nick(bot, ievent):
""" change bot's nick. """
if bot.jabber:
ievent.reply('nick works only on irc bots')
return
try: nick = ievent.args[0]
except IndexError:
ievent.missing('<nickname>')
return
ievent.reply('changing nick to %s' % nick)
bot.donick(nick, setorig=True, save=True)
ievent.done()
cmnds.add('nick', handle_nick, 'OPER', threaded=True)
examples.add('nick', 'nick <nickname> .. set nick of the bot', 'nick mekker')
## sendraw command
def handle_sendraw(bot, ievent):
""" send raw text to the server. """
ievent.reply('sending raw txt')
bot._raw(ievent.rest)
ievent.done()
cmnds.add('sendraw', handle_sendraw, ['OPER', 'SENDRAW'])
examples.add('sendraw', 'sendraw <txt> .. send raw string to the server', 'sendraw PRIVMSG #test :yo!')
## nicks command
nickresult = []
def handle_nicks(bot, event):
""" return nicks on channel. """
if bot.type != 'irc': event.reply('nicks only works on irc bots') ; return
def aggregate(bot, e):
global nickresult
nickresult.extend(e.txt.split())
def nickscb(bot, e):
global nickresult
event.reply("nicks on %s (%s): " % (event.channel, bot.cfg.server), nickresult)
nickresult = []
waiter.remove("jsb.plugs.core.irc")
w353 = waiter.register('353', aggregate)
w366 = waiter.register('366', nickscb)
event.reply('searching for nicks')
bot.names(event.channel)
time.sleep(5)
waiter.ready(w353)
waiter.ready(w366)
cmnds.add('nicks', handle_nicks, ['OPER', 'USER'], threaded=True)
examples.add('nicks', 'show nicks on channel the command was given in', 'nicks')
## reconnect command
def handle_reconnect(bot, ievent):
""" reconnect .. reconnect to server. """
ievent.reply('reconnecting')
bot.reconnect()
ievent.done()
cmnds.add('reconnect', handle_reconnect, 'OPER', threaded=True)
examples.add('reconnect', 'reconnect to server', 'reconnect')
## action command
def handle_action(bot, ievent):
""" make the bot send an action string. """
try: channel, txt = ievent.rest.split(' ', 1)
except ValueError:
ievent.missing('<channel> <txt>')
return
bot.action(channel, txt)
cmnds.add('action', handle_action, ['ACTION', 'OPER'])
examples.add('action', 'send an action message', 'action #test yoo dudes')
## say command
def handle_say(bot, ievent):
""" <channel> <txt> .. make the bot say something. """
try: channel, txt = ievent.rest.split(' ', 1)
except ValueError:
ievent.missing('<channel> <txt>')
return
bot.say(channel, txt)
cmnds.add('say', handle_say, ['SAY', 'OPER'], speed=1)
examples.add('say', 'send txt to channel/user', 'say #test good morning')
## server command
def handle_server(bot, ievent):
""" show the server to which the bot is connected. """
ievent.reply(bot.cfg.server or "not connected.")
cmnds.add('server', handle_server, 'OPER')
examples.add('server', 'show server hostname of bot', 'server')
## voice command
def handle_voice(bot, ievent):
""" <nick> .. give voice. """
if bot.type != 'irc':
ievent.reply('voice only works on irc bots')
return
if len(ievent.args)==0:
ievent.missing('<nickname>')
return
ievent.reply('setting voide on %s' % str(ievent.args))
for nick in sets.Set(ievent.args): bot.voice(ievent.channel, nick)
ievent.done()
cmnds.add('voice', handle_voice, 'OPER')
examples.add('voice', 'give voice to user', 'voice test')
| Python |
# jsb/plugs/core/more.py
#
#
""" access the output cache. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.less import outcache
## basic imports
import logging
## more command
def handle_more(bot, ievent):
""" pop message from the output cache. """
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')
| Python |
# jsb/plugs/core/tail.py
#
#
""" 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):
""" used in a pipeline .. show last <nr> elements. """
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')
| Python |
# jsb/plugs/core/dispatch.py
#
#
""" this is the dispatch plugin that dispatches events to commands. """
## jsb imports
from jsb.lib.callbacks import last_callbacks
from jsb.lib.errors import NoSuchCommand, NoSuchUser
## basic logging
import logging
import copy
## defines
cpy = copy.deepcopy
## dispatch-precondition
def predispatch(bot, event):
""" check whether we should check for commands. """
if event.status == "done": logging.debug("dispatch - event is done .. ignoring") ; return
if event.isremote(): logging.debug("dispatch - event is remote .. not dispatching") ; return
#if event.isrelayed: logging.debug("dispatch - event is relayed .. not dispatching") ; return
return True
## dispatch-callback
def dispatch(bot, event):
""" dispatch an event. """
logging.info("dispatch - doing event %s" % event.dump())
if event.userhost in bot.ignore: logging.warn("%s - ignore on %s" % (bot.name, event.userhost)) ; return
if event.nodispatch:
logging.debug("dispatch - nodispatch option is set - ignoring %s" % event.userhost)
return
bot.status = "dispatch"
if not event.bonded: event.bind(bot)
bot.curevent = event
go = False
execstr = event.iscmnd()
logging.debug("dispatch - execstr is %s" % execstr)
try:
if execstr:
event.iscommand = True
event.dontclose = True
e = cpy(event)
e.bind(bot)
e.usercmnd = execstr.split()[0]
e.txt = execstr
e.showexception = True
if not e.options: e.makeoptions()
e.bind(bot)
if event.chan and e.usercmnd in event.chan.data.silentcommands: e.silent = True
result = bot.plugs.dispatch(bot, e)
else:
logging.debug("dispatch - no go for %s (cc is %s)" % (event.auth or event.userhost, execstr))
result = None
except NoSuchUser, ex: logging.error("no such user: %s" % str(ex)) ; result = None
except NoSuchCommand: logging.info("no such command: %s" % event.usercmnd) ; result = None
return result
## register callback
last_callbacks.add('PRIVMSG', dispatch, predispatch)
last_callbacks.add('MESSAGE', dispatch, predispatch)
last_callbacks.add('BLIP_SUBMITTED', dispatch, predispatch)
last_callbacks.add('WEB', dispatch, predispatch)
last_callbacks.add('CONSOLE', dispatch, predispatch)
last_callbacks.add('DCC', dispatch, predispatch)
last_callbacks.add('DISPATCH', dispatch, predispatch)
last_callbacks.add('CMND', dispatch, predispatch)
last_callbacks.add('CONVORE', dispatch, predispatch)
| Python |
# jsb/plugs/core/test.py
# encoding: utf-8
#
#
""" test plugin. """
from jsb.utils.exception import exceptionmsg, handle_exception, exceptionevents, exceptionlist
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.eventbase import EventBase
from jsb.lib.users import users
from jsb.lib.threads import start_new_thread
from jsb.utils.generic import waitforqueue, waitevents
from jsb.lib.runner import cmndrunner, defaultrunner
## basic imports
import time
import random
import copy
import logging
## defines
cpy = copy.deepcopy
donot = ['whatis', 'urlinfo', 'privmsg', 'notice', 'disable', 'deadline', 'twitter', 'stop', 'admin', 'quit', 'reboot', 'shutdown', 'exit', 'delete', 'halt', 'upgrade', \
'install', 'reconnect', 'wiki', 'weather', 'sc', 'jump', 'disable', 'dict', \
'snarf', 'validate', 'popcon', 'twitter', 'tinyurl', 'whois', 'rblcheck', \
'wowwiki', 'wikipedia', 'tr', 'translate', 'serie', 'sc', 'shoutcast', 'mash', \
'gcalc', 'identi', 'mail', 'part', 'cycle', 'exception', 'fleet', 'ln', 'markov-learn', 'pit', 'bugtracker', 'tu', 'banner', 'test', 'cloud', 'dispatch', 'lns', 'loglevel', \
'cloneurl', 'clone', 'hb', 'rss-all', 'rss-get', 'rss-sync', 'rss-add', 'rss-register', 'rss-cloneurl', 'rss-scan']
errors = {}
teller = 0
def dummy(a, b=None):
return ""
## dotest function
def dotest(bot, event):
global teller
global errors
match = ""
waiting = []
if True:
examplez = examples.getexamples()
random.shuffle(examplez)
for example in examplez:
time.sleep(0.001)
if match and match not in example: continue
skip = False
for dont in donot:
if dont in example: skip = True
if skip: continue
teller += 1
cmnd = "!" + example.strip()
event.reply('command: ' + cmnd)
time.sleep(0.001)
bot.putevent(event.userhost, event.channel, cmnd, event=event)
if not bot.isgae: waiting.append(event)
teller += 1
event.reply("%s commands executed" % teller)
if errors:
event.reply("there are %s errors .. " % len(errors))
for cmnd, error in errors.iteritems(): event.reply("%s - %s" % (cmnd, error))
for (event, msg) in exceptionevents: event.reply("EXCEPTION: %s - %s" % (event.txt,msg))
for msg in exceptionlist: event.reply("EXCEPTION: %s" % msg)
## test-plugs command
def handle_testplugs(bot, event):
""" test the plugins by executing all the available examples. """
bot.plugs.loadall(force=True)
global teller
try: loop = int(event.args[0])
except (ValueError, IndexError): loop = 1
try: threaded = event.args[1]
except (ValueError, IndexError): threaded = 0
threads = []
teller = 0
#event.dontclose = True
for i in range(loop):
if threaded: threads.append(start_new_thread(dotest, (bot, event)))
else: dotest(bot, event)
if threads:
for thread in threads: thread.join()
event.reply('%s tests run' % teller)
if errors:
event.reply("there are %s errors .. " % len(errors))
for cmnd, error in errors.iteritems(): event.reply("%s - %s" % (cmnd, error))
else: event.reply("no errors")
event.outqueue.put_nowait(None)
cmnds.add('test-plugs', handle_testplugs, ['TEST', ], threaded=True)
examples.add('test-plugs', 'test all plugins by running there examples', 'test-plugs')
## test-forcedconnection command
def handle_forcedreconnect(bot, ievent):
""" do a forced reconnect. """
if not bot.cfg.ssl: bot.sock.shutdown(2)
else: bot.sock.shutdown()
cmnds.add('test-forcedreconnect', handle_forcedreconnect, 'TEST')
## test-forcedexception command
def handle_forcedexception(bot, ievent):
""" raise a exception. """
raise Exception('test exception')
cmnds.add('test-forcedexception', handle_forcedexception, 'TEST')
examples.add('test-forcedexception', 'throw an exception as test', 'test-forcedexception')
## test-wrongxml command
def handle_testwrongxml(bot, ievent):
""" try sending borked xml. """
if not bot.type == "sxmpp":
ievent.reply('only sxmpp')
return
ievent.reply('sending bork xml')
bot._raw('<message asdfadf/>')
cmnds.add('test-wrongxml', handle_testwrongxml, 'TEST')
## test-unicode command
def handle_testunicode(bot, ievent):
""" send unicode test down the output paths. """
outtxt = u"Đíť ìš éèñ ëņċøďıńğŧęŝţ· .. にほんごがはなせません .. ₀0⁰₁1¹₂2²₃3³₄4⁴₅5⁵₆6⁶₇7⁷₈8⁸₉9⁹ .. ▁▂▃▄▅▆▇▉▇▆▅▄▃▂▁ .. .. uǝʌoqǝʇsɹǝpuo pɐdı ǝɾ ʇpnoɥ ǝɾ"
ievent.reply(outtxt)
bot.say(ievent.channel, outtxt, event=ievent)
cmnds.add('test-unicode', handle_testunicode, 'TEST')
examples.add('test-unicode', 'test if unicode output path is clear', 'test-unicode')
## test-docmnd command
def handle_testdocmnd(bot, ievent):
""" call bot.docmnd(). """
if ievent.rest: bot.docmnd(ievent.origin or ievent.userhost, ievent.channel, ievent.rest, event=ievent)
else: ievent.missing("<cmnd>")
cmnds.add('test-docmnd', handle_testdocmnd, 'TEST')
examples.add('test-docmnd', 'test the bot.docmnd() method', 'test-docmnd version')
## test-say command
def handle_testsay(bot, ievent):
if not ievent.rest:
ievent.missing("<txt>")
return
bot.say(ievent.printto, ievent.rest)
cmnds.add('test-say', handle_testsay, 'TEST')
examples.add('test-say', 'use bot.say()', 'test-say')
## test-options command
def handle_testoptions(bot, ievent):
ievent.reply('"%s" - %s' % (ievent.txt, unicode(ievent.options)))
cmnds.add('test-options', handle_testoptions, 'TEST')
examples.add('test-options', "test event options", "test-options")
## test-deadline command
def handle_testdeadline(bot, ievent):
ievent.reply('starting 40 sec sleep')
time.sleep(40)
cmnds.add('test-deadline', handle_testdeadline, 'TEST')
examples.add('test-deadline', "sleep 40 sec to trigger deadlineexceeded exception (GAE)", "test-deadline")
## test-xhtml command
def handle_testhtml(bot, ievent):
if not ievent.rest: data = '<span style="font-family: fixed; font-size: 10pt"><b>YOOOO BROEDERS</b></span>'
else: data = ievent.rest
ievent.reply(data, html=True)
cmnds.add('test-html', handle_testhtml, 'TEST')
examples.add('test-html', 'test html output', '1) test-html 2) test-html <h1><YOO</h1>')
## test-uuid command
def handle_testuuid(bot, ievent):
""" show a uuid4. """
import uuid
ievent.reply(str(uuid.uuid4()))
cmnds.add('test-uuid', handle_testuuid, 'TEST')
examples.add("test-uuid", "show a uuid4.", "test-uuid")
## test-threaded command
def handle_testthreaded(bot, ievent):
""" run a threaded command. """
ievent.reply("yoooo!")
cmnds.add("test-threaded", handle_testthreaded, "TEST", threaded=True)
examples.add("test-threaded", "run a threaded command.", "test-threaded")
| Python |
# jsb/plugs/core/choice.py
#
#
""" the choice command can be used with a string or in a pipeline. """
## jsb imports
from jsb.utils.generic import waitforqueue
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
import random
## choice command
def handle_choice(bot, ievent):
""" make a random choice out of different words or list elements. """
result = []
if ievent.args: result = ievent.args
elif ievent.inqueue: result = waitforqueue(ievent.inqueue, 3000)
else: ievent.missing('<space seperated list>') ; return
if result: ievent.reply(random.choice(result))
else: ievent.reply('nothing to choose from: %s' % ievent.txt)
cmnds.add('choice', handle_choice, ['OPER', 'USER', 'GUEST'])
examples.add('choice', 'make a random choice', '1) choice a b c 2) list ! choice')
| Python |
# jsb/plugs/core/fleet.py
#
#
"""
The fleet makes it possible to run multiple bots in one running instance.
It is a list of bots. This plugin provides commands to manipulate this list of bots.
"""
## jsb imports
from jsb.lib.config import Config
from jsb.lib.threads import start_new_thread
from jsb.lib.fleet import getfleet, FleetBotAlreadyExists
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.name import stripname
from jsb.utils.generic import waitforqueue
## basic imports
import os
## fleet-avail command
def handle_fleetavail(bot, ievent):
""" show available fleet bots. """
ievent.reply('available bots: ', getfleet().avail())
cmnds.add('fleet-avail', handle_fleetavail, 'OPER')
examples.add('fleet-avail', 'show available fleet bots', 'fleet-avail')
## fleet-connect command
def handle_fleetconnect(bot, ievent):
""" connect a fleet bot to it's server. """
try: botname = ievent.args[0]
except IndexError:
ievent.missing('<botname>')
return
try:
fleet = getfleet()
fleetbot = fleet.byname(botname)
if fleetbot:
start_new_thread(fleetbot.connect, ())
ievent.reply('%s connect thread started' % botname)
else:
ievent.reply("can't connect %s .. trying enable" % botname)
cfg = Config('fleet' + os.sep + stripname(botname) + os.sep + 'config')
cfg['disable'] = 0
if not cfg.name: cfg.name = botname
cfg.save()
bot = fleet.makebot(cfg.type, cfg.name, cfg)
if bot:
ievent.reply('enabled and started %s bot' % botname)
start_new_thread(bot.start, ())
else: ievent.reply("can't make %s bot" % cfg.name)
except Exception, ex:
ievent.reply(str(ex))
cmnds.add('fleet-connect', handle_fleetconnect, 'OPER', threaded=True)
examples.add('fleet-connect', 'connect bot with <name> to irc server', 'fleet-connect test')
## fleet-disconnect command
def handle_fleetdisconnect(bot, ievent):
""" disconnect a fleet bot from server. """
try: botname = ievent.args[0]
except IndexError:
ievent.missing('<botname>')
return
ievent.reply('exiting %s' % botname)
try:
fleet = getfleet()
if fleet.exit(botname): ievent.reply("%s bot stopped" % botname)
else: ievent.reply("can't stop %s bot" % botname)
except Exception, ex: ievent.reply("fleet - %s" % str(ex))
cmnds.add('fleet-disconnect', handle_fleetdisconnect, 'OPER', threaded=True)
examples.add('fleet-disconnect', 'fleet-disconnect <name> .. disconnect bot with <name> from irc server', 'fleet-disconnect test')
## fleet-list command
def handle_fleetlist(bot, ievent):
""" fleet-list .. list bot names in fleet. """
ievent.reply("fleet: ", getfleet().list())
cmnds.add('fleet-list', handle_fleetlist, ['OPER', 'USER', 'GUEST'])
examples.add('fleet-list', 'show current fleet list', 'fleet-list')
## fleet-del command
def handle_fleetdel(bot, ievent):
""" delete bot from fleet. """
try: name = ievent.args[0]
except IndexError:
ievent.missing('<name>')
return
try:
if getfleet().delete(name): ievent.reply('%s deleted' % name)
else: ievent.reply('%s delete failed' % name)
except Exception, ex: ievent.reply(str(ex))
cmnds.add('fleet-del', handle_fleetdel, 'OPER', threaded=True)
examples.add('fleet-del', 'fleet-del <botname> .. delete bot from fleet list', 'fleet-del test')
## fleet-disable command
def fleet_disable(bot, ievent):
""" disable a fleet bot. """
if not ievent.rest:
ievent.missing("list of fleet bots")
return
bots = ievent.rest.split()
fleet = getfleet()
for name in bots:
bot = fleet.byname(name)
if bot:
bot.cfg['enable'] = 0
bot.cfg.save()
ievent.reply('disabled %s' % name)
fleet.exit(name)
else: ievent.reply("can't find %s bot in fleet" % name)
cmnds.add('fleet-disable', fleet_disable, 'OPER')
examples.add('fleet-disable', 'disable a fleet bot', 'fleet-disable local')
## fleet-enable command
def fleet_enable(bot, ievent):
""" enable a fleet bot. """
if not ievent.rest:
ievent.missing("list of fleet bots")
return
bots = ievent.rest.split()
fleet = getfleet()
for name in bots:
bot = fleet.byname(name)
if bot:
bot.cfg.load()
bot.cfg['disable'] = 0
if not bot.cfg.name: bot.cfg.name = name
bot.cfg.save()
ievent.reply('enabled %s' % name)
start_new_thread(bot.connect, ())
elif name in fleet.avail():
cfg = Config('fleet' + os.sep + stripname(name) + os.sep + 'config')
cfg['disable'] = 0
if not cfg.name: cfg.name = name
cfg.save()
bot = fleet.makebot(cfg.type, cfg.name, cfg)
if not bot: ievent.reply("can't make %s bot - %s" % (cfg.name, cfg.type)) ; return
ievent.reply('enabled and started %s bot' % name)
start_new_thread(bot.start, ())
else: ievent.reply('no %s bot in fleet' % name)
cmnds.add('fleet-enable', fleet_enable, 'OPER', threaded=True)
examples.add('fleet-enable', 'enable a fleet bot', 'fleet-enable local')
## fleet-add command
def fleet_add(bot, ievent):
""" add a fleet bot. """
try:
name, type, server, nick = ievent.rest.split()
except ValueError: ievent.missing("<name> <type> <server>|<botjid> <nick>|<passwd>") ; return
bots = ievent.rest.split()
fleet = getfleet()
bot = fleet.byname(name)
if bot: event.reply("%s bot already exists" % name) ; return
cfg = Config('fleet' + os.sep + stripname(name) + os.sep + 'config')
cfg.disable = 0
if type == "irc":
cfg.port = 6667
cfg.server = server
cfg.nick = nick
elif type in ["xmpp", "sxmpp"]:
cfg.port = 4442
cfg.host = server
try: n, serv = cfg.host.split("@")
except (ValueError, TypeError): pass
cfg.server = serv
cfg.password = nick
cfg.save()
bot = fleet.makebot(type, name, cfg)
if bot:
ievent.reply('enabled and started %s bot - %s' % (name, cfg.filename))
start_new_thread(bot.start, ())
else: ievent.reply("can't make %s bot" % cfg.name)
cmnds.add('fleet-add', fleet_add, 'OPER', threaded=True)
examples.add('fleet-add', 'add a fleet bot', 'fleet-add local irc localhost jsbtest')
## fleet-cmnd command
def fleet_cmnd(bot, ievent):
""" do cmnd on fleet bot(s). """
try:
(name, cmndtxt) = ievent.rest.split(' ', 1)
except ValueError: ievent.missing("<name> <cmndstring>") ; return
fleet = getfleet()
if name == "all": do = fleet.list()
else: do = [name, ]
for botname in do:
bot = fleet.byname(botname)
if not bot: ievent.reply("%s bot is not in fleet" % botname) ; return
result = bot.docmnd(ievent.userhost, ievent.channel, cmndtxt, wait=1, nooutput=True)
if result: res = waitforqueue(result.outqueue, 60000)
else: ievent.reply("no result")
ievent.reply("[%s] %s" % (botname, ", ".join(res)))
ievent.reply("done")
cmnds.add('fleet-cmnd', fleet_cmnd, 'OPER', threaded=True)
examples.add('fleet-cmnd', 'run cmnd on fleet bot(s)', '1) fleet-cmnd default-irc uptime 2) fleet-cmnd all uptime')
| Python |
# jsb/plugs/core/to.py
#
#
""" send output to another user .. used in a pipeline. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.utils.generic import getwho, waitforqueue
from jsb.lib.examples import examples
## to command
def handle_to(bot, ievent):
""" direct pipeline output to <nick>. """
if not ievent.inqueue: ievent.reply('use to in a pipeline') ; return
try: nick = ievent.args[0]
except IndexError: ievent.reply('to <nick>') ; return
if nick == 'me': nick = ievent.nick
if not getwho(bot, nick): ievent.reply("don't know %s" % nick) ; return
result = waitforqueue(ievent.inqueue, 5000)
if result:
bot.say(nick, "%s sends you this:" % ievent.nick)
bot.say(nick, " ".join(result))
if len(result) == 1: ievent.reply('1 element sent')
else: ievent.reply('%s elements sent' % len(result))
else: ievent.reply('nothing to send')
cmnds.add('to', handle_to, ['OPER', 'USER', 'TO'])
examples.add('to', 'send pipeline output to another user', 'list ! to dunker')
| Python |
# jsb/plugs/core.admin.py
#
#
""" admin related commands. these commands are mainly for maintaining the bot. """
## jsb imports
from jsb.lib.eventhandler import mainhandler
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
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.lib.config import getmainconfig
from jsb.utils.generic import stringsed
from jsb.utils.exception import handle_exception
## basic imports
import logging
## 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 command
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 command
def handle_admincallbacks(bot, ievent):
""" load all available plugins. """
cbs = getcallbacktable()
if not ievent.rest: ievent.reply("callbacks: ", cbs)
else:
try: ievent.reply("%s callbacks: " % ievent.rest, cbs[ievent.rest])
except KeyError: ievent.reply("no such callbacks available")
cmnds.add('admin-callbacks', handle_admincallbacks, 'OPER')
examples.add('admin-callbacks', 'show runtime callback table', 'admin-callbacks')
## admin-loadall command
def handle_loadall(bot, ievent):
""" load all available plugins. """
plugs.loadall(plugin_packages, force=True)
ievent.done()
cmnds.add('admin-loadall', handle_loadall, 'OPER', threaded=True)
examples.add('admin-loadall', 'load all plugins', 'admin-loadall')
## admin-makebot command
def handle_adminmakebot(bot, ievent):
""" create a bot of given type. """
try: botname, bottype = ievent.args
except ValueError: ievent.missing("<name> <type>") ; return
newbot = BotBase()
newbot.botname = botname
newbot.type = bottype
newbot.owner = bot.owner
newbot.save()
ievent.done()
cmnds.add('admin-makebot', handle_adminmakebot, 'OPER')
examples.add('admin-makebot', 'create a bot', 'admin-makebot cmndxmpp xmpp')
## admin-stop command
def handle_adminstop(bot, ievent):
if bot.isgae: ievent.reply("this command doesn't work on the GAE") ; return
mainhandler.put(0, globalshutdown)
cmnds.add("admin-stop", handle_adminstop, "OPER")
examples.add("admin-stop", "stop the bot.", "stop")
## admin-upgrade command
def handle_adminupgrade(bot, event):
if not bot.isgae: event.reply("this command only works in GAE") ; return
else: import google
from jsb.lib.persist import JSONindb
teller = 0
props = JSONindb.properties()
for d in JSONindb.all():
try:
dd = d.filename
if not "gozerdata" in dd: continue
if 'run' in dd: continue
ddd = stringsed(dd, "s/%s/%s/" % ("gozerdata", "data"))
ddd = stringsed(ddd, "s/waveplugs/jsb.plugs.wave/")
ddd = stringsed(ddd, "s/gozerlib\.plugs/jsb.plugs.core/")
ddd = stringsed(ddd, "s/commonplugs/jsb.plugs.common/")
ddd = stringsed(ddd, "s/socketplugs/jsb.plugs.socket/")
ddd = stringsed(ddd, "s/gaeplugs/jsb.plugs.gae/")
if d.get_by_key_name(ddd): continue
d.filename = ddd
kwds = {}
for prop in props: kwds[prop] = getattr(d, prop)
d.get_or_insert(ddd, **kwds)
bot.say(event.channel, "UPGRADED %s" % ddd)
teller += 1
except Exception, ex: bot.say(event.channel, str(ex))
bot.say(event.channel, "DONE - upgraded %s items" % teller)
cmnds.add("admin-upgrade", handle_adminupgrade, "OPER", threaded=True)
examples.add("admin-upgrade", "upgrade the GAE bot", "admin-upgrade")
## admin-setstatus command
def handle_adminsetstatus(bot, event):
if bot.type != "sxmpp": event.reply("this command only works on sxmpp bots (for now)") ; return
if not event.rest: event.missing("<status> [<show>]") ; return
status = event.args[0]
try: show = event.args[1]
except IndexError: show = ""
bot.setstatus(status, show)
cmnds.add("admin-setstatus", handle_adminsetstatus, ["STATUS", "OPER"])
examples.add("admin-setstatus", "set status of sxmpp bot", "admin-setstatus available Yooo dudes !")
## admin-reloadconfig command
def handle_adminreloadconfig(bot, event):
try:
#bot.cfg.reload()
getmainconfig().reload()
except Exception, ex: handle_exception()
event.done()
cmnds.add("admin-reloadconfig", handle_adminreloadconfig, ["OPER"])
examples.add("admin-reloadconfig", "reload mainconfig", "admin-reloadconfig")
def handle_adminexceptions(bot, event):
from jsb.utils.exception import exceptionlist, exceptionevents
for e, ex in exceptionevents: logging.warn("%s - exceptions raised is %s" % (e.bot.cfg.name, ex))
event.reply("exceptions raised: ", exceptionlist)
cmnds.add("admin-exceptions", handle_adminexceptions, ["OPER"])
examples.add("admin-exceptions", "show exceptions raised", "admin-exceptions")
| Python |
# jsb/plugs/core/misc.py
#
#
""" misc commands. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persiststate import UserState
## basic imports
import time
import os
import threading
import thread
import copy
## defines
cpy = copy.deepcopy
## test command
def handle_test(bot, ievent):
""" give test response. """
ievent.reply("%s (%s) - %s - it works!" % (ievent.auth or ievent.userhost, ievent.nick, ievent.user.data.name))
cmnds.add('test', handle_test, ['USER', 'GUEST'])
examples.add('test', 'give test response',' test')
## source command
def handle_source(bot, ievent):
""" show where to fetch the bot source. """
ievent.reply('see http://jsonbot.googlecode.com')
cmnds.add('source', handle_source, ['USER', 'GUEST'])
examples.add('source', 'show source url', 'source')
| Python |
# jsb/plugs/core/xmpp.py
#
#
""" xmpp related commands. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.fleet import getfleet
## xmpp-invite command
def handle_xmppinvite(bot, event):
""" invite (subscribe to) a different user. """
if not event.rest:
event.missing("<list of jids>")
return
bot = getfleet().getfirstjabber()
if bot:
for jid in event.args: bot.invite(jid)
event.done()
else: event.reply("can't find jabber bot in fleet")
cmnds.add("xmpp-invite", handle_xmppinvite, 'OPER')
examples.add("xmpp-invite", "invite a user.", "xmpp-invite jsoncloud@appspot.com")
| Python |
# jsb/plugs/core/remotecallbacks.py
#
#
""" dispatch remote events. """
## jsb imports
from jsb.utils.lazydict import LazyDict
from jsb.utils.generic import fromenc
from jsb.utils.exception import handle_exception
from jsb.lib.callbacks import callbacks, remote_callbacks, first_callbacks
from jsb.lib.container import Container
from jsb.lib.eventbase import EventBase
from jsb.lib.errors import NoProperDigest
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.contrib.xmlstream import NodeBuilder, XMLescape, XMLunescape
## basic imports
import logging
import copy
import hmac
import hashlib
import cgi
## defines
cpy = copy.deepcopy
## callback
def remotecb(bot, event):
""" dispatch an event. """
try: container = Container().load(event.txt)
except TypeError:
handle_exception()
logging.warn("remotecallbacks - not a remote event - %s " % event.userhost)
return
logging.debug('doing REMOTE callback')
try:
digest = hmac.new(str(container.hashkey), XMLunescape(container.payload), hashlib.sha512).hexdigest()
logging.debug("remotecallbacks - digest is %s" % digest)
except TypeError:
handle_exception()
logging.error("remotecallbacks - can't load payload - %s" % container.payload)
return
if container.digest == digest: e = EventBase().load(XMLunescape(container.payload))
else: raise NoProperDigest()
e.txt = XMLunescape(e.txt)
e.nodispatch = True
e.forwarded = True
bot.doevent(e)
event.status = "done"
return
remote_callbacks.add("MESSAGE", remotecb)
| Python |
# jsb/plugs/core/not.py
#
#
""" negative grep. """
## jsb imports
from jsb.lib.examples import examples
from jsb.lib.commands import cmnds
from jsb.utils.generic import waitforqueue
## basic imports
import getopt
import re
## not command
def handle_not(bot, ievent):
""" negative grep. """
if not ievent.inqueue:
ievent.reply('use not in a pipeline')
return
if not ievent.rest:
ievent.reply('not <txt>')
return
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, ['OPER', 'USER', 'GUEST'])
examples.add('not', 'reverse grep used in pipelines', 'list ! not todo')
| Python |
# jsb/plugs/core/chan.py
#
#
""" channel related commands. """
## jsb imports
from jsb.lib.persist import Persist
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.callbacks import callbacks
from jsb.lib.channelbase import ChannelBase
from jsb.lib.datadir import getdatadir
from jsb.utils.exception import handle_exception
## basic imports
import os
import logging
## chan-token command
def handle_chantoken(bot, event):
""" request a token for the channel. used in channel API on GAE. """
if not bot.isgae: event.reply("this command only works on the App Engine") ; return
import google
try:
(chan, token) = event.chan.gae_create()
logging.warn("chantoken - %s - %s" % (chan, token))
event.response.out.write(token)
except google.appengine.runtime.DeadlineExceededError:
event.response.out.write("DeadLineExceededError .. this request took too long to finish.")
except Exception, ex:
event.response.out.write("An exception occured: %s" % str(ex))
handle_exception()
cmnds.add("chan-token", handle_chantoken, ['OPER', 'USER', "GUEST"])
examples.add("chan-token", "create a new token for the appengine channel API", "chan-token")
## chan-join command
def handle_chanjoin(bot, ievent):
""" join a channel/wave"""
try: channel = ievent.args[0]
except IndexError:
ievent.missing("<channel> [password]")
return
try: password = ievent.args[1]
except IndexError: password = None
bot.join(channel, password=password)
ievent.done()
cmnds.add('chan-join', handle_chanjoin, ['OPER', 'JOIN'])
cmnds.add('join', handle_chanjoin, ['OPER', 'JOIN'])
examples.add('chan-join', 'chan-join <channel> [password]', '1) chan-join #test 2) chan-join #test mekker')
## chan-del command
def handle_chandel(bot, ievent):
""" remove channel from bot.state['joinedchannels']. """
try: chan = ievent.args[0].lower()
except IndexError:
ievent.missing("<channel>")
return
try:
if bot.state:
bot.state.data['joinedchannels'].remove(chan)
bot.state.save()
except ValueError: pass
ievent.done()
cmnds.add('chan-del', handle_chandel, 'OPER')
examples.add('chan-del', 'remove channel from bot.channels', 'chan-del #mekker')
## chan-part command
def handle_chanpart(bot, ievent):
""" leave a channel. """
if not ievent.rest: chan = ievent.channel
else: chan = ievent.rest
ievent.reply('leaving %s chan' % chan)
bot.part(chan)
try:
if bot.state:
bot.state.data['joinedchannels'].remove(chan)
bot.state.save()
except ValueError: pass
ievent.done()
cmnds.add('chan-part', handle_chanpart, 'OPER')
cmnds.add('part', handle_chanpart, 'OPER')
examples.add('chan-part', 'chan-part [<channel>]', '1) chan-part 2) chan-part #test')
## chan-list command
def handle_chanlist(bot, ievent):
""" channels .. show joined channels. """
if bot.state: chans = bot.state['joinedchannels']
else: chans = []
if chans: ievent.reply("joined channels: ", chans)
else: ievent.reply('no channels joined')
cmnds.add('chan-list', handle_chanlist, ['USER', 'GUEST'])
examples.add('chan-list', 'show what channels the bot is on', 'chan-list')
## chan-cycle command
def handle_chancycle(bot, ievent):
""" cycle .. recycle channel. """
ievent.reply('cycling %s' % ievent.channel)
bot.part(ievent.channel)
try: key = ievent.chan.data.password
except (KeyError, TypeError): key = None
bot.join(ievent.channel, password=key)
ievent.done()
cmnds.add('chan-cycle', handle_chancycle, 'OPER')
examples.add('chan-cycle', 'part/join channel', 'chan-cycle')
## chan-silent command
def handle_chansilent(bot, ievent):
""" set silent mode of channel. """
if ievent.rest: channel = ievent.rest.split()[0].lower()
else:
if ievent.cmnd == 'DCC': return
channel = ievent.channel
ievent.reply('putting %s to silent mode' % channel)
ievent.chan.data.silent = True
ievent.chan.save()
ievent.done()
cmnds.add('chan-silent', handle_chansilent, 'OPER')
examples.add('chan-silent', 'set silent mode on channel the command was given in', 'chan-silent')
## chan-loud command
def handle_chanloud(bot, ievent):
""" loud .. enable output to the channel. """
if ievent.rest: channel = ievent.rest.split()[0].lower()
else:
if ievent.cmnd == 'DCC': return
channel = ievent.channel
ievent.reply('putting %s into loud mode' % ievent.channel)
ievent.chan.data.silent= False
ievent.chan.save()
ievent.done()
cmnds.add('chan-loud', handle_chanloud, 'OPER')
examples.add('chan-loud', 'disable silent mode of channel command was given in', 'chan-loud')
## chan-withnotice comamnd
def handle_chanwithnotice(bot, ievent):
""" withnotice .. make bot use notice in channel. """
if ievent.rest: channel = ievent.rest.split()[0].lower()
else:
if ievent.cmnd == 'DCC': return
channel = ievent.channel
ievent.reply('setting notice in %s' % channel)
ievent.chan.data.how = "notice"
ievent.chan.save()
ievent.done()
cmnds.add('chan-withnotice', handle_chanwithnotice, 'OPER')
examples.add('chan-withnotice', 'make bot use notice on channel the command was given in', 'chan-withnotice')
## chan-withprivmsg
def handle_chanwithprivmsg(bot, ievent):
""" withprivmsg .. make bot use privmsg in channel. """
if ievent.rest: channel = ievent.rest.split()[0].lower()
else:
if ievent.cmnd == 'DCC': return
channel = ievent.channel
ievent.reply('setting privmsg in %s' % ievent.channel)
ievent.chan.data.how = "msg"
ievent.chan.save()
ievent.done()
cmnds.add('chan-withprivmsg', handle_chanwithprivmsg, 'OPER')
examples.add('chan-withprivmsg', 'make bot use privmsg on channel command was given in', 'chan-withprivmsg')
## chan-mode command
def handle_channelmode(bot, ievent):
""" show channel mode. """
if bot.type != 'irc':
ievent.reply('channelmode only works on irc bots')
return
try: chan = ievent.args[0].lower()
except IndexError: chan = ievent.channel.lower()
if not chan in bot.state['joinedchannels']:
ievent.reply("i'm not on channel %s" % chan)
return
ievent.reply('channel mode of %s is %s' % (chan, event.chan.data.mode))
cmnds.add('chan-mode', handle_channelmode, 'OPER')
examples.add('chan-mode', 'show mode of channel', '1) chan-mode 2) chan-mode #test')
## mode callback
def modecb(bot, ievent):
""" callback to detect change of channel key. """
if ievent.postfix.find('+k') != -1:
key = ievent.postfix.split('+k')[1]
ievent.chan.data.key = key
ievent.chan.save()
callbacks.add('MODE', modecb)
## chan-denyplug command
def handle_chandenyplug(bot, event):
""" deny a plugin to be active in a channel. """
if not event.rest: event.missing("<module name>") ; return
if not event.rest in event.chan.data.denyplug:
event.chan.data.denyplug.append(event.rest)
event.chan.save()
event.done()
else: event.reply("%s is already being denied in channel %s" % (event.rest, event.channel))
cmnds.add("chan-denyplug", handle_chandenyplug, 'OPER')
examples.add("chan-denyplug", "deny a plugin command or callbacks to be executed in a channel", "chan-denyplug idle")
## chan-allowplug command
def handle_chanallowplug(bot, event):
""" allow a plugin to be active in a channel. """
if not event.rest: event.missing("<module name>") ; return
if event.rest in event.chan.data.denyplug:
event.chan.data.denyplug.remove(event.rest)
event.chan.save()
event.done()
else: event.reply("%s is already being allowed in channel %s" % (event.rest, event.channel))
cmnds.add("chan-allowplug", handle_chanallowplug, 'OPER')
examples.add("chan-allowplug", "allow a plugin command or callbacks to be executed in a channel", "chan-denyplug idle")
## chan-allowcommand command
def handle_chanallowcommand(bot, event):
""" allow a command in the channel. """
try: cmnd = event.args[0]
except (IndexError, KeyError): event.missing("<cmnd>") ; return
if not cmnd in event.chan.data.allowcommands: event.chan.data.allowcommands.append(cmnd) ; event.chan.save() ; event.done()
cmnds.add("chan-allowcommand", handle_chanallowcommand, ["OPER", ])
examples.add("chan-allowcommand", "add a command to the allow list. allows for all users.", "chan-allowcommand learn")
## chan-silentcommand command
def handle_chansilentcommand(bot, event):
""" silence a command in the channel. /msg the result of a command."""
try: cmnd = event.args[0]
except (IndexError, KeyError): event.missing("<cmnd>") ; return
if not cmnd in event.chan.data.silentcommands: event.chan.data.silentcommands.append(cmnd) ; event.chan.save() ; event.done()
cmnds.add("chan-silentcommand", handle_chansilentcommand, ["OPER", ])
examples.add("chan-silentcommand", "add a command to the allow list.", "chan-silentcommand learn")
## chab-loudcommand command
def handle_chanloudcommand(bot, event):
""" allow output of a command in the channel. """
try: cmnd = event.args[0] ; event.chan.data.silentcommands.remove(cmnd) ; event.chan.save() ; event.done()
except (IndexError, ValueError): event.reply("%s is not in the silencelist" % event.rest)
cmnds.add("chan-loudcommand", handle_chanloudcommand, ["OPER", ])
examples.add("chan-loudcommand", "remove a command from the silence list.", "chan-loudcommand learn")
## chan-removecommand
def handle_chanremovecommand(bot, event):
""" remove a command from the allowed list of a channel. """
try: cmnd = event.args[0] ; event.chan.data.allowcommands.remove(cmnd) ; event.chan.save() ; event.done()
except (IndexError, ValueError): event.reply("%s is not in the whitelist" % event.rest)
cmnds.add("chan-removecommand", handle_chanremovecommand, ["OPER", ])
examples.add("chan-removecommand", "remove a command from the allow list.", "chan-removecommand learn")
## chan-upgrade command
def handle_chanupgrade(bot, event):
""" upgrade the channel. """
prevchan = event.channel
# 0.4.1
if prevchan.startswith("-"): prevchan[0] = "+"
prevchan = prevchan.replace("@", "+")
prev = Persist(getdatadir() + os.sep + "channels" + os.sep + prevchan)
if prev.data: event.chan.data.update(prev.data) ; event.chan.save() ; event.reply("done")
else:
prevchan = event.channel
prevchan = prevchan.replace("-", "#")
prevchan = prevchan.replace("+", "@")
prev = Persist(getdatadir() + os.sep + "channels" + os.sep + prevchan)
if prev.data: event.chan.data.update(prev.data) ; event.chan.save() ; event.reply("done")
else: event.reply("can't find previous channel data")
cmnds.add("chan-upgrade", handle_chanupgrade, ["OPER", ])
examples.add("chan-upgrade", "upgrade the channel.", "chan-upgrade")
## chan-allowwatch command
def handle_chanallowwatch(bot, event):
""" add a target channel to the allowwatch list. """
if not event.rest: event.missing("<JID or channel>") ; return
if event.rest not in event.chan.data.allowwatch: event.chan.data.allowwatch.append(event.rest) ; event.chan.save()
event.done()
cmnds.add("chan-allowwatch", handle_chanallowwatch, "OPER")
examples.add("chan-allowwatch", "allow channel events to be watch when forwarded", "chan-allowwatch bthate@gmail.com")
## chan-delwatch command
def handle_chandelwatch(bot, event):
""" add a target channel to the allowout list. """
if not event.rest: event.missing("<JID>") ; return
try: event.chan.data.allowwatch.remove(event.rest) ; event.chan.save()
except: event.reply("%s is not in the allowout list" % event.rest) ; return
event.done()
cmnds.add("chan-delwatch", handle_chandelwatch, "OPER")
examples.add("chan-delwatch", "deny channel events to be watched when forwarded", "chan-delwatch bthate@gmail.com")
## chan-enable command
def handle_chanenable(bot, event):
""" enable a channel. """
event.chan.data.enable = True
event.chan.save()
event.reply("%s channel enabled" % event.channel)
cmnds.add("chan-enable", handle_chanenable, ["OPER", "USER"])
examples.add("chan-enable", "enable a channel (allow for handling of events concerning this channel (convore for now)", "chan-enable")
## chan-disable command
def handle_chandisable(bot, event):
""" enable a channel. """
event.chan.data.enable = False
event.chan.save()
event.reply("%s channel disabled" % event.channel)
cmnds.add("chan-disable", handle_chandisable, ["OPER", "USER"])
examples.add("chan-disable", "disable a channel (disallow for handling of events concerning this channel (convore for now)", "chan-disable")
| Python |
# jsb/plugs/core/plug.py
#
#
""" plugin management. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.boot import default_plugins, plugin_packages, remove_plugin, update_mod
from jsb.utils.exception import handle_exception, exceptionmsg
from jsb.lib.boot import savecmndtable, savepluginlist, update_mod
from jsb.lib.errors import NoSuchPlugin
## basic imports
import os
import logging
## plug-enable command
def handle_plugenable(bot, event):
if not event.rest: event.missing("<plugin>") ; return
mod = bot.plugs.getmodule(event.rest)
if not mod: event.reply("can't find module for %s" % event.rest) ; return
event.reply("reloading and enabling %s" % mod)
bot.enable(mod)
bot.plugs.reload(mod, force=True)
event.done()
cmnds.add("plug-enable", handle_plugenable, ["OPER", ])
examples.add("plug-enable", "enable a plugin", "plug-enable rss")
## plug-disable command
def handle_plugdisable(bot, event):
if not event.rest: event.missing("<plugin>") ; return
mod = bot.plugs.getmodule(event.rest)
if mod in default_plugins: event.reply("can't remove a default plugin") ; return
if not mod: event.reply("can't find module for %s" % event.rest) ; return
event.reply("unloading and disabling %s" % mod)
bot.plugs.unload(mod)
bot.disable(mod)
event.done()
cmnds.add("plug-disable", handle_plugdisable, ["OPER", ])
examples.add("plug-disable", "disable a plugin", "plug-disable rss")
## plug-reload command
def handle_plugreload(bot, ievent):
""" reload list of plugins. """
try: pluglist = ievent.args
except IndexError:
ievent.missing('<list plugins>')
return
reloaded = []
errors = []
for plug in pluglist:
modname = bot.plugs.getmodule(plug)
if not modname: errors.append("can't find %s plugin" % plug) ; continue
try:
loaded = bot.plugs.reload(modname, force=True, showerror=True)
for plug in loaded:
reloaded.append(plug)
logging.warn("%s reloaded" % plug)
except NoSuchPlugin: errors.append("can't find %s plugin" % plug) ; continue
except Exception, ex:
if 'No module named' in str(ex) and plug in str(ex):
logging.debug('%s - %s' % (modname, str(ex)))
continue
errors.append(exceptionmsg())
for modname in reloaded:
if modname: update_mod(modname)
if errors: ievent.reply('errors: ', errors)
if reloaded: ievent.reply('reloaded: ', reloaded)
cmnds.add('plug-reload', handle_plugreload, 'OPER')
examples.add('plug-reload', 'reload <plugin>', 'reload core')
| Python |
# jsb/plugs/core/welcome.py
#
#
""" send welcome message. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## welcome command
def handle_welcome(bot, event):
event.how = "background"
event.reply("Welcome to JSONBOT - you can give this bot commands. try !help .. or !todo or !shop or !feedback .. ;]")
cmnds.add('welcome', handle_welcome, ['OPER', 'USER', 'GUEST'])
examples.add('welcome', 'send welcome msg', 'welcome')
| Python |
# jsb basic plugins
#
#
""" register all .py files """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb/plugs/core/sort.py
#
#
""" sort bot results. """
__author__ = "Wijnand 'maze' Modderman <http://tehmaze.com>"
__license__ = "BSD"
## jsb imports
from jsb.lib.commands import cmnds
from jsb.utils.generic import waitforqueue
from jsb.lib.examples import examples
## basic imports
import optparse
## SortError exception
class SortError(Exception): pass
## SortOptionParser class
class SortOptionParser(optparse.OptionParser):
""" options parsers for the sort command. """
def __init__(self):
optparse.OptionParser.__init__(self)
self.add_option('-f', '--ignore-case',
help='fold lower case to upper case characters', default=False,
action='store_true', dest='ignorecase')
self.add_option('-n', '--numeric-sort', default=False,
help='compare according to string numerical value',
action='store_true', dest='numeric')
self.add_option('-r', '--reverse', default=False,
help='reverse the result of comparisons',
action='store_true', dest='reverse')
self.add_option('-u', '--unique', default=False,
help='output only the first of an equal run',
action='store_true', dest='unique')
def format_help(self, formatter=None):
""" ask maze. """
raise SortError('sort [-fnru] [--ignore-case] [--numeric-sort] [--reverse] [--unique]')
def error(self, msg):
""" ask maze. """
return self.exit(msg=msg)
def exit(self, status=0, msg=None):
""" ask maze. """
if msg: raise SortError(msg)
else: raise SortError
## muneric_compare function
def numeric_compare(x, y):
try: a = int(x)
except: return cmp(x, y)
try: b = int(y)
except: return cmp(x, y)
return a - b
## sort command
def handle_sort(bot, ievent):
""" sort the result list. """
parser = SortOptionParser()
if ievent.args:
try: options, result = parser.parse_args(ievent.args)
except SortError, e:
ievent.reply(str(e))
return
elif ievent.inqueue:
result = waitforqueue(ievent.inqueue, 3000)
try: options, args = parser.parse_args(ievent.rest.split())
except SortError, e:
ievent.reply(str(e))
return
if not result:
ievent.reply('no data to sort: %s' % ievent.dump())
return
if options.unique: result = list(set(result))
if options.numeric: result.sort(numeric_compare)
else: result.sort()
if options.ignorecase: result.sort(lambda a, b: cmp(a.upper(), b.upper()))
if options.reverse: result.reverse()
ievent.reply("results: ", result)
cmnds.add('sort', handle_sort, ['OPER', 'USER', 'GUEST'])
examples.add('sort', 'sort the output of a command', 'list ! sort')
| Python |
# 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
## count command
def handle_count(bot, ievent):
""" show nr of elements in result list. """
if not ievent.inqueue:
ievent.reply("use count in a pipeline")
return
result = waitforqueue(ievent.inqueue, 5000)
ievent.reply(str(len(result)))
cmnds.add('count', handle_count, ['OPER', 'USER', 'GUEST'])
examples.add('count', 'count nr of items', 'list ! count')
| Python |
# jsb/plugs/core/botevent.py
#
#
""" provide handling of host/tasks/botevent tasks. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.lib.tasks import taskmanager
from jsb.lib.botbase import BotBase
from jsb.lib.eventbase import EventBase
from jsb.utils.lazydict import LazyDict
from jsb.lib.factory import BotFactory
from jsb.lib.callbacks import first_callbacks, callbacks, last_callbacks
## simplejson imports
from jsb.imports import getjson
json = getjson()
## basic imports
import logging
## boteventcb callback
def boteventcb(inputdict, request, response):
logging.warn(inputdict)
logging.warn(dir(request))
logging.warn(dir(response))
body = request.body
logging.warn(body)
payload = json.loads(body)
try:
botjson = payload['bot']
logging.warn(botjson)
cfg = LazyDict(json.loads(botjson))
logging.warn(str(cfg))
bot = BotFactory().create(cfg.type, cfg)
logging.warn("botevent - created bot: %s" % bot.dump())
eventjson = payload['event']
logging.warn(eventjson)
event = EventBase()
event.update(LazyDict(json.loads(eventjson)))
logging.warn("botevent - created event: %s" % event.dump())
event.isremote = True
event.notask = True
bot.doevent(event)
except Exception, ex: handle_exception()
taskmanager.add('botevent', boteventcb)
| Python |
# jsb/plugs/core/user.py
#
#
""" users related commands. """
## jsb imports
from jsb.utils.generic import getwho
from jsb.utils.exception import handle_exception
from jsb.utils.name import stripname
from jsb.lib.users import users
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
import logging
## user-whoami command
def handle_whoami(bot, ievent):
""" get your username. """
ievent.reply('%s' % bot.users.getname(ievent.auth))
cmnds.add('user-whoami', handle_whoami, ['OPER', 'USER', 'GUEST'])
examples.add('user-whoami', 'get your username', 'user-whoami')
## user-meet command
def handle_meet(bot, ievent):
""" introduce a new user to the bot. """
try: nick = ievent.args[0]
except IndexError:
ievent.missing('<nick>')
return
if bot.users.exist(nick):
ievent.reply('there is already a user with username %s' % nick)
return
userhost = getwho(bot, nick)
logging.warn("users - meet - userhost is %s" % userhost)
if not userhost:
ievent.reply("can't find userhost of %s" % nick)
return
username = bot.users.getname(userhost)
if username:
ievent.reply('we already have a user with userhost %s (%s)' % (userhost, username))
return
result = 0
name = stripname(nick.lower())
result = bot.users.add(name, [userhost, ], ['USER', 'GUEST'])
if result: ievent.reply('%s - %s - (%s) added to user database' % (nick, userhost, name))
else: ievent.reply('add failed')
cmnds.add('user-meet', handle_meet, ['OPER', 'MEET'])
examples.add('user-meet', '<nick> .. introduce <nick> to the bot', 'user-meet dunker')
## user-add command
def handle_adduser(bot, ievent):
""" user-add <name> <userhost> .. introduce a new user to the bot. """
try: (name, userhost) = ievent.args
except ValueError:
ievent.missing('<name> <userhost>')
return
username = bot.users.getname(userhost)
if username:
ievent.reply('we already have a user with userhost %s (%s)' % (userhost, username))
return
result = 0
name = stripname(name.lower())
result = bot.users.add(name, [userhost, ], ['USER', 'GUEST'])
if result: ievent.reply('%s added to user database' % name)
else: ievent.reply('add failed')
cmnds.add('user-add', handle_adduser, 'OPER')
examples.add('user-add', 'add user to the bot', 'user-add dunker bart@localhost')
## user-merge command
def handle_merge(bot, ievent):
""" merge the userhost into a already existing user. """
if len(ievent.args) != 2:
ievent.missing('<name> <nick>')
return
name, nick = ievent.args
name = name.lower()
if bot.users.gotperm(name, 'OPER') and not bot.users.allowed(ievent.userhost, 'OPER'):
ievent.reply("only OPER perm can merge with OPER user")
return
if name == 'owner' and not bot.ownercheck(ievent.userhost):
ievent.reply("you are not the owner")
return
if not bot.users.exist(name):
ievent.reply("we have no user %s" % name)
return
userhost = getwho(bot, nick)
if not userhost:
ievent.reply("can't find userhost of %s" % nick)
return
if bot.ownercheck(userhost):
ievent.reply("can't merge with owner")
return
username = bot.users.getname(userhost)
if username:
ievent.reply('we already have a user with userhost %s (%s)' % (userhost, username))
return
result = bot.users.merge(name, userhost)
if result: ievent.reply('%s merged' % nick)
else: ievent.reply('merge failed')
cmnds.add('user-merge', handle_merge, ['OPER', 'MEET'])
examples.add('user-merge', '<name> <nick> .. merge record with <name> with userhost from <nick>', 'user-merge bart dunker')
## user-import command
def handle_import(bot, ievent):
""" merge the userhost into user giving the command. """
if len(ievent.args) != 1:
ievent.missing('<userhost>')
return
userhost = ievent.args[0]
if bot.ownercheck(userhost):
ievent.reply("can't merge owner")
return
name = bot.users.getname(ievent.auth)
if not name:
ievent.reply("i don't know you %s" % ievent.userhost)
return
result = bot.users.merge(name, userhost)
if result: ievent.reply('%s imported' % userhost)
else: ievent.reply('import failed')
cmnds.add('user-import', handle_import, ['IMPORT', 'OPER'])
examples.add('user-import', 'user-import <userhost> .. merge record with \
<name> with userhost from the person giving the command (self merge)', 'user-import bthate@gmail.com')
## user-del command
def handle_delete(bot, ievent):
""" remove user. """
if not bot.ownercheck(ievent.userhost):
ievent.reply('only owner can use delete')
return
if len(ievent.args) == 0:
ievent.missing('<name>')
return
name = ievent.args[0]
result = 0
name = stripname(name)
name = name.lower()
try:
result = bot.users.delete(name)
if result:
ievent.reply('%s deleted' % name)
return
except KeyError: pass
ievent.reply('no %s item in database' % name)
cmnds.add('user-del', handle_delete, 'OPER')
examples.add('user-del', 'user-del <name> .. delete user with <username>' , 'user-del dunker')
## user-scan command
def handle_userscan(bot, ievent):
""" scan for user. """
try:name = ievent.args[0]
except IndexError:
ievent.missing('<txt>')
return
name = name.lower()
names = bot.users.names()
result = []
for i in names:
if i.find(name) != -1: result.append(i)
if result: ievent.reply("users matching %s: " % name, result)
else: ievent.reply('no users matched')
cmnds.add('user-scan', handle_userscan, 'OPER')
examples.add('user-scan', '<txt> .. search database for matching usernames', 'user-scan dunk')
## user-names command
def handle_names(bot, ievent):
""" show registered users. """
ievent.reply("usernames: ", bot.users.names())
cmnds.add('user-names', handle_names, 'OPER')
examples.add('user-names', 'show names of registered users', 'user-names')
## user-name command
def handle_name(bot, ievent):
""" show name of user giving the command. """
ievent.reply('your name is %s' % bot.users.getname(ievent.auth))
cmnds.add('user-name', handle_name, ['USER', 'GUEST'])
examples.add('user-name', 'show name of user giving the commands', 'user-name')
## user-getname command
def handle_getname(bot, ievent):
""" fetch username of nick. """
try: nick = ievent.args[0]
except IndexError:
ievent.missing("<nick>")
return
userhost = getwho(bot, nick)
if not userhost:
ievent.reply("can't find userhost of %s" % nick)
return
name = bot.users.getname(userhost)
if not name:
ievent.reply("can't find user for %s" % userhost)
return
ievent.reply(name)
cmnds.add('user-getname', handle_getname, ['USER', 'GUEST'])
examples.add('user-getname', 'user-getname <nick> .. get the name of <nick>', 'user-getname dunker')
## user-addperm command
def handle_addperm(bot, ievent):
""" add permission. """
if len(ievent.args) != 2:
ievent.missing('<name> <perm>')
return
name, perm = ievent.args
perm = perm.upper()
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
result = 0
if bot.users.gotperm(name, perm):
ievent.reply('%s already has permission %s' % (name, perm))
return
result = bot.users.adduserperm(name, perm)
if result: ievent.reply('%s perm added' % perm)
else: ievent.reply('perm add failed')
cmnds.add('user-addperm', handle_addperm, 'OPER')
examples.add('user-addperm', 'user-addperm <name> <perm> .. add permissions to user <name>', 'user-addperm dunker rss')
## user-getperms command
def handle_getperms(bot, ievent):
""" get permissions of name. """
try: name = ievent.args[0]
except IndexError:
ievent.missing('<name>')
return
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
perms = bot.users.getuserperms(name)
if perms: ievent.reply("permissions of %s: " % name, perms)
else: ievent.reply('%s has no permissions set' % name)
cmnds.add('user-getperms', handle_getperms, 'OPER')
examples.add('user-getperms', 'user-getperms <name> .. get permissions of <name>', 'user-getperms dunker')
## user-perms command
def handle_perms(bot, ievent):
""" get permissions of the user given the command. """
if ievent.rest:
ievent.reply("use getperms to get the permissions of somebody else")
return
name = bot.users.getname(ievent.auth)
if not name:
ievent.reply("can't find username for %s" % ievent.userhost)
return
perms = bot.users.getuserperms(name)
if perms: ievent.reply("you have permissions: ", perms)
cmnds.add('user-perms', handle_perms, ['USER', 'GUEST'])
examples.add('user-perms', 'get permissions', 'user-perms')
## user-delperm command
def handle_delperm(bot, ievent):
""" <name> <perm> .. delete permission. """
if len(ievent.args) != 2:
ievent.missing('<name> <perm>')
return
name, perm = ievent.args
perm = perm.upper()
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
result = bot.users.deluserperm(name, perm)
if result: ievent.reply('%s perm removed' % perm)
else: ievent.reply("%s has no %s permission" % (name, perm))
cmnds.add('user-delperm', handle_delperm, 'OPER')
examples.add('user-delperm', 'delete from user <name> permission <perm>', 'user-delperm dunker rss')
## user-addstatus command
def handle_addstatus(bot, ievent):
""" add status to a user. """
if len(ievent.args) != 2:
ievent.missing('<name> <status>')
return
name, status = ievent.args
status = status.upper()
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
if bot.users.gotstatus(name, status):
ievent.reply('%s already has status %s' % (name, status))
return
result = bot.users.adduserstatus(name, status)
if result: ievent.reply('%s status added' % status)
else: ievent.reply('add failed')
cmnds.add('user-addstatus', handle_addstatus, 'OPER')
examples.add('user-addstatus', 'user-addstatus <name> <status>', 'user-addstatus dunker #dunkbots')
## user-getstatus command
def handle_getstatus(bot, ievent):
""" get status of a user. """
try: name = ievent.args[0]
except IndexError:
ievent.missing('<name>')
return
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
status = bot.users.getuserstatuses(name)
if status: ievent.reply("status of %s: " % name, status)
else: ievent.reply('%s has no status set' % name)
cmnds.add('user-getstatus', handle_getstatus, 'OPER')
examples.add('user-getstatus', 'user-getstatus <name> .. get status of <name>', 'user-getstatus dunker')
## user-status command
def handle_status(bot, ievent):
""" get status of user given the command. """
status = bot.users.getstatuses(ievent.userhost)
if status: ievent.reply("you have status: ", status)
else: ievent.reply('you have no status set')
cmnds.add('user-status', handle_status, ['USER', 'GUEST'])
examples.add('user-status', 'get status', 'user-status')
## user-delstatus command
def handle_delstatus(bot, ievent):
""" delete status. """
if len(ievent.args) != 2:
ievent.missing('<name> <status>')
return
name, status = ievent.args
status = status.upper()
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
result = bot.users.deluserstatus(name, status)
if result: ievent.reply('%s status deleted' % status)
else: ievent.reply("%s has no %s status" % (name, status))
cmnds.add('user-delstatus', handle_delstatus, 'OPER')
examples.add('user-delstatus', '<name> <status>', 'user-delstatus dunker #dunkbots')
## user-adduserhost command
def handle_adduserhost(bot, ievent):
""" add to userhosts of name. """
if len(ievent.args) != 2:
ievent.missing('<name> <userhost>')
return
name, userhost = ievent.args
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
if bot.users.gotuserhost(name, userhost):
ievent.reply('%s already has userhost %s' % (name, userhost))
return
result = bot.users.adduserhost(name, userhost)
if result: ievent.reply('userhost added')
else: ievent.reply('add failed')
cmnds.add('user-adduserhost', handle_adduserhost, 'OPER')
examples.add('user-adduserhost', 'user-adduserhost <name> <userhost>', 'user-adduserhost dunker bart@%.a2000.nl')
## user-deluserhost command
def handle_deluserhost(bot, ievent):
""" remove from userhosts of name. """
if len(ievent.args) != 2:
ievent.missing('<name> <userhost>')
return
name, userhost = ievent.args
name = name.lower()
if bot.ownercheck(userhost):
ievent.reply('can delete userhosts from owner')
return
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
result = bot.users.deluserhost(name, userhost)
if result: ievent.reply('userhost removed')
else: ievent.reply("%s has no %s in userhost list" % (name, userhost))
cmnds.add('user-deluserhost', handle_deluserhost, 'OPER')
examples.add('user-deluserhost', 'user-deluserhost <name> <userhost> .. delete from usershosts of <name> userhost <userhost>','user-deluserhost dunker bart1@bla.a2000.nl')
## user-getuserhost command
def handle_getuserhosts(bot, ievent):
""" get userhosts of a user. """
try: who = ievent.args[0]
except IndexError:
ievent.missing('<name>')
return
who = who.lower()
userhosts = bot.users.getuserhosts(who)
if userhosts: ievent.reply("userhosts of %s: " % who, userhosts)
else: ievent.reply("can't find user %s" % who)
cmnds.add('user-getuserhosts', handle_getuserhosts, 'OPER')
examples.add('user-getuserhosts', 'user-getuserhosts <name> .. get userhosts of <name>', 'user-getuserhosts dunker')
## user-userhosts command
def handle_userhosts(bot, ievent):
""" get userhosts of user giving the command. """
userhosts = bot.users.gethosts(ievent.userhost)
if userhosts: ievent.reply("you have userhosts: ", userhosts)
else: ievent.reply('no userhosts found')
cmnds.add('user-userhosts', handle_userhosts, ['USER', 'GUEST'])
examples.add('user-userhosts', 'get userhosts', 'user-userhosts')
## user-getemail command
def handle_getemail(bot, ievent):
""" get email addres of a user. """
try: name = ievent.args[0]
except IndexError:
ievent.missing('<name>')
return
name = name.lower()
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
email = bot.users.getuseremail(name)
if email: ievent.reply(email)
else: ievent.reply('no email set')
cmnds.add('user-getemail', handle_getemail, ['USER', ])
examples.add('user-getemail', 'user-getemail <name> .. get email from user <name>', 'user-getemail dunker')
## user-setemail command
def handle_setemail(bot, ievent):
""" set email. """
try: name, email = ievent.args
except ValueError:
ievent.missing('<name> <email>')
return
if not bot.users.exist(name):
ievent.reply("can't find user %s" % name)
return
bot.users.setemail(name, email)
ievent.reply('email set')
cmnds.add('user-setemail', handle_setemail, 'OPER')
examples.add('user-setemail', 'user-setemail <name> <email>.. set email of user <name>', 'user-setemail dunker bart@gozerbot.org')
## user-email command
def handle_email(bot, ievent):
""" show email of user giving the command. """
if len(ievent.args) != 0:
ievent.reply('use getemail to get the email address of an user .. email shows your own mail address')
return
email = bot.users.getemail(ievent.userhost)
if email: ievent.reply(email)
else: ievent.reply('no email set')
cmnds.add('user-email', handle_email, ['USER', 'GUEST'])
examples.add('user-email', 'get email', 'user-email')
## user-delemail command
def handle_delemail(bot, ievent):
""" reset email of user giving the command. """
name = bot.users.getname(ievent.auth)
if not name:
ievent.reply("can't find user for %s" % ievent.userhost)
return
result = bot.users.delallemail(name)
if result: ievent.reply('email removed')
else: ievent.reply('delete failed')
cmnds.add('user-delemail', handle_delemail, 'OPER')
examples.add('user-delemail', 'reset email', 'user-delemail')
## user-addpermit
def handle_addpermit(bot, ievent):
""" add permit to permit list of <name>. """
try: who, what = ievent.args
except ValueError:
ievent.missing("<name> <permit>")
return
if not bot.users.exist(who):
ievent.reply("can't find username of %s" % who)
return
name = bot.users.getname(ievent.auth)
if not name:
ievent.reply("i dont know %s" % ievent.userhost)
return
if bot.users.gotpermit(name, (who, what)):
ievent.reply('%s is already allowed to do %s' % (who, what))
return
result = bot.users.adduserpermit(name, who, what)
if result: ievent.reply('permit added')
else: ievent.reply('add failed')
cmnds.add('user-addpermit', handle_addpermit, ['USER', 'GUEST'])
examples.add('user-addpermit', 'user-addpermit <nick> <what> .. permit nick access to <what> .. use setperms to add permissions', 'user-addpermit dunker todo')
## user-permit command
def handle_permit(bot, ievent):
""" get permit list of user giving the command. """
if ievent.rest:
ievent.reply("use the user-addpermit command to allow somebody something .. use getname <nick> to get the username of somebody .. this command shows what permits you have")
return
name = bot.users.getname(ievent.auth)
if not name:
ievent.reply("can't find user for %s" % ievent.userhost)
return
permits = bot.users.getuserpermits(name)
if permits: ievent.reply("you permit the following: ", permits)
else: ievent.reply("you don't have any permits")
cmnds.add('user-permit', handle_permit, ['USER', 'GUEST'])
examples.add('user-permit', 'show permit of user giving the command', 'user-permit')
## user-delpermit command
def handle_userdelpermit(bot, ievent):
""" remove (name, permit) from permit list. """
try: who, what = ievent.args
except ValueError:
ievent.missing("<name> <permit>")
return
if not bot.users.exist(who):
ievent.reply("can't find registered name of %s" % who)
return
name = bot.users.getname(ievent.auth)
if not name:
ievent.reply("i don't know you %s" % ievent.userhost)
return
if not bot.users.gotpermit(name, (who, what)):
ievent.reply('%s is already not allowed to do %s' % (who, what))
return
result = bot.users.deluserpermit(name, (who, what))
if result: ievent.reply('%s denied' % what)
else: ievent.reply('delete failed')
cmnds.add('user-delpermit', handle_userdelpermit, ['USER', 'GUEST'])
examples.add('user-delpermit', 'user-delpermit <name> <permit>', 'user-delpermit dunker todo')
## user-check command
def handle_check(bot, ievent):
""" get user data of <nick>. """
try: nick = ievent.args[0]
except IndexError:
ievent.missing('<nick>')
return
userhost = getwho(bot, nick)
if not userhost:
ievent.reply("can't find userhost of %s" % nick)
return
name = bot.users.getname(userhost)
if not name:
ievent.reply("can't find user")
return
userhosts = bot.users.getuserhosts(name)
perms = bot.users.getuserperms(name)
email = bot.users.getuseremail(name)
permits = bot.users.getuserpermits(name)
status = bot.users.getuserstatuses(name)
ievent.reply('userrecord of %s = userhosts: %s perms: %s email: %s permits: %s status: %s' % (name, str(userhosts), str(perms), str(email), str(permits), str(status)))
cmnds.add('user-check', handle_check, 'OPER')
examples.add('user-check', 'user-check <nick>', 'user-check dunker')
## user-show command
def handle_show(bot, ievent):
""" get user data of <name>. """
try: name = ievent.args[0]
except IndexError:
ievent.missing('<name>')
return
name = name.lower()
user = bot.users.byname(name)
if not user:
ievent.reply("can't find user %s" % name)
return
userhosts = str(user.data.userhosts)
perms = str(user.data.perms)
email = str(user.data.email)
permits = str(user.data.permits)
status = str(user.data.status)
ievent.reply('userrecord of %s = userhosts: %s perms: %s email: %s permits: %s status: %s' % (name, userhosts, perms, email, permits, status))
cmnds.add('user-show', handle_show, 'OPER')
examples.add('user-show', 'user-show <name> .. show data of <name>', 'user-show dunker')
# user-match command
def handle_match(bot, ievent):
""" user-match <userhost> .. get data of <userhost>. """
try: userhost = ievent.args[0]
except IndexError:
ievent.missing('<userhost>')
return
user = bot.users.getuser(userhost)
if not user:
ievent.reply("can't find user with userhost %s" % userhost)
return
userhosts = str(user.data.userhosts)
perms = str(user.data.perms)
email = str(user.data.email)
permits = str(user.data.permits)
status = str(user.data.status)
ievent.reply('userrecord of %s = userhosts: %s perms: %s email: %s permits: %s status: %s' % (userhost, userhosts, perms, email, permits, status))
cmnds.add('user-match', handle_match, ['OPER', ])
examples.add('user-match', 'user-match <userhost>', 'user-match test@test')
# user-allstatus command
def handle_getuserstatus(bot, ievent):
""" list users with status <status>. """
try: status = ievent.args[0].upper()
except IndexError:
ievent.missing('<status>')
return
result = bot.users.getstatususers(status)
if result: ievent.reply("users with %s status: " % status, result)
else: ievent.reply("no users with %s status found" % status)
cmnds.add('user-allstatus', handle_getuserstatus, 'OPER')
examples.add('user-allstatus', 'user-allstatus <status> .. get all users with <status> status', 'user-allstatus #dunkbots')
## user-allperm command
def handle_getuserperm(bot, ievent):
""" list users with permission <perm>. """
try: perm = ievent.args[0].upper()
except IndexError:
ievent.missing('<perm>')
return
result = bot.users.getpermusers(perm)
if result: ievent.reply('users with %s permission: ' % perm, result)
else: ievent.reply("no users with %s permission found" % perm)
cmnds.add('user-allperm', handle_getuserperm, 'OPER')
examples.add('user-allperm', 'user-allperm <perm> .. get users with <perm> permission', 'user-allperm rss')
## user-search command
def handle_usersearch(bot, ievent):
""" search for user matching given userhost. """
try: what = ievent.args[0]
except IndexError:
ievent.missing('<txt>')
return
result = bot.users.usersearch(what)
if result:
res = ["(%s) %s" % u for u in result]
ievent.reply('users matching %s: ' % what, res)
else: ievent.reply('no userhost matching %s found' % what)
cmnds.add('user-search', handle_usersearch, 'OPER')
examples.add('user-search', 'search users userhosts', 'user-search gozerbot')
| Python |
# jsb/plugs/common/forward.py
#
#
""" forward incoming trafic on a bot to another bot through xmpp. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.callbacks import callbacks, remote_callbacks, last_callbacks, first_callbacks
from jsb.lib.eventbase import EventBase
from jsb.lib.persist import PlugPersist
from jsb.utils.lazydict import LazyDict
from jsb.lib.examples import examples
from jsb.lib.fleet import getfleet
from jsb.lib.container import Container
from jsb.lib.errors import NoProperDigest
from jsb.utils.exception import handle_exception
from jsb.utils.locking import locked
from jsb.utils.generic import strippedtxt, stripcolor
## twitter plugin imports
from jsb.plugs.common.twitter import postmsg
## xmpp import
from jsb.contrib.xmlstream import NodeBuilder, XMLescape, XMLunescape
## basic imports
import logging
import copy
import time
import types
import hmac
import hashlib
## defines
forward = PlugPersist("forward-core")
if not forward.data.allowin:
forward.data.allowin = []
if not forward.data.channels:
forward.data.channels = {}
if not forward.data.outs:
forward.data.outs = {}
if not forward.data.whitelist:
forward.data.whitelist = {}
cpy = copy.deepcopy
## forward-precondition
def forwardoutpre(bot, event):
""" preconditon to check if forward callbacks is to be fired. """
if event.how == "background": return False
chan = unicode(event.channel).lower()
if not chan: return
logging.debug("forward - pre - %s" % event.channel)
if chan in forward.data.channels and not event.isremote() and not event.forwarded:
if event.how != u"background": return True
return False
## forward-callback
def forwardoutcb(bot, event):
""" forward callback. """
e = cpy(event)
logging.debug("forward - cbtype is %s - %s" % (event.cbtype, event.how))
e.forwarded = True
e.source = bot.cfg.user
e.botname = bot.cfg.server or bot.cfg.name
if not event.chan: event.bind(bot)
if event.chan: e.allowwatch = event.chan.data.allowwatch
fleet = getfleet()
for jid in forward.data.channels[event.channel.lower()]:
if not "@" in jid: logging.error("forward - %s is not a valid JID" % jid) ; continue
logging.info("forward - sending to %s" % jid)
if jid == "twitter":
try: postmsg(forward.data.outs[jid], e.txt)
except Exception, ex: handle_exception()
continue
outbot = fleet.getfirstjabber(bot.isgae)
if not outbot and bot.isgae: outbot = fleet.makebot('xmpp', 'forwardbot')
if outbot:
e.source = outbot.cfg.user
txt = outbot.normalize(e.tojson())
txt = stripcolor(txt)
#txt = e.tojson()
container = Container(outbot.cfg.user, txt)
outbot.outnocb(jid, container.tojson())
else: logging.info("forward - no xmpp bot found in fleet".upper())
first_callbacks.add('BLIP_SUBMITTED', forwardoutcb, forwardoutpre)
first_callbacks.add('MESSAGE', forwardoutcb, forwardoutpre)
#first_callbacks.add('PRESENCE', forwardoutcb, forwardoutpre)
first_callbacks.add('PRIVMSG', forwardoutcb, forwardoutpre)
first_callbacks.add('JOIN', forwardoutcb, forwardoutpre)
first_callbacks.add('PART', forwardoutcb, forwardoutpre)
first_callbacks.add('QUIT', forwardoutcb, forwardoutpre)
first_callbacks.add('NICK', forwardoutcb, forwardoutpre)
first_callbacks.add('CONSOLE', forwardoutcb, forwardoutpre)
first_callbacks.add('WEB', forwardoutcb, forwardoutpre)
first_callbacks.add('DISPATCH', forwardoutcb, forwardoutpre)
first_callbacks.add('OUTPUT', forwardoutcb, forwardoutpre)
## forward-add command
def handle_forwardadd(bot, event):
""" add a new forward. """
if not event.rest:
event.missing('<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)
if event.rest:
event.chan.save()
event.done()
cmnds.add("forward-add", handle_forwardadd, 'OPER')
examples.add("forward-add" , "add an JID to forward to", "forward-add jsoncloud@appspot.com")
## forward-del command
def handle_forwarddel(bot, event):
""" delete a forward. """
if not event.rest:
event.missing('<JID>')
return
try: del forward.data.outs[event.rest]
except KeyError: event.reply("no forward out called %s" % event.rest) ; return
forward.save()
if event.rest in event.chan.data.forwards: event.chan.data.forwards.remove(event.rest) ; event.chan.save()
event.done()
cmnds.add("forward-del", handle_forwarddel, 'OPER')
examples.add("forward-del" , "delete an JID to forward to", "forward-del jsoncloud@appspot.com")
## forward-allow command
def handle_forwardallow(bot, event):
""" allow a remote bot to forward to us. """
if not event.rest:
event.missing("<JID>")
return
if forward.data.whitelist.has_key(event.rest):
forward.data.whitelist[event.rest] = bot.type
forward.save()
event.done()
cmnds.add("forward-allow", handle_forwardallow, 'OPER')
examples.add("forward-allow" , "allow an JID to forward to us", "forward-allow jsoncloud@appspot.com")
## forward-list command
def handle_forwardlist(bot, event):
""" list forwards. """
try: event.reply("forwards for %s: " % event.channel, forward.data.channels[event.channel])
except KeyError: event.reply("no forwards for %s" % event.channel)
cmnds.add("forward-list", handle_forwardlist, 'OPER')
examples.add("forward-list" , "list all forwards of a channel", "forward-list")
## forward command
def handle_forward(bot, event):
""" forward the channel tot another bot. """
if not event.args:
event.missing("<JID>")
return
forward.data.channels[event.channel.lower()] = event.args
for jid in event.args:
forward.data.outs[jid] = event.user.data.name
if not jid in event.chan.data.forwards: event.chan.data.forwards = event.args
if event.args: event.chan.save()
forward.save()
event.done()
cmnds.add("forward", handle_forward, 'OPER')
examples.add("forward" , "forward a channel to provided JIDS", "forward jsoncloud@appspot.com")
## forward-stop command
def handle_forwardstop(bot, event):
""" stop forwarding the channel to another bot. """
if not event.args:
event.missing("<JID>")
return
try:
for jid in event.args:
try:
forward.data.channels[event.channel].remove(jid)
del forward.data.outs[jid]
if jid in event.chan.data.forwards: event.chan.data.forwards.remove(jid)
except ValueError: pass
forward.save()
event.done()
except KeyError, ex: event.reply("we are not forwarding %s" % str(ex))
cmnds.add("forward-stop", handle_forwardstop, 'OPER')
examples.add("forward-stop" , "stop forwarding a channel to provided JIDS", "forward-stop jsoncloud@appspot.com")
| Python |
# jsb/plugs/common/hubbub.py
#
#
"""
the hubbub mantra is of the following:
use the hb-register <feedname> <url> command to register url and start a feed in in one pass.
"""
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persist import Persist, PlugPersist
from jsb.utils.pdol import Pdol
from jsb.utils.pdod import Pdod
from jsb.utils.generic import jsonstring
from jsb.utils.lazydict import LazyDict
from jsb.utils.url import useragent, geturl2
from jsb.utils.statdict import StatDict
from jsb.utils.exception import handle_exception
from jsb.lib.fleet import getfleet
from jsb.lib.channelbase import ChannelBase
from jsb.utils.url import posturl
from jsb.lib.errors import NoSuchBotType
from jsb.drivers.gae.wave.waves import Wave
from jsb.lib.threads import start_new_thread
from jsb.lib.datadir import getdatadir
from jsb.lib.jsbimport import _import_byfile
from jsb.imports import getfeedparser
feedparser = getfeedparser()
## basic imports
import base64
import logging
import urllib
import urlparse
import uuid
import os
import time
## subscribe function
def subscribe(url):
""" subscribe to an hubbub feed. """
subscribe_args = {
'hub.callback': urlparse.urljoin('https://jsonbot.appspot.com', '/hubbub'),
'hub.mode': 'subscribe',
'hub.topic': url,
'hub.verify': 'async',
'hub.verify_token': str(uuid.uuid4()),
}
headers = {}
credentials = _import_byfile("credentials", getdatadir() + os.sep + "config" + os.sep + "credentials.py")
if credentials.HUB_CREDENTIALS:
auth_string = "Basic " + base64.b64encode("%s:%s" % tuple(credentials.HUB_CREDENTIALS))
headers['Authorization'] = auth_string
logging.warn("hubbub - subscribe - trying %s (%s)" % (credentials.HUB_URL, url))
logging.warn("hubbub - subscribe - %s" % str(headers))
response = posturl(credentials.HUB_URL, headers, subscribe_args)
return response
## tinyurl import
try:
from jsb.plugs.common.tinyurl import get_tinyurl
except ImportError:
def get_tinyurl(url):
return [url, ]
## defines
allowedtokens = ['updated', 'link', 'summary', 'tags', 'author', 'content', 'title', 'subtitle']
savelist = []
possiblemarkup = {'separator': 'set this to desired item separator', \
'all-lines': "set this to 1 if you don't want items to be aggregated", \
'tinyurl': "set this to 1 when you want to use tinyurls", 'skipmerge': \
"set this to 1 if you want to skip merge commits", 'reverse-order': 'set \
this to 1 if you want the items displayed with oldest item first'}
def find_self_url(links):
""" find home url of feed. """
for link in links:
if link.rel == 'self': return link.href
## NoSuchFeed exception
class NoSuchFeed(Exception):
""" there is no such feed in the feed database. """
pass
## HubbubItem class
class HubbubItem(Persist):
""" item that contains hubbub data """
def __init__(self, name, url="", owner="", itemslist=['title', 'link'], watchchannels=[], running=1):
filebase = getdatadir() + os.sep + 'plugs' + os.sep + 'jsb.plugs.wave.hubbub' + os.sep + name
Persist.__init__(self, filebase + os.sep + name + '.core')
if not self.data: self.data = {}
self.data = LazyDict(self.data)
self.data['name'] = self.data.name or str(name)
self.data['url'] = self.data.url or str(url)
self.data['owner'] = self.data.owner or str(owner)
self.data['watchchannels'] = self.data.watchchannels or list(watchchannels)
self.data['running'] = self.data.running or running
self.itemslists = Pdol(filebase + os.sep + name + '.itemslists')
self.markup = Pdod(filebase + os.sep + name + '.markup')
def save(self):
""" save the hubbub items data. """
Persist.save(self)
self.itemslists.save()
self.markup.save()
def ownercheck(self, userhost):
""" check is userhost is the owner of the feed. """
try: return self.data.owner == userhost
except KeyError: pass
return False
def fetchdata(self):
""" get data of rss feed. """
url = self.data['url']
if not url:
logging.warn("hubbub - %s doesnt have url set" % self.data.name)
return []
result = feedparser.parse(url, agent=useragent())
logging.debug("hubbub - fetch - got result from %s" % url)
if result and result.has_key('bozo_exception'): logging.info('hubbub - %s bozo_exception: %s' % (url, result['bozo_exception']))
try:
status = result.status
logging.info("hubbub - status is %s" % status)
except AttributeError: status = 200
if status != 200 and status != 301 and status != 302: raise RssStatus(status)
return result.entries
## HubbubWatcher class
class HubbubWatcher(PlugPersist):
""" this watcher helps with the handling of incoming POST. also maitains
index of feed names.
"""
def __init__(self, filename):
PlugPersist.__init__(self, filename)
if not self.data: self.data = {}
if not self.data.has_key('names'): self.data['names'] = []
if not self.data.has_key('urls'): self.data['urls'] = {}
if not self.data.has_key('feeds'): self.data['feeds'] = {}
self.feeds = {}
def add(self, name, url, owner):
""" add a feed to the database. """
if not name in self.data['names']:
self.data['names'].append(name)
self.data['urls'][url] = name
self.save()
item = HubbubItem(name, url, owner)
if item.data.url != url:
return False
item.save()
self.feeds[name] = item
return True
def byname(self, name):
""" retrieve a feed by it's name. """
if name in self.feeds: return self.feeds[name]
item = HubbubItem(name)
if item.data.url: self.feeds[name] = item ; return item
def byurl(self, url):
""" retrieve a feed by it's url. """
try:
name = self.data['urls'][url]
return self.byname(name)
except KeyError: pass
def cloneurl(self, url, auth):
""" add feeds from remote url. """
data = geturl2(url)
got = []
for line in data.split('\n'):
try: (name, url) = line.split()
except ValueError:
logging.debug("hubbub - cloneurl - can't split %s line" % line)
continue
if url.endswith('<br>'): url = url[:-4]
self.add(name, url, auth)
got.append(name)
return got
def watch(self, name):
""" make feed ready for watching and mark it running. """
logging.debug('trying %s hubbub feed' % name)
item = self.byname(name)
if item == None: raise NoSuchFeed(name)
if not item.data.running:
item.data.running = 1
item.data.stoprunning = 0
item.save()
subscribe(item.data['url'])
logging.info('hubbub - started %s watch' % name)
def work(self, botname, type, channel, entries, url, *args, **kwargs):
try:
item = self.byurl(url)
name = item.data.name
try:
fleet = getfleet()
bot = fleet.byname(botname)
if not bot and type:
bot = fleet.makebot(type, botname)
if not bot:
bot = fleet.makebot('xmpp', botname)
except NoSuchBotType, ex: logging.warn("hubbub - %s" % str(ex)) ; return
if not bot: logging.error("hubbub - can't find %s bot in fleet" % type) ; return
res2 = entries
if not res2: logging.info("no updates for %s (%s) feed available" % (item.data.name, channel)) ; return
if item.markup.get(jsonstring([name, channel]), 'reverse-order'): res2 = res2[::-1]
if item.markup.get(jsonstring([name, channel]), 'all-lines'):
for i in res2:
response = self.makeresponse(name, [i, ], channel)
try: bot.say(channel, response)
except Exception, ex: handle_exception()
else:
sep = item.markup.get(jsonstring([name, channel]), 'separator')
if sep: response = self.makeresponse(name, res2, channel, sep=sep)
else: response = self.makeresponse(name, res2, channel)
bot.say(channel, response)
except Exception, ex: handle_exception()
def incoming(self, data):
""" process incoming hubbub data. """
result = feedparser.parse(data)
url = find_self_url(result.feed.links)
logging.info("hubbub - in - %s - %s" % (url, data))
try:
item = self.byurl(url)
if not item: logging.warn("hubbub - can't find feed for %s" % url) ; return
if not item.data.running: logging.warn("hubbub - %s is not in running mode" % item.data.url) ; return
if not item.data.url or item.data.url == 'urlnotset':
item.data.url = url
item.save()
if item:
loopover = item.data.watchchannels
name = item.data.name
else: logging.warn("hubbub - can't find %s item" % url) ; return
logging.debug("loopover in %s peek is: %s" % (name, loopover))
counter = 1
for i in loopover:
if len(i) == 3:
try: (botname, type, channel) = i
except:
try: (botname, type, channel) = loads(i)
except:
logging.info('hubbub - %s is not in the format (botname, bottype, channel)' % str(item))
continue
else:
logging.debug('hubbub - %s is not in the format (botname, bottype, channel)' % item.data.url)
continue
if type == 'wave':
wave = Wave(channel)
if wave and wave.data.json_data:
start_new_thread(work, (botname, type, channel, result.entries, url), {"_countdown": counter})
else: logging.warn("hubbub - skipping %s - not joined" % channel)
else: start_new_thread(work, (botname, type, channel, result.entries, url), {"_countdown": counter})
counter += 1
except Exception, ex: handle_exception(txt=url)
return True
def getall(self):
""" reconstruct all feeditems into self.feeds. """
for name in self.data['names']: self.feeds[name] = HubbubItem(name)
return self.feeds
def ownercheck(self, name, userhost):
""" check if userhost is the owner of feed. """
try: return self.byname(name).ownercheck(userhost)
except (KeyError, AttributeError): pass
return False
def makeresult(self, name, target, data):
"""
make a result (txt) of a feed depending on its itemlist (tokens)
and markup.
"""
item = self.byname(name)
res = []
for j in data:
tmp = {}
if not item.itemslists.data[jsonstring([name, target])]: return []
for i in item.itemslists.data[jsonstring([name, target])]:
try: tmp[i] = unicode(j[i])
except KeyError: continue
res.append(tmp)
return res
def makeresponse(self, name, res, channel, sep=" .. "):
""" loop over result to make a response. """
item = self.byname(name)
result = u"[%s] - " % name
try: itemslist = item.itemslists.data[jsonstring([name, channel])]
except KeyError:
item = self.byname(name)
if item == None: return "no %s rss item" % name
else:
item.itemslists.data[jsonstring([name, channel])] = ['title', 'link']
item.itemslists.save()
for j in res:
if item.markup.get(jsonstring([name, channel]), 'skipmerge') and 'Merge branch' in j['title']: continue
resultstr = u""
for i in item.itemslists.data[jsonstring([name, channel])]:
try:
ii = getattr(j, i)
if not ii: continue
ii = unicode(ii)
if ii.startswith('http://'):
if item.markup.get(jsonstring([name, channel]), 'tinyurl'):
try:
tinyurl = get_tinyurl(ii)
logging.debug('rss - tinyurl is: %s' % str(tinyurl))
if not tinyurl: resultstr += u"%s - " % ii
else: resultstr += u"%s - " % tinyurl[0]
except Exception, ex:
handle_exception()
resultstr += u"%s - " % item
else: resultstr += u"%s - " % ii
else: resultstr += u"%s - " % ii.strip()
except (KeyError, AttributeError), ex:
logging.info('hubbub - %s - %s' % (name, str(ex)))
continue
resultstr = resultstr[:-3]
if resultstr: result += u"%s %s " % (resultstr, sep)
return result[:-(len(sep)+2)]
def stopwatch(self, name):
""" disable running status of the feed. """
try:
feed = self.byname(name)
feed.data.running = 0
feed.save()
return True
except KeyError: pass
return False
def list(self):
""" return feed names. """
feeds = self.data['names']
return feeds
def runners(self):
""" show names/channels of running watchers. """
result = []
for name in self.data['names']:
z = self.byname(name)
if z.data.running == 1 and not z.data.stoprunning: result.append((z.data.name, z.data.watchchannels))
return result
def listfeeds(self, botname, type, channel):
""" show names/channels of running watcher. """
result = []
for name in self.data['names']:
z = self.byname(name)
if not z or not z.data.running: continue
if jsonstring([botname, type, channel]) in z.data.watchchannels or [botname, type, channel] in z.data.watchchannels:
result.append(z.data.name)
return result
def getfeeds(self, channel, botname, type=None):
""" get all feeds running in a channel. """
chan = ChannelBase(channel, botname)
return chan.data.feeds
def url(self, name):
""" return url of a feed. """
feed = self.byname(name)
if feed: return feed.data.url
def seturl(self, name, url):
""" set url of hubbub feed. """
feed = self.byname(name)
feed.data.url = url
feed.save()
return True
def fetchdata(self, name):
""" fetch the feed ourselves instead of receiving push items. """
return self.byname(name).fetchdata()
def scan(self, name):
""" scan a rss url for tokens. """
keys = []
items = self.fetchdata(name)
for item in items:
for key in item:
if key in allowedtokens: keys.append(key)
statdict = StatDict()
for key in keys: statdict.upitem(key)
return statdict.top()
def startwatchers(self):
""" enable all runnable feeds """
for name in self.data['names']:
z = self.byname(name)
if z.data.running: self.watch(z.data.name)
def start(self, botname, type, name, channel):
""" start a feed in a channel. """
item = self.byname(name)
if not item:
logging.info("we don't have a %s feed" % name)
return False
target = channel
if not jsonstring([botname, type, target]) in item.data.watchchannels and not [botname, type, target] in item.data.watchchannels:
item.data.watchchannels.append([botname, type, target])
item.itemslists.data[jsonstring([name, target])] = ['title', 'link']
item.markup.set(jsonstring([name, target]), 'tinyurl', 1)
item.data.running = 1
item.data.stoprunning = 0
item.save()
watcher.watch(name)
logging.debug("hubbub - started %s feed in %s channel" % (name, channel))
return True
def stop(self, botname, type, name, channel):
""" stop watching a feed. """
item = self.byname(name)
if not item: return False
try:
logging.warn("trying to remove %s from %s feed list" % (name, channel))
if type == "wave": chan = Wave(channel)
else: chan = ChannelBase(channel, botname)
chan.data.feeds.remove(name)
chan.save()
except ValueError:
logging.warn("can't remove %s from %s feed list" % (name, channel))
try:
item.data.watchchannels.remove([botname, type, channel])
item.save()
logging.debug("stopped %s feed in %s channel" % (name, channel))
except ValueError: return False
return True
def clone(self, botname, type, newchannel, oldchannel):
""" clone feeds over to a new wave. """
feeds = self.getfeeds(oldchannel, botname)
logging.debug("hubbub - clone - %s - %s - %s - %s - %s" % (botname, type, newchannel, oldchannel, feeds))
for feed in feeds:
self.stop(botname, type, feed, oldchannel)
self.start(botname, type, feed, newchannel)
return feeds
## work function
def work(botname, type, channel, result, item, *args, **kwargs):
""" worker function used in defer. """
watcher.work(botname, type, channel, result, item, *args, **kwargs)
## the watcher object
watcher = HubbubWatcher('hubbub')
## size function
def size():
""" return number of watched rss entries. """
return watcher.size()
## hb-subscribe command
def handle_hubbubsubscribe(bot, event):
""" subscribe to a hubbub feed """
for name in event.args:
item = watcher.byname(name)
if not item: event.reply("%s feed is not yet added .. see hb-add" % name) ; continue
url = item.data.url
if not url: event.reply('please provide a url for %s feed' % name) ; return
if not url.startswith('http://'): event.reply('%s doesnt start with "http://"' % url)
if not watcher.data['urls'].has_key(name): watcher.add(name, url, event.channel)
if not watcher.byname(name): watcher.add(name, url, event.channel)
response = subscribe(url)
event.reply("subscription send: %s - %s" % (url, response.status))
cmnds.add('hb-subscribe', handle_hubbubsubscribe, ['USER',])
examples.add('hb-subscribe', 'subscribe to a feed', 'hb-subscribe jsb-hg http://code.google.com/feeds/p/jsb/hgchanges/basic')
## hb-clone command
def handle_hubbubclone(bot, event):
""" clone the feeds running in a channel. """
if not event.rest: event.missing('<channel>') ; return
feeds = watcher.clone(bot.cfg.name, bot.type, event.channel, event.rest)
event.reply('cloned the following feeds: ', feeds)
bot.say(event.rest, "this wave is continued in %s" % event.url)
cmnds.add('hb-clone', handle_hubbubclone, 'USER')
examples.add('hb-clone', 'clone feeds into new channel', 'hb-clone waveid')
## hb-cloneurl command
def handle_hubbubcloneurl(bot, event):
""" clone urls from http://host/feeds. """
if not event.rest: event.missing('<url>') ; return
import urllib2
try:
feeds = watcher.cloneurl(event.rest, event.auth)
event.reply('cloned the following feeds: ', feeds)
except urllib2.HTTPError, ex: event.reply("hubbub - clone - %s" % str(ex))
cmnds.add('hb-cloneurl', handle_hubbubcloneurl, 'OPER')
examples.add('hb-cloneurl', 'clone feeds from remote url', 'hb-cloneurl http://jsonbot.appspot.com/feeds')
## hb-add command
def handle_hubbubadd(bot, ievent):
""" add a hubbub item. """
try: (name, url) = ievent.args
except ValueError: ievent.missing('<name> <url>') ; return
result = subscribe(url)
if int(result.status) > 200 and int(result.status) < 300:
watcher.add(name, url, ievent.userhost)
ievent.reply('%s feed added' % name)
else: ievent.reply('%s feed NOT added. status code is %s' % (name, result.status))
cmnds.add('hb-add', handle_hubbubadd, 'USER')
examples.add('hb-add', 'hubbub-add <name> <url> to the watcher', 'hb-add jsb-hg http://code.google.com/feeds/p/jsb/hgchanges/basic')
## hb-watch command
def handle_hubbubwatch(bot, ievent):
""" enable a feed for watching. """
if not ievent.channel: ievent.reply('no channel provided')
try: name = ievent.args[0]
except IndexError: ievent.missing('<feedname>') ; return
item = watcher.byname(name)
if item == None: ievent.reply("we don't have a %s hubbub item" % name) ; return
got = None
if not item.data.running or item.data.stoprunning:
item.data.running = 1
item.data.stoprunning = 0
got = True
item.save()
try: watcher.watch(name)
except Exception, ex: ievent.reply(str(ex)) ; return
if got: ievent.reply('watcher started')
else: ievent.reply('already watching %s' % name)
cmnds.add('hb-watch', handle_hubbubwatch, 'USER')
examples.add('hb-watch', 'hubbub-watch <name> [seconds to sleep] .. go watching <name>', 'hb-watch gozerbot')
## hubbub-start command
def handle_hubbubstart(bot, ievent):
""" start sending a feed to an user or channel/wave. """
feeds = ievent.args
if not feeds: ievent.missing('<list of feeds>') ; return
started = []
cantstart = []
if feeds[0] == 'all': feeds = watcher.list()
for name in feeds:
if watcher.start(bot.cfg.name, bot.type, name, ievent.channel):
started.append(name)
if name not in ievent.chan.data.feeds:
ievent.chan.data.feeds.append(name)
ievent.chan.save()
else: cantstart.append(name)
if bot.type == "wave":
wave = ievent.chan
if wave and wave.data:
logging.debug("feed running in %s: %s" % (ievent.title, wave.data.feeds))
if wave.data.loud:
try: ievent.set_title("JSONBOT - %s - #%s" % (' - '.join(wave.data.feeds), str(wave.data.nrcloned)))
except Exception, ex: handle_exception()
if started: ievent.reply('started: ', started)
else: ievent.reply("sorry can't start: ", cantstart)
cmnds.add('hb-start', handle_hubbubstart, ['USER', 'GUEST'])
examples.add('hb-start', 'hubbub-start <list of feeds> .. start a hubbub feed (per user/channel) ', 'hb-start gozerbot')
## hb-stop command
def handle_hubbubstop(bot, ievent):
""" stop a hubbub feed to a user. """
if not ievent.args: ievent.missing('<list of feeds>') ; return
feeds = ievent.args
stopped = []
cantstop = []
if feeds[0] == 'all': feeds = watcher.listfeeds(bot.cfg.name, bot.type, ievent.channel)
for name in feeds:
if watcher.stop(bot.cfg.name, bot.type, name, ievent.channel):
stopped.append(name)
if name in ievent.chan.data.feeds:
ievent.chan.data.feeds.remove(name)
ievent.chan.save()
else: cantstop.append(name)
if stopped: ievent.reply('feeds stopped: ', feeds)
elif cantstop: ievent.reply('failed to stop %s feed' % cantstop)
ievent.done()
cmnds.add('hb-stop', handle_hubbubstop, ['USER', 'GUEST'])
examples.add('hb-stop', 'hubbub-stop <list of names> .. stop a hubbub feed (per user/channel) ', 'hb-stop gozerbot')
## hb-stopall command
def handle_hubbubstopall(bot, ievent):
""" stop all hubbub feeds to a channel. """
if not ievent.rest: target = ievent.channel
else: target = ievent.rest
stopped = []
feeds = watcher.getfeeds(target, bot.cfg.name)
if feeds:
for feed in feeds:
if watcher.stop(bot.cfg.name, bot.type, feed, target):
if feed in ievent.chan.data.feeds:
ievent.chan.data.feeds.remove(feed)
ievent.chan.save()
stopped.append(feed)
ievent.reply('stopped feeds: ', stopped)
else: ievent.reply('no feeds running in %s' % target)
cmnds.add('hb-stopall', handle_hubbubstopall, ['HUBBUB', 'OPER'])
examples.add('hb-stopall', 'hubbub-stopall .. stop all hubbub feeds (per user/channel) ', 'hb-stopall')
## hb-channels command
def handle_hubbubchannels(bot, ievent):
""" show channels of hubbub feed. """
try: name = ievent.args[0]
except IndexError: ievent.missing("<feedname>") ; return
item = watcher.byname(name)
if item == None: ievent.reply("we don't have a %s hubbub object" % name) ; return
if not item.data.watchchannels: ievent.reply('%s is not in watch mode' % name) ; return
result = []
for i in item.data.watchchannels: result.append(str(i))
ievent.reply("channels of %s: " % name, result)
cmnds.add('hb-channels', handle_hubbubchannels, ['OPER', ])
examples.add('hb-channels', 'hb-channels <name> .. show channels', 'hb-channels gozerbot')
## hb-addchannel
def handle_hubbubaddchannel(bot, ievent):
""" add a channel to hubbub feed. """
try: (name, botname, type, channel) = ievent.args
except ValueError:
try:
botname = bot.cfg.name
(name, type, channel) = ievent.args
except ValueError:
try:
botname = bot.cfg.name
type = bot.type
(name, channel) = ievent.args
type = bot.type
except ValueError:
try:
botname = bot.cfg.name
name = ievent.args[0]
type = bot.type
channel = ievent.channel
except IndexError:
ievent.missing('<name> [<botname>][<bottype>] <channel>')
return
item = watcher.byname(name)
if item == None: ievent.reply("we don't have a %s hubbub object" % name) ; return
if not item.data.running: ievent.reply('%s watcher is not running' % name) ; return
if jsonstring([botname, type, channel]) in item.data.watchchannels or [botname, type, channel] in item.data.watchchannels:
ievent.reply('we are already monitoring %s on (%s,%s)' % (name, type, channel))
return
item.data.watchchannels.append([botname, type, channel])
item.save()
ievent.reply('%s added to %s hubbub item' % (channel, name))
cmnds.add('hb-addchannel', handle_hubbubaddchannel, ['OPER', ])
examples.add('hb-addchannel', 'add a channel to a feeds watchlist', '1) hb-addchannel gozerbot #dunkbots 2) hb-addchannel gozerbot main #dunkbots')
## hb-setitems command
def handle_hubbubsetitems(bot, ievent):
""" set items (tokens) of a feed. """
try: (name, items) = ievent.args[0], ievent.args[1:]
except ValueError: ievent.missing('<feedname> <tokens>') ; return
target = ievent.channel
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
feed.itemslists.data[jsonstring([name, target])] = items
feed.itemslists.save()
ievent.reply('%s added to (%s,%s) itemslist' % (items, name, target))
cmnds.add('hb-setitems', handle_hubbubsetitems, ['GUEST', 'USER'])
examples.add('hb-setitems', 'set tokens of the itemslist (per user/channel)', 'hb-setitems gozerbot author author link pubDate')
## hb-additem command
def handle_hubbubadditem(bot, ievent):
""" add an item (token) to a feeds itemslist. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<feedname> <token>') ; return
target = ievent.channel
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
try: feed.itemslists.data[jsonstring([name, target])].append(item)
except KeyError: feed.itemslists.data[jsonstring([name, target])] = ['title', 'link']
feed.itemslists.save()
ievent.reply('%s added to (%s,%s) itemslist' % (item, name, target))
cmnds.add('hb-additem', handle_hubbubadditem, ['GUEST', 'USER'])
examples.add('hb-additem', 'add a token to the itemslist (per user/channel)', 'hb-additem gozerbot link')
## hb-delitem command
def handle_hubbubdelitem(bot, ievent):
""" delete item (token) from a feeds itemlist. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<name> <item>') ; return
target = ievent.channel
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
try:
feed.itemslists.data[jsonstring([name, target])].remove(item)
feed.itemslists.save()
except (NoSuchFeed, ValueError): ievent.reply("we don't have a %s feed" % name) ; return
ievent.reply('%s removed from (%s,%s) itemslist' % (item, name, target))
cmnds.add('hb-delitem', handle_hubbubdelitem, ['GUEST', 'USER'])
examples.add('hb-delitem', 'remove a token from the itemslist (per user/channel)', 'hb-delitem gozerbot link')
## hb-markuplist command
def handle_hubbubmarkuplist(bot, ievent):
""" show possible markups that can be used. """
ievent.reply('possible markups ==> ' , possiblemarkup)
cmnds.add('hb-markuplist', handle_hubbubmarkuplist, ['USER', 'GUEST'])
examples.add('hb-markuplist', 'show possible markup entries', 'hb-markuplist')
## hb-markup command
def handle_hubbubmarkup(bot, ievent):
""" show the markup of a feed (channel specific). """
try: name = ievent.args[0]
except IndexError: ievent.missing('<feedname>') ; return
target = ievent.channel
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
try: ievent.reply(str(feed.markup[jsonstring([name, target])]))
except KeyError: pass
cmnds.add('hb-markup', handle_hubbubmarkup, ['GUEST', 'USER'])
examples.add('hb-markup', 'show markup list for a feed (per user/channel)', 'hb-markup gozerbot')
## hb-addmarkup command
def handle_hubbubaddmarkup(bot, ievent):
""" add a markup to a feeds markuplist. """
try: (name, item, value) = ievent.args
except ValueError: ievent.missing('<feedname> <item> <value>') ; return
target = ievent.channel
try: value = int(value)
except ValueError: pass
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
try:
feed.markup.set(jsonstring([name, target]), item, value)
feed.markup.save()
ievent.reply('%s added to (%s,%s) markuplist' % (item, name, target))
except KeyError: ievent.reply("no (%s,%s) feed available" % (name, target))
cmnds.add('hb-addmarkup', handle_hubbubaddmarkup, ['GUEST', 'USER'])
examples.add('hb-addmarkup', 'add a markup option to the markuplist (per user/channel)', 'hb-addmarkup gozerbot all-lines 1')
## hb-delmarkup command
def handle_hubbubdelmarkup(bot, ievent):
""" delete markup item from a feed's markuplist. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<feedname> <item>') ; return
target = ievent.channel
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
try: del feed.markup[jsonstring([name, target])][item]
except (KeyError, TypeError): ievent.reply("can't remove %s from %s feed's markup" % (item, name)) ; return
feed.markup.save()
ievent.reply('%s removed from (%s,%s) markuplist' % (item, name, target))
cmnds.add('hb-delmarkup', handle_hubbubdelmarkup, ['GUEST', 'USER'])
examples.add('hb-delmarkup', 'remove a markup option from the markuplist (per user/channel)', 'hb-delmarkup gozerbot all-lines')
## hb-delchannel command
def handle_hubbubdelchannel(bot, ievent):
""" delete channel from hubbub feed. """
bottype = None
try: (name, botname, bottype, channel) = ievent.args
except ValueError:
try:
botname = bot.cfg.name
(name, type, channel) = ievent.args
except ValueError:
try:
botname = bot.cfg.name
name = ievent.args[0]
type = bot.type
channel = ievent.channel
except IndexError:
ievent.missing('<feedname> [<botname>] [<bottype>] [<channel>]')
return
item = watcher.byname(name)
if item == None: ievent.reply("we don't have a %s object" % name) ; return
if jsonstring([botname, type, channel]) in item.data.watchchannels:
item.data.watchchannels.remove(jsonstring([botname, type, channel]))
ievent.reply('%s removed from %s hubbub item' % (channel, name))
elif [type, channel] in item.data.watchchannels:
item.data.watchchannels.remove([botname, type, channel])
ievent.reply('%s removed from %s hubbub item' % (channel, name))
else:
ievent.reply('we are not monitoring %s on (%s,%s)' % (name, type, channel))
return
item.save()
cmnds.add('hb-delchannel', handle_hubbubdelchannel, ['OPER', ])
examples.add('hubbub-delchannel', 'remove a channel from a feeds watchlist', '1) hb-delchannel gozerbot #dunkbots 2) hb-delchannel gozerbot main #dunkbots')
## hb-stopwatch command
def handle_hubbubstopwatch(bot, ievent):
""" stop watching a feed. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<feedname>') ; return
item = watcher.byname(name)
if not item: ievent.reply("there is no %s item" % name) ; return
if not watcher.stopwatch(name): ievent.reply("can't stop %s watcher" % name) ; return
ievent.reply('stopped %s hubbub watch' % name)
cmnds.add('hb-stopwatch', handle_hubbubstopwatch, ['OPER', ])
examples.add('hb-stopwatch', 'hubbub-stopwatch <name> .. stop polling <name>', 'hb-stopwatch gozerbot')
## hb-get command
def handle_hubbubget(bot, ievent):
""" fetch feed data. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<feedname>') ; return
channel = ievent.channel
item = watcher.byname(name)
if item == None: ievent.reply("we don't have a %s item" % name) ; return
try: result = watcher.fetchdata(name)
except Exception, ex: ievent.reply('%s error: %s' % (name, str(ex))) ; return
if item.markup.get(jsonstring([name, channel]), 'reverse-order'): result = result[::-1]
response = watcher.makeresponse(name, result, ievent.channel)
if response: ievent.reply("results of %s: %s" % (name, response))
else: ievent.reply("can't make a reponse out of %s" % name)
cmnds.add('hb-get', handle_hubbubget, ['HUBBUB', 'USER'], threaded=True)
examples.add('hb-get', 'hubbub-get <name> .. get data from <name>', 'hb-get gozerbot')
## hb-running command
def handle_hubbubrunning(bot, ievent):
""" show which feeds are running. """
result = watcher.runners()
resultlist = []
teller = 1
for i in result: resultlist.append("%s %s" % (i[0], i[1]))
if resultlist: ievent.reply("running hubbub watchers: ", resultlist, nr=1)
else: ievent.reply('nothing running yet')
cmnds.add('hb-running', handle_hubbubrunning, ['HUBBUB', 'USER'])
examples.add('hb-running', 'hubbub-running .. get running feeds', 'hb-running')
## hb-list command
def handle_hubbublist(bot, ievent):
""" return list of available feeds. """
result = watcher.list()
result.sort()
if result: ievent.reply("hubbub items: ", result)
else: ievent.reply('no hubbub items yet')
cmnds.add('hb-list', handle_hubbublist, ['GUEST', 'USER'])
examples.add('hb-list', 'get list of hubbub items', 'hb-list')
## hb-url command
def handle_hubbuburl(bot, ievent):
""" return url of feed. """
try:
name = ievent.args[0]
except IndexError: ievent.missing('<feedname>') ; return
if not watcher.ownercheck(name, ievent.userhost):
ievent.reply("you are not the owner of the %s feed" % name)
return
result = watcher.url(name)
if not result: ievent.reply("can't fetch url for %s" % name) ; return
try:
if ':' in result.split('/')[1]:
if not ievent.msg: ievent.reply('run this command in a private message') ; return
except (TypeError, ValueError, IndexError): pass
ievent.reply('url of %s: %s' % (name, result))
cmnds.add('hb-url', handle_hubbuburl, ['OPER', ])
examples.add('hb-url', 'hb-url <name> .. get url from hubbub item', 'hb-url gozerbot')
## hb-itemslist command
def handle_hubbubitemslist(bot, ievent):
""" show itemslist (tokens) of hubbub item. """
try:name = ievent.args[0]
except IndexError: ievent.missing('<feedname>') ; return
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
try: itemslist = feed.itemslists.data[jsonstring([name, ievent.channel])]
except KeyError: ievent.reply("no itemslist set for (%s, %s)" % (name, ievent.channel)) ; return
ievent.reply("itemslist of (%s, %s): " % (name, ievent.channel), itemslist)
cmnds.add('hb-itemslist', handle_hubbubitemslist, ['GUEST', 'USER'])
examples.add('hb-itemslist', 'hb-itemslist <name> .. get itemslist of <name> ', 'hb-itemslist gozerbot')
## hb-scan command
def handle_hubbubscan(bot, ievent):
""" scan feed for available tokens. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
if not watcher.byname(name): ievent.reply('no %s feeds available' % name) ; return
try: result = watcher.scan(name)
except Exception, ex: ievent.reply(str(ex)) ; return
if result == None: ievent.reply("can't get data for %s" % name) ; return
res = []
for i in result: res.append("%s=%s" % i)
ievent.reply("tokens of %s: " % name, res)
cmnds.add('hb-scan', handle_hubbubscan, ['USER', 'GUEST'])
examples.add('hb-scan', 'hb-scan <name> .. get possible items of <name> ', 'hb-scan gozerbot')
## hb-feeds command
def handle_hubbubfeeds(bot, ievent):
""" show what feeds are running in a channel. """
try: channel = ievent.args[0]
except IndexError: channel = ievent.channel
try:
result = watcher.getfeeds(channel, bot.cfg.name)
if result: ievent.reply("feeds running: ", result)
else: ievent.reply('no feeds running')
except Exception, ex: ievent.reply("ERROR: %s" % str(ex))
cmnds.add('hb-feeds', handle_hubbubfeeds, ['USER', 'GUEST'])
examples.add('hb-feeds', 'hb-feeds <name> .. show what feeds are running in a channel', '1) hb-feeds 2) hb-feeds #dunkbots')
## hb-welcome command
def handle_hubbubwelcome(bot, ievent):
""" show hubbub welcome message, used by the gadget. """
ievent.reply("hb-register <feedname> <url>")
cmnds.add('hb-welcome', handle_hubbubwelcome, ['USER', 'GUEST'])
examples.add('hb-welcome', 'hb-welcome .. show welcome message', 'hb-welcome')
## hb-register command
def handle_hubbubregister(bot, ievent):
""" register a url and start the feed in one pass. """
if not ievent.waveid: target = ievent.channel
else: target = ievent.waveid
if len(ievent.args) > 2: ievent.reply("feed name needs to be 1 word.") ; return
try: (name, url) = ievent.args
except ValueError:
try: name = ievent.args[0]
except IndexError: ievent.reply("i need a feed name and a feed url to work with") ; return
item = watcher.byname(name)
if item:
if not name in watcher.getfeeds(ievent.channel, bot.cfg.name):
watcher.start(bot.cfg.name, bot.type, name, target)
if name not in ievent.chan.data.feeds:
ievent.chan.data.feeds.append(name)
ievent.chan.save()
ievent.reply('started %s feed. entries will show up when the feed is updated.' % name)
if bot.type == "wave":
wave = Wave(ievent.waveid)
logging.debug("feed running in %s: %s" % (ievent.title, wave.data.feeds))
if name not in ievent.title:
ievent.set_title("JSONBOT - %s - #%s" % (' - '.join(wave.data.feeds), str(wave.data.nrcloned)))
else: ievent.reply("feed %s is already running." % name)
else: ievent.reply("i don't know a %s feed. please enter name and url." % name)
return
if not url.startswith("http"): ievent.reply("the feedurl needs to start with http(s)://") ; return
result = subscribe(url)
if int(result.status) > 200 and int(result.status) < 300:
if watcher.add(name, url, ievent.userhost):
watcher.start(bot.cfg.name, bot.type, name, target)
ievent.reply('started %s feed. entries will show up when the feed is updated.' % name)
if bot.type == "wave":
wave = Wave(ievent.waveid)
logging.debug("feed running in %s: %s" % (ievent.title, wave.data.feeds))
if name not in ievent.title:
ievent.set_title("JSONBOT - %s - #%s" % (' - '.join(wave.data.feeds), str(wave.data.nrcloned)))
return
else:
ievent.reply("there already exists a %s feed. please choose a different name" % name)
return
else:
ievent.reply('feed %s NOT added. Status code is %s. please check if the feed is valid.' % (name, result.status))
cmnds.add('hb-register', handle_hubbubregister, ['USER', 'GUEST'])
examples.add('hb-register', 'hb-register .. register url and start it in one pass', 'hb-register hgrepo http://code.google.com/feeds/p/jsb/hgchanges/basic')
| Python |
# jsb/plugs/core/topic.py
#
#
""" manage topics. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
import time
## checktopicmode function
def checktopicmode(bot, ievent):
""" callback for change in channel topic mode """
chan = ievent.channel
mode = ievent.chan.data.mode
if mode and 't' in mode:
if chan not in bot.state['opchan']:
ievent.reply("i'm not op on %s" % chan)
return 0
return 1
def handle_gettopic(bot, ievent):
""" topic [<channel>] .. get topic """
try: channel = ievent.args[0]
except IndexError: channel = ievent.channel
result = bot.gettopic(channel)
try:
(what, who, when) = result
ievent.reply('topic on %s is %s made by %s on %s' % (channel, what, who, time.ctime(when)))
except (ValueError, TypeError): ievent.reply("can't get topic data of channel %s" % channel)
cmnds.add('topic', handle_gettopic, 'USER', threaded=True)
examples.add('topic', 'topic [<channel>] .. get topic', '1) topic 2) topic #dunkbots')
def handle_topicset(bot, ievent):
""" topic-set .. set the topic """
if not bot.jabber and not checktopicmode(bot, ievent): return
if not ievent.rest: ievent.missing('<what>') ; return
bot.settopic(ievent.channel, ievent.rest)
cmnds.add('topic-set', handle_topicset, 'USER', allowqueue=False)
examples.add('topic-set', 'set channel topic', 'topic-set Yooo')
def handle_topicadd(bot, ievent):
""" topic-add <txt> .. add topic item """
if not bot.jabber and not checktopicmode(bot, ievent): return
if not ievent.rest: ievent.missing("<what>") ; return
result = bot.gettopic(ievent.channel)
if not result: ievent.reply("can't get topic data") ; return
what = result[0]
what += " | %s" % ievent.rest
bot.settopic(ievent.channel, what)
cmnds.add('topic-add', handle_topicadd, 'USER', threaded=True)
examples.add('topic-add', 'topic-add <txt> .. add a topic item', 'topic-add mekker')
def handle_topicdel(bot, ievent):
""" topic-del <topicnr> .. delete topic item """
if not bot.jabber and not checktopicmode(bot, ievent): return
try: topicnr = int(ievent.args[0])
except (IndexError, ValueError): ievent.reply('i need a integer as argument') ; return
if topicnr < 1: ievent.reply('topic items start at 1') ; return
result = bot.gettopic(ievent.channel)
if not result: ievent.reply("can't get topic data") ; return
what = result[0].split(' | ')
if topicnr > len(what): ievent.reply('there are only %s topic items' % len(what)) ; return
del what[topicnr-1]
newtopic = ' | '.join(what)
bot.settopic(ievent.channel, newtopic)
cmnds.add('topic-del', handle_topicdel, 'USER', threaded=True)
examples.add('topic-del', 'topic-del <topicnr> .. delete topic item', 'topic-del 1')
def handle_topicmove(bot, ievent):
""" topic-move <nrfrom> <nrto> .. move topic item """
if not bot.jabber and not checktopicmode(bot, ievent): return
try: (topicfrom, topicto) = ievent.args
except ValueError: ievent.missing('<from> <to>') ; return
try: topicfrom = int(topicfrom) ; topicto = int(topicto)
except ValueError: ievent.reply('i need two integers as arguments') ; return
if topicfrom < 1 or topicto < 1: ievent.reply('topic items start at 1') ; return
topicdata = bot.gettopic(ievent.channel)
if not topicdata: ievent.reply("can't get topic data") ; return
splitted = topicdata[0].split(' | ')
if topicfrom > len(splitted) or topicto > len(splitted): ievent.reply('max item is %s' % len(splitted)) ; return
tmp = splitted[topicfrom-1]
del splitted[topicfrom-1]
splitted.insert(topicto-1, tmp)
newtopic = ' | '.join(splitted)
bot.settopic(ievent.channel, newtopic)
cmnds.add('topic-move', handle_topicmove, 'USER', threaded=True)
examples.add('topic-move', 'topic-move <nrfrom> <nrto> .. move topic items', 'topic-move 3 1')
def handle_topiclistadd(bot, ievent):
""" topic-listadd <topicnr> <person> .. add a person to a topic list """
if not bot.jabber and not checktopicmode(bot, ievent): return
try: (topicnr, person) = ievent.args
except ValueError: ievent.missing('<topicnr> <person>') ; return
try: topicnr = int(topicnr)
except ValueError: ievent.reply('i need an integer as topicnr') ; return
if topicnr < 1: ievent.reply('topic items start at 1') ; return
topicdata = bot.gettopic(ievent.channel)
if not topicdata: ievent.reply("can't get topic data") ; return
splitted = topicdata[0].split(' | ')
if topicnr > len(splitted): ievent.reply('max item is %s' % len(splitted)) ; return
try: topic = splitted[topicnr-1]
except IndexError: ievent.reply('no %s topic found' % str(topicnr)) ; return
if topic.strip().endswith(':'): topic += " %s" % person
else: topic += ",%s" % person
splitted[topicnr-1] = topic
newtopic = ' | '.join(splitted)
bot.settopic(ievent.channel, newtopic)
cmnds.add('topic-listadd', handle_topiclistadd, 'USER', threaded=True)
examples.add('topic-listadd', 'topic-listadd <toicnr> <person> .. add user to topiclist', 'topic-listadd 1 bart')
def handle_topiclistdel(bot, ievent):
""" topic-listdel <topicnr> <person> .. remove person from topic list """
if not bot.jabber and not checktopicmode(bot, ievent): return
try: (topicnr, person) = ievent.args
except ValueError: ievent.missing('<topicnr> <person>') ; return
try: topicnr = int(topicnr)
except ValueError: ievent.reply('i need an integer as topicnr') ; return
if topicnr < 1: ievent.reply('topic items start at 1') ; return
topicdata = bot.gettopic(ievent.channel)
if not topicdata: ievent.reply("can't get topic data") ; return
splitted = topicdata[0].split(' | ')
if topicnr > len(splitted): ievent.reply('max item is %s' % len(splitted)) ; return
try: topic = splitted[topicnr-1]
except IndexError: ievent.reply('no %s topic found' % str(topicnr)) ; return
if not person in topic: ievent.reply('%s is not on the list' % person) ; return
l = topic.rsplit(':', 1)
try:
persons = l[-1].split(',')
persons = [i.strip() for i in persons]
persons.remove(person)
except ValueError: ievent.reply('no %s in list' % person) ; return
except IndexError: ievent.reply('i need a : in the topic to work properly') ; return
splitted[topicnr-1] = "%s: %s" % (l[0], ','.join(persons))
newtopic = ' | '.join(splitted)
bot.settopic(ievent.channel, newtopic)
cmnds.add('topic-listdel', handle_topiclistdel, 'USER', threaded=True)
examples.add('topic-listdel', 'topic-listdel <topicnr> <person> .. delete user from topiclist', 'topic-listdel 1 bart')
| Python |
# jsb/plugs/common/wikipedia.py
#
#
""" query wikipedia .. use countrycode to select a country specific wikipedia. """
## jsb imports
from jsb.utils.url import geturl, striphtml
from jsb.utils.generic import splittxt, handle_exception, fromenc
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.rsslist import rsslist
## generic imports
from urllib import quote
import re
import logging
## defines
wikire = re.compile('start content(.*?)end content', re.M)
## searchwiki function
def searchwiki(txt, lang='en'):
input = []
for i in txt.split():
if i.startswith('-'):
if len(i) != 3: continue
else: lang = i[1:]
continue
input.append(i.strip().capitalize())
what = "_".join(input)
url = u'http://%s.wikipedia.org/wiki/Special:Export/%s' % (lang, quote(what.encode('utf-8')))
url2 = u'http://%s.wikipedia.org/wiki/%s' % (lang, quote(what.encode('utf-8')))
txt = getwikidata(url)
if not txt: return ("", url2)
if 'from other capitalisation' in txt:
what = what.title()
url = u'http://%s.wikipedia.org/wiki/Special:Export/%s' % (lang, quote(what.encode('utf-8')))
url2 = u'http://%s.wikipedia.org/wiki/%s' % (lang, quote(what.encode('utf-8')))
txt = getwikidata(url)
if '#REDIRECT' in txt or '#redirect' in txt:
redir = ' '.join(txt.split()[1:])
url = u'http://%s.wikipedia.org/wiki/Special:Export/%s' % (lang, quote(redir.encode('utf-8')))
url2 = u'http://%s.wikipedia.org/wiki/%s' % (lang, quote(redir.encode('utf-8')))
txt = getwikidata(url)
return (txt, url2)
## getwikidata function
def getwikidata(url):
""" fetch wiki data """
result = geturl(url)
if not result: return
res = rsslist(result)
txt = ""
for i in res:
try:
logging.debug(unicode(i))
txt = i['text']
break
except: pass
txt = re.sub('\[\[(.*?)\]\]', '<b>\g<1></b>', txt)
txt = re.sub('{{(.*?)}}', '<i>\g<1></i>', txt)
txt = re.sub('==(.*?)==', '<h3>\g<1></h3>', txt)
txt = re.sub('=(.*?)=', '<h2>\g<1></h2>', txt)
txt = re.sub('\*(.*?)\n', '<li>\g<1></li>', txt)
txt = re.sub('\n\n', '<br><br>', txt)
txt = re.sub('\s+', ' ', txt)
txt = txt.replace('|', ' - ')
return txt
## wikipedia command
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')
| Python |
# jsb/plugs/common/feedback.py
#
#
""" give feedback on the bot to dunker@jsonbot.org. connects to jsonbot.org if no jabber bot exists. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.fleet import getfleet
from jsb.lib.factory import bot_factory
from jsb.utils.lazydict import LazyDict
## basic imports
import uuid
import time
## feedback command
def handle_feedback(bot, event):
fleet = getfleet()
feedbackbot = fleet.getfirstjabber()
if not feedbackbot:
if bot.isgae: cfg = LazyDict({"name": "feedbackbot-gae", "user": "feedback@jsonbot.org", "password": "givesomereply"})
else: cfg = LazyDict({"name": "feedbackbot", "user": "feedback@jsonbot.org", "password": "givesomereply"})
feedbackbot = fleet.makebot("sxmpp", cfg.name, config=cfg)
if not feedbackbot: event.reply("can't make xmpp bot.") ; return
feedbackbot.start()
if not feedbackbot.cfg.password: feedbackbot.cfg.password = cfg['password'] ; feedbackbot.cfg.save()
feedbackbot.cfg.disable = False
event.reply("sending to bart@jsonbot.org ... ")
feedbackbot.say("bart@jsonbot.org", event.rest)
feedbackbot.cfg.disable = True
feedbackbot.cfg.save()
event.done()
cmnds.add("feedback", handle_feedback, ["OPER", "USER", "GUEST"])
examples.add("feedback", "send a message to bart@jsonbot.org", "feedback the bot is missing some spirit !")
| Python |
# jsb/plugs/common/weather.py
#
#
""" show weather based on Google's weather API """
__copyright__ = 'this file is in the public domain'
__author__ = 'Landon Fowles'
## jsb imports
from jsb.utils.url import geturl
from jsb.utils.generic import getwho
from jsb.lib.commands import cmnds
from jsb.lib.persist import Persist
from jsb.lib.examples import examples
from jsb.lib.persiststate import UserState
## basic imports
from xml.dom import minidom
from urllib import urlencode
import logging
import time
## weather command
def handle_weather(bot, ievent):
""" show weather using Google's weather API """
userhost = ""
loc = ""
try:
nick = ievent.rest
if nick:
userhost = getwho(bot, nick)
if not userhost: pass
else:
try:
name = bot.users.getname(userhost)
if not name: ievent.reply("%s is not known with the bot" % nick) ; return
us = UserState(name)
loc = us['location']
except KeyError: ievent.reply("%s doesn't have his location set in userstate" % nick) ; return
except KeyError: pass
if not loc:
if ievent.rest: loc = ievent.rest
else: ievent.missing('<nick>|<location>') ; return
query = urlencode({'weather':loc})
weathertxt = geturl('http://www.google.ca/ig/api?%s' % query)
if 'problem_cause' in weathertxt:
logging.error('weather - %s' % weathertxt)
ievent.reply('an error occured looking up data for %s' % loc)
return
logging.debug("weather - got reply: %s" % weathertxt)
resultstr = ""
if weathertxt:
gweather = minidom.parseString(weathertxt)
gweather = gweather.getElementsByTagName('weather')[0]
if ievent.usercmnd == "weather":
info = gweather.getElementsByTagName('forecast_information')[0]
if info:
city = info.getElementsByTagName('city')[0].attributes["data"].value
zip = info.getElementsByTagName('postal_code')[0].attributes["data"].value
time = info.getElementsByTagName('current_date_time')[0].attributes["data"].value
weather = gweather.getElementsByTagName('current_conditions')[0]
condition = weather.getElementsByTagName('condition')[0].attributes["data"].value
temp_f = weather.getElementsByTagName('temp_f')[0].attributes["data"].value
temp_c = weather.getElementsByTagName('temp_c')[0].attributes["data"].value
humidity = weather.getElementsByTagName('humidity')[0].attributes["data"].value
try: wind = weather.getElementsByTagName('wind_condition')[0].attributes["data"].value
except IndexError: wind = ""
try: wind_km = round(int(wind[-6:-4]) * 1.609344)
except ValueError: wind_km = ""
if (not condition == ""): condition = " Oh, and it's " + condition + "."
resultstr = "As of %s, %s (%s) has a temperature of %sC/%sF with %s. %s (%s km/h).%s" % (time, city, zip, temp_c, temp_f, humidity, wind, wind_km, condition)
elif ievent.usercmnd == "forecast":
forecasts = gweather.getElementsByTagName('forecast_conditions')
for forecast in forecasts:
condition = forecast.getElementsByTagName('condition')[0].attributes["data"].value
low_f = forecast.getElementsByTagName('low')[0].attributes["data"].value
high_f = forecast.getElementsByTagName('high')[0].attributes["data"].value
day = forecast.getElementsByTagName('day_of_week')[0].attributes["data"].value
low_c = round((int(low_f) - 32) * 5.0 / 9.0)
high_c = round((int(high_f) - 32) * 5.0 / 9.0)
resultstr += "[%s: F(%sl/%sh) C(%sl/%sh) %s]" % (day, low_f, high_f, low_c, high_c, condition)
if not resultstr: ievent.reply('%s not found!' % loc) ; return
else: ievent.reply(resultstr)
cmnds.add('weather', handle_weather, ['OPER', 'USER', 'GUEST'])
examples.add('weather', 'get weather for <LOCATION> or <nick>', '1) weather London, England 2) weather dunker')
| Python |
# jsb/plugs/common/ask.py
#
#
""" ask a user a question and relay back the response. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.callbacks import callbacks
from jsb.lib.persist import PlugPersist
from jsb.lib.examples import examples
from jsb.lib.fleet import getfleet
## basic imports
import logging
## defines
defaultJID = 'bart@jsonbot.org'
questions = PlugPersist('questions')
experts = PlugPersist('experts')
subjects = PlugPersist('subjects')
## ask-precondition
def askprecondition(bot, event):
""" check to see whether the callback needs to be executed. """
global questions
if event.userhost in questions.data and not event.iscmnd: return True
## ask-callback
def askcallback(bot, event):
""" this is the callbacks that handles the responses to questions. """
sendto = questions.data[event.userhost]
jid = []
channels = []
try: (printto, txt) = event.txt.split(':', 1)
except ValueError: printto = False ; txt = event.txt
txt = txt.strip()
done = []
fleet = getfleet()
for botname, type, userhost, channel in sendto:
if not printto or userhost != printto: continue
askbot = fleet.makebot(type)
if not askbot: askbot = fleet.makebot('xmpp', 'askxmppbot')
logging.debug("ask - %s %s %s %s" % (botname, type, userhost, channel))
if askbot:
for jid in channel: askbot.say(channel, "%s says: %s" % (event.userhost, txt))
else: logging.warn("ask - can't find %s bot in fleet" % type) ; continue
try:
questions.data[event.userhost].remove([botname, type, userhost, channel])
questions.save()
except ValueError: pass
done.append(channel)
break
if done: event.reply('answer sent to ', done)
callbacks.add('MESSAGE', askcallback, askprecondition)
callbacks.add('DISPATCH', askcallback, askprecondition)
callbacks.add('WEB', askcallback, askprecondition)
callbacks.add('CONVORE', askcallback, askprecondition)
callbacks.add('PRIVMSG', askcallback, askprecondition)
## ask command
def handle_ask(bot, event):
"""
this command lets you ask a question that gets dispatched to jabber
users that have registered themselves for that particular subject.
"""
try: subject, question = event.rest.split(' ', 1)
except ValueError:
event.missing('<subject> <question>')
return
try: expertslist = experts.data[subject]
except KeyError:
if '@' in subject: expertslist = [subject, ]
else: expertslist = [defaultJID, ]
fleet = getfleet()
xmppbot = fleet.getfirstjabber()
if xmppbot:
for expert in expertslist: xmppbot.say(expert, "%s (%s) asks you: %s" % (event.userhost, bot.cfg.name, question))
else:
logging.warn("ask - can't find jabber bot in fleet")
return
asker = event.userhost
for expert in expertslist:
if not questions.data.has_key(expert): questions.data[expert] = []
questions.data[expert].append([bot.cfg.name, bot.type, event.userhost, event.channel])
questions.save()
event.reply('question is sent to %s' % ' .. '.join(expertslist))
cmnds.add('ask', handle_ask, ['OPER', 'USER', 'GUEST'], options={'-w': False})
examples.add('ask', 'ask [group|JID] question .. ask a groups of users a question or use a specific JID', 'ask ask-bot what is the mercurial repository')
## ask-stop command
def handle_askstop(bot, event):
""" remove any waiting data for the user giving the command. """
try: del questions.data[event.userhost]
except KeyError: event.reply('no question running')
cmnds.add('ask-stop', handle_askstop, ['OPER', 'USER', 'GUEST'])
examples.add('ask-stop', 'stop listening to answers', 'ask-stop')
## ask-join command
def handle_askjoin(bot, event):
""" join the expert list of a subject. """
if bot.type != 'xmpp':
event.reply('this command only works in jabber')
return
try: subject = event.args[0]
except IndexError:
event.missing('<subject>')
return
if not experts.data.has_key(subject): experts.data[subject] = []
if not event.userhost in experts.data[subject]:
experts.data[subject].append(event.userhost)
experts.save()
expert = event.userhost
if not subjects.data.has_key(expert): subjects.data[expert] = []
if not subject in subjects.data[expert]:
subjects.data[expert].append(subject)
subjects.save()
event.done()
cmnds.add('ask-join', handle_askjoin, ['OPER', 'USER', 'GUEST'])
examples.add('ask-join', 'ask-join <subject> .. join a subject as an expert', 'ask-join ask-bot')
## ask-part command
def handle_askpart(bot, event):
""" leave the expert list of a subject. """
if bot.type != 'xmpp':
event.reply('this command only works in jabber')
return
try: subject = event.args[0]
except IndexError: event.missing('<subject>')
try: experts.data[subject].remove(event.userhost)
except (ValueError, KeyError): pass
try: subjects.data[event.userhost].remove(subject)
except (ValueError, KeyError): pass
event.done()
cmnds.add('ask-part', handle_askpart, ['OPER', 'USER', 'GUEST'])
examples.add('ask-part', 'leave the subject expert list', 'ask-part ask-bot')
## ask-list command
def handle_asklist(bot, event):
""" show all available subjects. """
event.reply('available subjects: ', experts.data.keys())
cmnds.add('ask-list', handle_asklist, ['OPER', 'USER', 'GUEST'])
examples.add('ask-list', 'list available subjects', 'ask-list')
## ask-experts command
def handle_askexperts(bot, event):
""" show all the experts on a subject. """
try: subject = event.args[0]
except IndexError:
event.missing('<subject>')
return
try: event.reply('experts on %s: ' % subject, experts.data[subject])
except KeyError: event.reply('we dont know any experts on this subject yet')
cmnds.add('ask-experts', handle_askexperts, ['OPER', 'USER', 'GUEST'])
examples.add('ask-experts', 'list all experts on a subject', 'ask-experts ask-bot')
## ask-subjects command
def handle_asksubjects(bot, event):
""" show all the subjects an expert handles. """
try: expert = event.args[0]
except IndexError:
event.missing('<JID>')
return
try: event.reply('subjects handled by %s: ' % expert, subjects.data[expert])
except KeyError: event.reply('%s doesnt handle any subjects' % expert)
cmnds.add('ask-subjects', handle_asksubjects, ['OPER', 'USER', 'GUEST'])
examples.add('ask-subjects', 'list all the subjects an expert handles', 'ask-subjects bthate@gmail.com')
| Python |
# jsb/plugs/common/rss.py
#
#
"""
the rss mantra is of the following:
1) add a url with !rss-add <feedname> <url>
2) use !rss-start <feed> in the channel you want the feed to appear
3) run !rss-scan <feed> to see what tokens you can use .. add them with !rss-additem <feed> <token>
4) change markup with !rss-addmarkup <feed> <markupitem> <value> .. see !rss-markuplist for possible markups
5) check with !rss-feeds in a channel to see what feeds are running in a channel
6) in case of trouble check !rss-running to see what feeds are monitored
7) enjoy
"""
## jsb imports
from jsb.lib.persist import Persist, PlugPersist
from jsb.utils.url import geturl2, striphtml, useragent
from jsb.utils.exception import handle_exception
from jsb.utils.generic import strippedtxt, fromenc, toenc, jsonstring, getwho
from jsb.utils.rsslist import rsslist
from jsb.utils.lazydict import LazyDict
from jsb.utils.statdict import StatDict
from jsb.utils.timeutils import strtotime
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.dol import Dol
from jsb.utils.pdod import Pdod
from jsb.utils.pdol import Pdol
from jsb.lib.users import users
from jsb.utils.id import getrssid
from jsb.lib.tasks import taskmanager
from jsb.lib.callbacks import callbacks
from jsb.lib.fleet import getfleet
from jsb.lib.threadloop import TimedLoop
from jsb.lib.threads import start_new_thread
from jsb.lib.errors import NoSuchBotType, FeedAlreadyExists, NameNotSet
from jsb.lib.datadir import getdatadir
from jsb.imports import getfeedparser, getjson
## google imports
try: from google.appengine.api.memcache import get, set, delete
except ImportError: from jsb.lib.cache import get, set, delete
## tinyurl import
try: from jsb.plugs.common.tinyurl import get_tinyurl
except ImportError:
def get_tinyurl(url):
return [url, ]
## basic imports
import time
import os
import types
import thread
import socket
import xml
import logging
import datetime
import hashlib
import copy
## exceptions
class RssException(Exception):
pass
class Rss301(RssException):
pass
class RssStatus(RssException):
pass
class RssBozoException(RssException):
pass
class RssNoSuchItem(RssException):
pass
## defines
feedparser = getfeedparser()
json = getjson()
cpy = copy.deepcopy
allowedtokens = ['updated', 'link', 'summary', 'tags', 'author', 'content', 'title', 'subtitle']
savelist = []
possiblemarkup = {'separator': 'set this to desired item separator', \
'all-lines': "set this to 1 if you don't want items to be aggregated", \
'tinyurl': "set this to 1 when you want to use tinyurls", 'skipmerge': \
"set this to 1 if you want to skip merge commits", 'reverse-order': \
'set this to 1 if you want the rss items displayed with oldest item first', \
'nofeedname': "if you don't want the feedname shown"}
## global data
lastpoll = PlugPersist('lastpoll')
if not lastpoll.data: lastpoll.data = LazyDict() ; lastpoll.save()
sleeptime = PlugPersist('sleeptime')
if not sleeptime.data: sleeptime.data = LazyDict() ; sleeptime.save()
runners = PlugPersist('runners')
if not runners.data: runners.data = LazyDict() ; runners.save()
## helper functions
def txtindicts(result, d):
""" return lowlevel values in (nested) dicts. """
for j in d.values():
if type(j) == types.DictType: txtindicts(result, j)
else: result.append(j)
def checkfordate(data, date):
""" see if date is in data (list of feed items). """
if not data: return False
for item in data:
try: d = item['updated']
except (KeyError, TypeError): continue
if date == d: return True
return False
def find_self_url(links):
for link in links:
logging.debug("trying link: %s" % (link))
if link.rel == 'self': return link.href
return None
## Feed class
class Feed(Persist):
""" item that contains rss data """
def __init__(self, name="nonameset", url="", owner="noownerset", itemslist=['title', 'link'], watchchannels=[], \
sleeptime=15*60, running=0):
if name:
filebase = getdatadir() + os.sep + 'plugs' + os.sep + 'jsb.plugs.common.rss' + os.sep + name
Persist.__init__(self, filebase + '-core')
if not self.data: self.data = {}
self.data = LazyDict(self.data)
self.data.length = 200
self.data['name'] = self.data.name or unicode(name)
self.data['url'] = self.data.url or unicode(url)
self.data['owner'] = self.data.owner or unicode(owner)
self.data['result'] = []
self.data['seen'] = self.data.seen or []
self.data['watchchannels'] = self.data.watchchannels or list(watchchannels)
self.data['running'] = self.data.running or running
self.itemslists = Pdol(filebase + '-itemslists')
self.markup = Pdod(filebase + '-markup')
else: raise NameNotSet()
def checkseen(self, data, itemslist=["title", "link"]):
d = {}
for item in itemslist:
try: d[item] = data[item]
except (KeyError, TypeError): continue
digest = hashlib.md5(unicode(d)).hexdigest()
return digest in self.data.seen
def setseen(self, data, itemslist=['title', 'link'], length=200):
d = {}
for item in itemslist:
d[item] = data[item]
digest = hashlib.md5(unicode(d)).hexdigest()
if digest not in self.data.seen: self.data.seen.insert(0, digest)
self.data.seen = self.data.seen[:self.data.length]
return self.data.seen
def ownercheck(self, userhost):
""" check is userhost is the owner of the feed. """
try: return self.data.owner.lower() == userhost.lower()
except KeyError: pass
return False
def save(self, coreonly=False):
""" save rss data. """
Persist.save(self)
if not coreonly:
self.itemslists.save()
self.markup.save()
def getdata(self):
""" return data from cache or run fetchdata() to retrieve them. """
url = self.data['url']
result = get(url, namespace='rss')
if result == None:
result = self.fetchdata()
set(url, result, namespace='rss')
logging.debug("got result from %s" % url)
else: logging.debug("got result from %s *cached*" % url)
return result
def fetchdata(self, data=None):
""" get data of rss feed. """
name = self.data.name
global etags
if name and etags.data.has_key(name): etag = etags.data[name]
else: etag = None
if data:
result = feedparser.parse(data.content, etag=etag)
try: status = data.status_code
except AttributeError: status = None
else:
url = self.data['url']
logging.debug("fetching %s" % url)
result = feedparser.parse(url, agent=useragent(), etag=etag)
try: status = result.status
except AttributeError: status = None
logging.info("status returned of %s feed is %s" % (name, status))
if status == 304: return []
if result: set(self.data.url, result.entries, namespace='rss')
if data:
try: etag = etags.data[name] = data.headers.get('etag') ; logging.info("etag of %s set to %s" % (name, etags.data[name])) ; etags.sync()
except KeyError: etag = None
else:
try: etag = etags.data[name] = result.etag ; logging.info("etag of %s set to %s" % (name, etags.data[name])) ; etags.sync()
except (AttributeError, KeyError): etag = None
if not name in urls.data: urls.data[name] = self.data.url ; urls.save()
logging.debug("got result from %s" % self.data.url)
if result and result.has_key('bozo_exception'): logging.warn('%s bozo_exception: %s' % (self.data.url, result['bozo_exception']))
l = len(result.entries)
if l > self.data.length: self.data.length = l ; self.save()
return result.entries
def sync(self):
""" refresh cached data of a feed. """
if not self.data.running:
logging.info("%s not enabled .. %s not syncing " % (self.data.name, self.data.url))
return False
logging.info("syncing %s - %s" % (self.data.name, self.data.url))
result = self.fetchdata()
if not result:
cached = get(self.data.url, namespace="rss")
if cached: result = cached
else: result = []
return result
def check(self, entries=None, save=True):
got = False
tobereturned = []
if entries == None: entries = self.fetchdata()
if entries:
for res in entries[::-1]:
if self.checkseen(res): continue
tobereturned.append(LazyDict(res))
got = True
self.setseen(res)
if got and save: self.save()
logging.debug("%s - %s items ready" % (self.data.name, len(tobereturned)))
return tobereturned
def deliver(self, datalist, save=True):
name = self.data.name
try:
loopover = self.data.watchchannels
logging.debug("loopover in %s deliver is: %s" % (self.data.name, loopover))
for item in loopover:
if not item: continue
try:
(botname, type, channel) = item
except ValueError:
logging.debug('%s is not in the format (botname, type, channel)' % str(item))
continue
if not botname: logging.error("%s - %s is not correct" % (name, str(item))) ; continue
if not type: logging.error("%s - %s is not correct" % (name, str(item))) ; continue
try:
bot = getfleet().byname(botname)
if not bot: bot = getfleet().makebot(type, botname)
except NoSuchBotType, ex: logging.warn("can't make bot - %s" % str(ex)) ; continue
if not bot: logging.error("can't find %s bot in fleet" % botname) ; continue
res2 = datalist
if type == "irc" and not '#' in channel: nick = getwho(bot, channel)
else: nick = None
if self.markup.get(jsonstring([name, type, channel]), 'reverse-order'): res2 = res2[::-1]
if self.markup.get(jsonstring([name, type, channel]), 'all-lines'):
for i in res2:
response = self.makeresponse(name, type, [i, ], channel)
try: bot.saynocb(nick or channel, response)
except Exception, ex: handle_exception()
else:
sep = self.markup.get(jsonstring([name, type, channel]), 'separator')
if sep: response = self.makeresponse(name, type, res2, channel, sep=sep)
else: response = self.makeresponse(name, type, res2, channel)
try: bot.saynocb(nick or channel, response)
except Exception, ex: handle_exception()
return True
except Exception, ex: handle_exception(txt=name) ; return False
def makeresponse(self, name, type, res, channel, sep=" || "):
""" loop over result to make a response. """
if self.markup.get(jsonstring([name, type, channel]), 'nofeedname'): result = u""
else: result = u"<b>[%s]</b> - " % name
try: itemslist = self.itemslists.data[jsonstring([name, type, channel])]
except KeyError:
itemslist = self.itemslists.data[jsonstring([name, type, channel])] = ['title', 'link']
self.itemslists.save()
for j in res:
if self.markup.get(jsonstring([name, type, channel]), 'skipmerge') and 'Merge branch' in j['title']: continue
resultstr = u""
for i in itemslist:
try:
item = getattr(j, i)
if not item: continue
item = unicode(item)
if item.startswith('http://'):
if self.markup.get(jsonstring([name, type, channel]), 'tinyurl'):
try:
tinyurl = get_tinyurl(item)
logging.debug(' tinyurl is: %s' % str(tinyurl))
if not tinyurl: resultstr += u"%s - " % item
else: resultstr += u"%s - " % tinyurl[0]
except Exception, ex:
handle_exception()
resultstr += u"%s - " % item
else: resultstr += u"%s - " % item
else: resultstr += u"%s - " % item.strip()
except (KeyError, AttributeError, TypeError), ex: logging.warn('%s - %s' % (name, str(ex))) ; continue
resultstr = resultstr[:-3]
if resultstr: result += u"%s %s " % (resultstr, sep)
return result[:-(len(sep)+2)]
def all(self):
""" get all entries of the feed. """
return self.getdata()
def search(self, item, search):
""" search feed entries. """
res = []
for result in self.all():
try: i = getattr(result, item)
except AttributeError: continue
if i and search in i: res.append(i)
return res
## Rssdict class
class Rssdict(PlugPersist):
""" dict of rss entries """
def __init__(self, filename, feedname=None):
self.sleepsec = 900
self.feeds = LazyDict()
PlugPersist.__init__(self, filename)
if not self.data:
self.data = LazyDict()
self.data['names'] = []
self.data['urls'] = {}
else:
self.data = LazyDict(self.data)
if not self.data.has_key('names'): self.data['names'] = []
if not self.data.has_key('urls'): self.data['urls'] = {}
if not feedname: pass
else: self.feeds[feedname] = Feed(feedname)
#self.startwatchers()
def save(self, namein=None):
""" save all feeds or provide a feedname to save. """
PlugPersist.save(self)
for name, feed in self.feeds.iteritems():
if namein and name != namein: continue
try: feed.save()
except Exception, ex: handle_exception()
def size(self):
""" return number of rss feeds. """
return len(self.data['names'])
def add(self, name, url, owner):
""" add rss item. """
logging.warn('adding %s - %s - (%s)' % (name, url, owner))
if name not in self.data['names']: self.data['names'].append(name)
self.feeds[name] = Feed(name, url, owner, ['title', 'link'])
self.data['urls'][url] = name
self.feeds[name].save()
self.watch(name)
self.save(name)
def delete(self, name):
""" delete rss item by name. """
target = self.byname(name)
if target:
target.data.stoprunning = 1
target.data.running = 0
target.save()
try: del self.feeds[name]
except KeyError: pass
try: self.data['names'].remove(name)
except ValueError: pass
self.save()
def byname(self, name):
""" return rss item by name. """
if not name: return
item = Feed(name)
if item.data.url: return item
def cloneurl(self, url, auth):
""" add feeds from remote url. """
data = geturl2(url)
got = []
for line in data.split('\n'):
try: (name, url) = line.split()
except ValueError: logging.debug("cloneurl - can't split %s line" % line) ; continue
if self.byname(name): logging.debug('cloneurl - already got %s feed' % name) ; continue
if url.endswith('<br>'): url = url[:-4]
self.add(name, url, auth)
got.append(name)
return got
def getdata(self, name):
""" get data of rss feed. """
rssitem = self.byname(name)
if rssitem == None: raise RssNoSuchItem("no %s rss item found" % name)
return rssitem.getdata()
def watch(self, name, sleepsec=900):
""" start a watcher thread """
logging.debug('trying %s rss feed watcher' % name)
rssitem = self.byname(name)
if rssitem == None: raise RssNoItem()
rssitem.data.running = 1
rssitem.data.stoprunning = 0
rssitem.check(rssitem.sync())
rssitem.save()
if not name in runners.data: runners.data[name] = "bla" ; runners.save()
sleeptime.data[name] = sleepsec
sleeptime.save()
logging.info('started %s rss watch' % name)
## Rsswatcher class
class Rsswatcher(Rssdict):
""" rss watchers. """
def checkfeed(self, url, event):
""" get data of rss feed. """
result = feedparser.parse(url, agent=useragent())
logging.info("fetch - got result from %s" % url)
if result and result.has_key('bozo_exception'):
event.reply('%s bozo_exception: %s' % (url, result['bozo_exception']))
return True
try: status = result.status ; event.reply("%s - status is %s" % (url, status))
except AttributeError: status = 200
if status != 200 and status != 301 and status != 302: return False
return True
def byurl(self, url):
try: name = self.data['urls'][url]
except KeyError: return
return self.byname(name)
def handle_data(self, data, name=None):
""" handle data received in callback. """
try:
if name: rssitem = self.byname(name)
else: url = find_self_url(result.feed.links) ; rssitem = self.byurl(url)
if rssitem: name = rssitem.data.name
else: logging.warn("can't find %s item" % url) ; del data ; return
if not name in urls.data: urls.data[name] = url ; urls.save()
result = rssitem.fetchdata(data)
logging.warn("%s - got %s items from feed" % (name, len(result)))
res = rssitem.check(result)
if res: rssitem.deliver(res, save=True)
else: logging.warn("%s - no items to deliver" % name)
except Exception, ex: handle_exception(txt=name)
del data
return True
def getall(self):
""" get all feeds. """
for name in self.data['names']: self.feeds[name] = Feed(name)
return self.feeds
def shouldpoll(self, name, curtime):
""" check whether poll of feed in needed. """
return self.byname(name).shouldpoll(curtime)
def get(self, name, userhost, save=True):
""" get entries for a user. """
return self.byname(name).get(userhost, save)
def check(self, name, entries=None, save=True):
""" check for updates. """
return self.byname(name).check(entries=entries, save=save)
def syncdeliver(self, name):
""" sync a feed. """
feed = self.byname(name)
if feed:
result = feed.sync()
if result:
res2 = feed.check(result)
if res2: feed.deliver(res2)
def ownercheck(self, name, userhost):
""" check if userhost is the owner of feed. """
try:
feed = self.byname(name)
if feed: return feed.ownercheck(userhost)
except KeyError: pass
return False
def changeinterval(self, name, interval):
""" not implemented yet. """
sleeptime.data[name] = interval
sleeptime.save()
def stopwatchers(self):
""" stop all watcher threads. """
for j, z in self.data.iteritems():
if z.data.running: z.data.stoprunning = 1
def dowatch(self, name, sleeptime=1800):
""" start a watcher. """
rssitem = self.byname(name)
if not rssitem == None:
logging.error("no %s rss item available" % name)
return
while 1:
try: self.watch(name)
except Exception, ex:
logging.warn('%s feed error: %s' % (name, str(ex)))
if not rssitem.data.running: break
else: break
def stopwatch(self, name, save=True):
""" stop watcher thread. """
try:
feed = self.byname(name)
if feed:
feed.data.running = 0
feed.data.stoprunning = 1
if save: feed.save()
except KeyError: pass
try:
del runners.data[name]
if save: runners.save()
return True
except KeyError: pass
return False
def list(self):
""" return of rss names. """
feeds = self.data['names']
return feeds
def runners(self):
if runners.data: return runners.data.keys()
return []
def checkrunners(self):
""" show names/channels of running watchers. """
result = []
for name in self.data['names']:
z = self.byname(name)
if z and z.data.running == 1 and not z.data.stoprunning:
result.append((z.data.name, z.data.watchchannels))
runners.data[name] = z.data.watchchannels
runners.save()
return result
def getfeeds(self, botname, type, channel):
""" show names/channels of running watcher. """
result = []
for name in self.runners():
z = self.byname(name)
if not z or not z.data.running: continue
if jsonstring([botname, type, channel]) in z.data.watchchannels or [botname, type, channel] in z.data.watchchannels:
result.append(z.data.name)
return result
def url(self, name):
""" return url of rssitem. """
return self.byname(name).data.url
def seturl(self, name, url):
""" set url of rssitem. """
feed = self.byname(name)
feed.data.url = url
feed.save()
return True
def scan(self, name):
""" scan a rss url for tokens. """
keys = []
items = self.byname(name).getdata()
for item in items:
for key in item:
keys.append(key)
statdict = StatDict()
for key in keys: statdict.upitem(key)
return statdict.top()
def search(self, name, item, search):
""" search titles of a feeds cached data. """
i = self.byname(name)
if i: return i.search(item, search)
return []
def searchall(self, item, search):
""" search titles of all cached data. """
res = []
for name in self.data['names']:
feed = self.byname(name)
res.append(str(feed.search(item, search)))
return res
def all(self, name, item):
""" search all cached data of a feed. """
res = []
feed = self.byname(name)
if not feed: return res
for result in feed.all():
try: txt = getattr(result, item)
except AttributeError: continue
if txt: res.append(txt)
return res
def startwatchers(self):
""" start watcher threads """
for name in self.data['names']:
z = self.byname(name)
if z and z.data.running: self.watch(z.data.name)
def start(self, botname, bottype, name, channel):
""" start a rss feed (per user/channel). """
rssitem = self.byname(name)
if rssitem == None: logging.warn("we don't have a %s rss object" % name) ; return False
target = channel
if not jsonstring([botname, bottype, target]) in rssitem.data.watchchannels and not [botname, bottype, target] in rssitem.data.watchchannels:
rssitem.data.watchchannels.append([botname, bottype, target])
rssitem.itemslists[jsonstring([name, bottype, target])] = ['title', 'link']
rssitem.markup.set(jsonstring([name, bottype, target]), 'tinyurl', 1)
rssitem.data.running = 1
rssitem.data.stoprunning = 0
rssitem.save()
watcher.watch(name)
logging.warn("started %s feed in %s channel" % (name, channel))
return True
def stop(self, botname, bottype, name, channel):
""" stop a rss feed (per user/channel). """
rssitem = self.byname(name)
if not rssitem: return False
try:
rssitem.data.watchchannels.remove([botname, bottype, channel])
rssitem.save()
logging.warn("stopped %s feed in %s channel" % (name, channel))
except ValueError: return False
return True
def clone(self, botname, bottype, newchannel, oldchannel):
""" clone feeds from one channel to another. """
feeds = self.getfeeds(botname, oldchannel)
for feed in feeds:
self.stop(botname, bottype, feed, oldchannel)
self.start(botname, bottype, feed, newchannel)
return feeds
## more global defines
watcher = Rsswatcher('rss')
urls = PlugPersist('urls')
etags = PlugPersist('etags')
assert(watcher)
## dosync function
def dummycb(bot, event): pass
callbacks.add('START', dummycb)
def dosync(feedname):
""" main level function to be deferred by periodical. """
try:
logging.info("doing sync of %s" % feedname)
localwatcher = Rsswatcher('rss', feedname)
localwatcher.syncdeliver(feedname)
except RssException, ex: logging.error("%s - error: %s" % (feedname, str(ex)))
## shouldpoll function
def shouldpoll(name, curtime):
""" check whether a new poll is needed. """
global lastpoll
try: lp = lastpoll.data[name]
except KeyError: lp = lastpoll.data[name] = time.time() ; lastpoll.sync()
global sleeptime
try: st = sleeptime.data[name]
except KeyError: st = sleeptime.data[name] = 900 ; sleeptime.sync()
logging.debug("pollcheck - %s - %s - remaining %s" % (name, time.ctime(lp), (lp + st) - curtime))
if curtime - lp > st: return True
## dodata function
def dodata(data, name):
watcher.handle_data(data, name=name)
## rssfetchcb callback
def rssfetchcb(rpc):
import google
try: data = rpc.get_result()
except google.appengine.api.urlfetch_errors.DownloadError, ex: logging.warn("%s - error: %s" % (rpc.final_url, str(ex))) ; return
name = rpc.feedname
logging.debug("headers of %s: %s" % (name, unicode(data.headers)))
if data.status_code == 200:
logging.info("defered %s feed" % rpc.feedname)
from google.appengine.ext.deferred import defer
defer(dodata, data, rpc.feedname)
else: logging.warn("fetch returned status code %s - %s" % (data.status_code, rpc.feedurl))
## creaete_rsscallback function
def create_rsscallback(rpc):
return lambda: rssfetchcb(rpc)
## doperiodicalGAE function
def doperiodicalGAE(*args, **kwargs):
""" rss periodical function. """
from google.appengine.api import urlfetch
curtime = time.time()
feedstofetch = []
rpcs = []
for feed in watcher.runners():
if not shouldpoll(feed, curtime): continue
feedstofetch.append(feed)
logging.info("feeds to fetch: %s" % str(feedstofetch))
got = False
for f in feedstofetch:
if not f: continue
lastpoll.data[f] = curtime
if f not in urls.data: url = Feed(f).data.url ; urls.data[f] = url ; got = True
else: url = urls.data[f]
rpc = urlfetch.create_rpc()
rpc.feedname = f
rpc.callback = create_rsscallback(rpc)
rpc.feedurl = url
try: etag = etags.data[f]
except KeyError: etag = ""
logging.info("%s - sending request - %s" % (f, etag))
try: urlfetch.make_fetch_call(rpc, url, headers={"If-None-Match": etag}) ; rpcs.append(rpc)
except Exception, ex: handle_exception()
for rpc in rpcs:
try: rpc.wait()
except Exception, ex: handle_exception()
if feedstofetch: lastpoll.save()
if got: urls.save()
## doperiodical function
def doperiodical(*args, **kwargs):
""" rss periodical function. """
curtime = time.time()
for feed in watcher.data.names:
if not shouldpoll(feed, curtime): continue
lastpoll.data[feed] = curtime
logging.debug("periodical - launching %s" % feed)
try:
from google.appengine.ext.deferred import defer
defer(dosync, feed)
except ImportError:
try: start_new_thread(dosync, (feed, ))
except Exception, ex: handle_exception() ; return
lastpoll.save()
callbacks.add('TICK', doperiodical)
## init function
def init():
taskmanager.add('rss', doperiodicalGAE)
if not runners.data: watcher.checkrunners()
## shutdown function
def shutdown():
taskmanager.unload('rss')
## size function
def size():
""" return number of watched rss entries. """
return watcher.size()
## save function
def save():
""" save watcher data. """
watcher.save()
## rss-clone command
def handle_rssclone(bot, event):
""" clone feed running in a channel. """
if not event.rest: event.missing('<channel>') ; event.done()
feeds = watcher.clone(bot.cfg.name, event.channel, event.rest)
event.reply('cloned the following feeds: ', feeds)
bot.say(event.rest, "this wave is continued in %s" % event.url)
cmnds.add('rss-clone', handle_rssclone, 'USER')
examples.add('rss-clone', 'clone feeds into new channel', 'wave-clone waveid')
## rss-cloneurl command
def handle_rsscloneurl(bot, event):
""" clone feeds from another bot (pointed to by url). """
if not event.rest: event.missing('<url>') ; event.done
feeds = watcher.cloneurl(event.rest, event.auth)
event.reply('cloned the following feeds: ', feeds)
cmnds.add('rss-cloneurl', handle_rsscloneurl, 'OPER')
examples.add('rss-cloneurl', 'clone feeds from remote url', 'wave-clone jsonbot-hg http://jsonbot.appspot.com')
## rss-add command
def handle_rssadd(bot, ievent):
""" rss-add <name> <url> .. add a rss item. """
try: (name, url) = ievent.args
except ValueError: ievent.missing('<name> <url>') ; return
if watcher.checkfeed(url, ievent): watcher.add(name, url, ievent.userhost) ; ievent.reply('rss item added')
else: ievent.reply('%s is not valid' % url)
cmnds.add('rss-add', handle_rssadd, 'USER')
examples.add('rss-add', 'rss-add <name> <url> to the rsswatcher', 'rss-add jsonbot http://code.google.com/feeds/p/jsonbot/hgchanges/basic')
## rss-register command
def handle_rssregister(bot, ievent):
""" rss-register <name> <url> .. register and start a rss item. """
try: (name, url) = ievent.args
except ValueError: ievent.missing('<name> <url>') ; return
if watcher.byname(name):
ievent.reply('we already have a feed with %s name .. plz choose a different name' % name)
return
if watcher.checkfeed(url, ievent):
watcher.add(name, url, ievent.userhost)
watcher.start(bot.cfg.name, bot.type, name, ievent.channel)
if name not in ievent.chan.data.feeds: ievent.chan.data.feeds.append(name) ; ievent.chan.save()
ievent.reply('rss item added and started in channel %s' % ievent.channel)
else: ievent.reply('%s is not valid' % url)
cmnds.add('rss-register', handle_rssregister, 'USER')
examples.add('rss-register', 'rss-register <name> <url> - register and start a rss feed', 'rss-register jsonbot-hg http://code.google.com/feeds/p/jsonbot/hgchanges/basic')
## rss-del command
def handle_rssdel(bot, ievent):
""" rss-del <name> .. delete a rss item. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
rssitem = watcher.byname(name)
if rssitem:
if not watcher.ownercheck(name, ievent.userhost): ievent.reply("you are not the owner of the %s feed" % name) ; return
watcher.stopwatch(name)
watcher.delete(name)
ievent.reply('rss item deleted')
else: ievent.reply('there is no %s rss item' % name)
cmnds.add('rss-del', handle_rssdel, ['USER', ])
examples.add('rss-del', 'rss-del <name> .. remove <name> from the rsswatcher', 'rss-del mekker')
## rss-sync command
def handle_rsssync(bot, ievent):
""" rss-del <name> .. delete a rss item. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
if name in watcher.data['names']: watcher.byname(name).sync() ; ievent.done()
else: ievent.reply("no %s feed available" % name)
cmnds.add('rss-sync', handle_rsssync, ['OPER', ])
examples.add('rss-sync', 'rss-sync <name> .. sync <name> feed', 'rss-sync mekker')
## rss-watch command
def handle_rsswatch(bot, ievent):
""" rss-watch <name> .. start watcher thread. """
if not ievent.channel: ievent.reply('no channel provided')
try: name, sleepsec = ievent.args
except ValueError:
try: name = ievent.args[0] ; sleepsec = 1800
except IndexError: ievent.missing('<name> [secondstosleep]') ; return
try: sleepsec = int(sleepsec)
except ValueError: ievent.reply("time to sleep needs to be in seconds") ; return
if name == "all": target = watcher.data.names
else: target = [name, ]
got = []
for feed in target:
rssitem = watcher.byname(feed)
if rssitem == None: continue
if not sleeptime.data.has_key(name): sleeptime.data[feed] = sleepsec ; sleeptime.save()
try: watcher.watch(feed, sleepsec)
except Exception, ex: ievent.reply('%s - %s' % (feed, str(ex))) ; continue
got.append(feed)
if got: ievent.reply('watcher started ', got)
else: ievent.reply('already watching ', target)
cmnds.add('rss-watch', handle_rsswatch, 'USER')
examples.add('rss-watch', 'rss-watch <name> [seconds to sleep] .. go watching <name>', '1) rss-watch jsonbot 2) rss-watch jsonbot 600')
## rss-start command
def handle_rssstart(bot, ievent):
""" rss-start <name> .. start a rss feed to a user. """
feeds = ievent.args
if not feeds: ievent.missing('<list of feeds>') ; return
started = []
if feeds[0] == 'all': feeds = watcher.list()
for name in feeds:
watcher.start(bot.cfg.name, bot.type, name, ievent.channel)
if name not in ievent.chan.data.feeds: ievent.chan.data.feeds.append(name) ; ievent.chan.save()
started.append(name)
ievent.reply('started: ', started)
cmnds.add('rss-start', handle_rssstart, ['RSS', 'USER'])
examples.add('rss-start', 'rss-start <name> .. start a rss feed \
(per user/channel) ', 'rss-start jsonbot')
## rss-stop command
def handle_rssstop(bot, ievent):
""" rss-start <name> .. start a rss feed to a user. """
if not ievent.rest: ievent.missing('<feed name>') ; return
if ievent.rest == "all": loopover = ievent.chan.data.feeds
else: loopover = [ievent.rest, ]
stopped = []
for name in loopover:
if name in ievent.chan.data.feeds: ievent.chan.data.feeds.remove(name)
rssitem = watcher.byname(name)
target = ievent.channel
if rssitem == None: continue
if not rssitem.data.running: continue
try: rssitem.data.watchchannels.remove([bot.cfg.name, bot.type, target])
except ValueError:
try: rssitem.data.watchchannels.remove([bot.cfg.name, bot.type, target])
except ValueError: continue
rssitem.save()
stopped.append(name)
ievent.chan.save()
ievent.reply('stopped feeds: ', stopped)
cmnds.add('rss-stop', handle_rssstop, ['RSS', 'USER'])
examples.add('rss-stop', 'rss-stop <name> .. stop a rss feed (per user/channel) ', 'rss-stop jsonbot')
## rss-stopall command
def handle_rssstopall(bot, ievent):
""" rss-stop <name> .. stop all rss feeds to a channel. """
if not ievent.rest: target = ievent.channel
else: target = ievent.rest
stopped = []
feeds = watcher.getfeeds(bot.cfg.name, bot.type, target)
if feeds:
for feed in feeds:
if watcher.stop(bot.cfg.name, bot.type, feed, target):
if feed in ievent.chan.data.feeds: ievent.chan.data.feeds.remove(feed) ; ievent.chan.save()
stopped.append(feed)
ievent.reply('stopped feeds: ', stopped)
else: ievent.reply('no feeds running in %s' % target)
cmnds.add('rss-stopall', handle_rssstopall, ['RSS', 'OPER'])
examples.add('rss-stopall', 'rss-stopall .. stop all rss feeds (per user/channel) ', 'rss-stopall')
## rss-channels command
def handle_rsschannels(bot, ievent):
""" rss-channels <name> .. show channels of rss feed. """
try: name = ievent.args[0]
except IndexError: ievent.missing("<name>") ; return
rssitem = watcher.byname(name)
if rssitem == None: ievent.reply("we don't have a %s rss object" % name) ; return
if not rssitem.data.watchchannels: ievent.reply('%s is not in watch mode' % name) ; return
result = []
for i in rssitem.data.watchchannels: result.append(str(i))
ievent.reply("channels of %s: " % name, result)
cmnds.add('rss-channels', handle_rsschannels, ['OPER', ])
examples.add('rss-channels', 'rss-channels <name> .. show channels', 'rss-channels jsonbot')
## rss-addchannel command
def handle_rssaddchannel(bot, ievent):
""" rss-addchannel <name> [<botname>] <channel> .. add a channel to rss item. """
try: (name, botname, type, channel) = ievent.args
except ValueError:
try: (name, channel) = ievent.args ; botname = bot.cfg.name ; type = bot.type
except ValueError:
try: name = ievent.args[0] ; botname = bot.cfg.name ; type = bot.type ; channel = ievent.channel
except IndexError: ievent.missing('<name> [<botname>] <channel>') ; return
rssitem = watcher.byname(name)
if rssitem == None: ievent.reply("we don't have a %s rss object" % name) ; return
if not rssitem.data.running: ievent.reply('%s watcher is not running' % name) ; return
if jsonstring([botname, type, channel]) in rssitem.data.watchchannels or [botname, channel] in rssitem.data.watchchannels:
ievent.reply('we are already monitoring %s on (%s,%s)' % (name, botname, channel))
return
rssitem.data.watchchannels.append([botname, type, channel])
rssitem.save()
ievent.reply('%s added to %s rss item' % (channel, name))
cmnds.add('rss-addchannel', handle_rssaddchannel, ['OPER', ])
examples.add('rss-addchannel', 'add a channel to watchchannels of a feed', '1) rss-addchannel jsonbot #dunkbots 2) rss-addchannel jsonbot main #dunkbots')
## rss-setitems command
def handle_rsssetitems(bot, ievent):
""" set items of a rss feed. """
try: (name, items) = ievent.args[0], ievent.args[1:]
except (ValueError, IndexError): ievent.missing('<name> <items>') ; return
target = ievent.channel
rssitem = watcher.byname(name)
if not rssitem: ievent.reply("we don't have a %s feed" % name) ; return
rssitem.itemslists.data[jsonstring([name, bot.type, target])] = items
rssitem.itemslists.save()
ievent.reply('%s added to (%s,%s) itemslist' % (items, name, target))
cmnds.add('rss-setitems', handle_rsssetitems, ['RSS', 'USER'])
examples.add('rss-setitems', 'set tokens of the itemslist (per user/channel)', 'rss-setitems jsonbot author author link pubDate')
## rss-additem command
def handle_rssadditem(bot, ievent):
""" add an item (token) to a feeds itemslist. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<name> <item>') ; return
target = ievent.channel
feed = watcher.byname(name)
if not feed: ievent.reply("we don't have a %s feed" % name) ; return
try: feed.itemslists.data[jsonstring([name, bot.type, target])].append(item)
except KeyError: feed.itemslists.data[jsonstring([name, bot.type, target])] = ['title', 'link']
feed.itemslists.save()
ievent.reply('%s added to (%s,%s) itemslist' % (item, name, target))
cmnds.add('rss-additem', handle_rssadditem, ['RSS', 'USER'])
examples.add('rss-additem', 'add a token to the itemslist (per user/channel)',\
'rss-additem jsonbot link')
## rss-delitem command
def handle_rssdelitem(bot, ievent):
""" delete item from a feeds itemlist. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<name> <item>') ; return
target = ievent.channel
rssitem = watcher.byname(name)
if not rssitem: ievent.reply("we don't have a %s feed" % name) ; return
try:
rssitem.itemslists.data[jsonstring([name, bot.type, target])].remove(item)
rssitem.itemslists.save()
except (ValueError, KeyError): ievent.reply("we don't have a %s rss feed" % name) ; return
ievent.reply('%s removed from (%s,%s) itemslist' % (item, name, target))
cmnds.add('rss-delitem', handle_rssdelitem, ['RSS', 'USER'])
examples.add('rss-delitem', 'remove a token from the itemslist (per user/channel)', 'rss-delitem jsonbot link')
## rss-markuplist command
def handle_rssmarkuplist(bot, ievent):
""" show possible markups that can be used. """
ievent.reply('possible markups ==> ' , possiblemarkup)
cmnds.add('rss-markuplist', handle_rssmarkuplist, ['USER', ])
examples.add('rss-markuplist', 'show possible markup entries', 'rss-markuplist')
## rss-markup command
def handle_rssmarkup(bot, ievent):
""" show the markup of a feed. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
rssitem = watcher.byname(name)
if not rssitem: ievent.reply("we don't have a %s feed" % name) ; return
target = ievent.channel
try: ievent.reply(str(rssitem.markup[jsonstring([name, bot.type, target])]))
except KeyError: pass
cmnds.add('rss-markup', handle_rssmarkup, ['RSS', 'USER'])
examples.add('rss-markup', 'show markup list for a feed (per user/channel)', 'rss-markup jsonbot')
## rss-addmarkup command
def handle_rssaddmarkup(bot, ievent):
""" add a markup to a feeds markuplist. """
try: (name, item, value) = ievent.args
except ValueError: ievent.missing('<name> <item> <value>') ; return
rssitem = watcher.byname(name)
if not rssitem: ievent.reply("we don't have a %s feed" % name) ; return
target = ievent.channel
try: value = int(value)
except ValueError: pass
try:
rssitem.markup.set(jsonstring([name, bot.type, target]), item, value)
rssitem.markup.save()
ievent.reply('%s added to (%s,%s) markuplist' % (item, name, target))
except KeyError: ievent.reply("no (%s,%s) feed available" % (name, target))
cmnds.add('rss-addmarkup', handle_rssaddmarkup, ['RSS', 'USER'])
examples.add('rss-addmarkup', 'add a markup option to the markuplist (per user/channel)', 'rss-addmarkup jsonbot all-lines 1')
## rss-delmarkup command
def handle_rssdelmarkup(bot, ievent):
""" delete markup from a feeds markuplist. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<name> <item>') ; return
rssitem = watcher.byname(name)
if not rssitem: ievent.reply("we don't have a %s feed" % name) ; return
target = ievent.channel
try: del rssitem.markup[jsonstring([name, bot.type, target])][item]
except (KeyError, TypeError): ievent.reply("can't remove %s from %s feed's markup" % (item, name)) ; return
rssitem.markup.save()
ievent.reply('%s removed from (%s,%s) markuplist' % (item, name, target))
cmnds.add('rss-delmarkup', handle_rssdelmarkup, ['RSS', 'USER'])
examples.add('rss-delmarkup', 'remove a markup option from the markuplist (per user/channel)', 'rss-delmarkup jsonbot all-lines')
## rss-delchannel command
def handle_rssdelchannel(bot, ievent):
""" delete channel from feed. """
botname = None
try: (name, botname, type, channel) = ievent.args
except ValueError:
try: (name, channel) = ievent.args ; type = bot.type ; botname = bot.cfg.name
except ValueError:
try:
name = ievent.args[0]
botname = bot.cfg.name
type = bot.type
channel = ievent.channel
except IndexError: ievent.missing('<name> [<botname>] [<channel>]') ; return
rssitem = watcher.byname(name)
if rssitem == None: ievent.reply("we don't have a %s rss object" % name) ; return
if jsonstring([botname, type, channel]) in rssitem.data.watchchannels:
rssitem.data.watchchannels.remove(jsonstring([botname, type, channel]))
ievent.reply('%s removed from %s rss item' % (channel, name))
elif [botname, type, channel] in rssitem.data.watchchannels:
rssitem.data.watchchannels.remove([botname, type, channel])
ievent.reply('%s removed from %s rss item' % (channel, name))
else: ievent.reply('we are not monitoring %s on (%s,%s)' % (name, botname, channel)) ; return
rssitem.save()
cmnds.add('rss-delchannel', handle_rssdelchannel, ['OPER', ])
examples.add('rss-delchannel', 'delete channel from feed', '1) rss-delchannel jsonbot #dunkbots 2) rss-delchannel jsonbot main #dunkbots')
## rss-stopwatch command
def handle_rssstopwatch(bot, ievent):
""" stop watching a feed. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
stopped = []
if name == "all":
for name in watcher.runners():
if watcher.stopwatch(name): stopped.append(name)
else:
if watcher.stopwatch(name): stopped.append(name)
ievent.reply('stopped rss watchers: ', stopped)
cmnds.add('rss-stopwatch', handle_rssstopwatch, ['OPER', ])
examples.add('rss-stopwatch', 'rss-stopwatch <name> .. stop polling <name>', 'rss-stopwatch jsonbot')
## rss-sleeptime command
def handle_rsssleeptime(bot, ievent):
""" get sleeptime of rss item. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
try: ievent.reply('sleeptime for %s is %s seconds' % (name, str(sleeptime.data[name])))
except KeyError: ievent.reply("can't get sleeptime for %s" % name)
cmnds.add('rss-sleeptime', handle_rsssleeptime, 'USER')
examples.add('rss-sleeptime', 'rss-sleeptime <name> .. get sleeping time \
for <name>', 'rss-sleeptime jsonbot')
## rss-setsleeptime command
def handle_rsssetsleeptime(bot, ievent):
""" set sleeptime of feed. """
try: (name, sec) = ievent.args ; sec = int(sec)
except ValueError: ievent.missing('<name> <seconds>') ; return
if not watcher.ownercheck(name, ievent.userhost): ievent.reply("you are not the owner of the %s feed" % name) ; return
if sec < 60: ievent.reply('min is 60 seconds') ; return
rssitem = watcher.byname(name)
if rssitem == None: ievent.reply("we don't have a %s rss item" % name) ; return
rssitem.data.sleeptime = sec
if rssitem.data.running:
try: watcher.changeinterval(name, sec)
except KeyError, ex: ievent.reply("failed to set interval: %s" % str(ex)) ; return
ievent.reply('sleeptime set')
cmnds.add('rss-setsleeptime', handle_rsssetsleeptime, ['USER', ])
examples.add('rss-setsleeptime', 'rss-setsleeptime <name> <seconds> .. set \
sleeping time for <name> .. min 60 sec', 'rss-setsleeptime jsonbot 600')
## rss-get command
def handle_rssget(bot, ievent):
""" fetch feed data. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
channel = ievent.channel
rssitem = watcher.byname(name)
if rssitem == None: ievent.reply("we don't have a %s rss item" % name) ; return
try: result = watcher.getdata(name)
except Exception, ex: ievent.reply('%s error: %s' % (name, str(ex))) ; return
if rssitem.markup.get(jsonstring([name, bot.type, channel]), 'reverse-order'): result = result[::-1]
response = rssitem.makeresponse(name, bot.type, result, ievent.channel)
if response: ievent.reply("results of %s: %s" % (name, response))
else: ievent.reply("can't make a reponse out of %s" % name)
cmnds.add('rss-get', handle_rssget, ['RSS', 'USER'], threaded=True)
examples.add('rss-get', 'rss-get <name> .. get data from <name>', 'rss-get jsonbot')
## rss-running command
def handle_rssrunning(bot, ievent):
""" show which watchers are running. """
result = watcher.runners()
resultlist = []
teller = 1
for i in result: resultlist.append(i)
if resultlist: ievent.reply("running rss watchers: ", resultlist)
else: ievent.reply('nothing running yet')
cmnds.add('rss-running', handle_rssrunning, ['RSS', 'USER'])
examples.add('rss-running', 'rss-running .. get running rsswatchers', \
'rss-running')
## rss-list command
def handle_rsslist(bot, ievent):
""" return list of rss items. """
result = watcher.list()
result.sort()
if result: ievent.reply("rss items: ", result)
else: ievent.reply('no rss items yet')
cmnds.add('rss-list', handle_rsslist, ['RSS', 'USER'])
examples.add('rss-list', 'get list of rss items', 'rss-list')
## rss-url command
def handle_rssurl(bot, ievent):
""" return url of feed. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
if not watcher.ownercheck(name, ievent.userhost): ievent.reply("you are not the owner of the %s feed" % name) ; return
result = watcher.url(name)
if not result: ievent.reply("don't know url for %s" % name) ; return
try:
if ':' in result.split('/')[1]:
if not ievent.msg: ievent.reply('run this command in a private message') ; return
except (TypeError, ValueError, IndexError): pass
ievent.reply('url of %s: %s' % (name, result))
cmnds.add('rss-url', handle_rssurl, ['OPER', ])
examples.add('rss-url', 'get url of feed', 'rss-url jsonbot')
## rss-seturl command
def handle_rssseturl(bot, ievent):
""" set url of feed. """
try: name = ievent.args[0] ; url = ievent.args[1]
except IndexError: ievent.missing('<name> <url>') ; return
if not watcher.ownercheck(name, ievent.userhost): ievent.reply("you are not the owner of the %s feed" % name) ; return
oldurl = watcher.url(name)
if not oldurl: ievent.reply("no %s rss item found" % name) ; return
if watcher.seturl(name, url):
rssitem = watcher.byname(name)
rssitem.sync()
ievent.reply('url of %s changed' % name)
else: ievent.reply('failed to set url of %s to %s' % (name, url))
cmnds.add('rss-seturl', handle_rssseturl, ['USER', ])
examples.add('rss-seturl', 'change url of rssitem', 'rss-seturl jsonbot-hg http://code.google.com/feeds/p/jsonbot/hgchanges/basic')
## rss-itemslist
def handle_rssitemslist(bot, ievent):
""" rss-itemslist <name> .. show itemslist of rss item. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
rssitem = watcher.byname(name)
if not rssitem: ievent.reply("we don't have a %s feed." % name) ; return
try: itemslist = rssitem.itemslists[jsonstring([name, bot.type, ievent.channel])]
except KeyError: ievent.reply("no itemslist set for (%s, %s)" % (name, ievent.channel)) ; return
ievent.reply("itemslist of (%s, %s): " % (name, ievent.channel), itemslist)
cmnds.add('rss-itemslist', handle_rssitemslist, ['RSS', 'USER'])
examples.add('rss-itemslist', 'get itemslist of feed', 'rss-itemslist jsonbot')
## rss-scan command
def handle_rssscan(bot, ievent):
""" scan rss item for used xml tokens. """
try: name = ievent.args[0]
except IndexError: ievent.missing('<name>') ; return
if not watcher.byname(name): ievent.reply('no %s feeds available' % name) ; return
try: result = watcher.scan(name)
except Exception, ex: ievent.reply(str(ex)) ; return
if result == None: ievent.reply("can't get data for %s" % name) ; return
res = []
for i in result: res.append("%s=%s" % i)
ievent.reply("tokens of %s: " % name, res)
cmnds.add('rss-scan', handle_rssscan, ['USER', ])
examples.add('rss-scan', 'rss-scan <name> .. get possible items of <name> ', 'rss-scan jsonbot')
## rss-feeds
def handle_rssfeeds(bot, ievent):
""" show what feeds are running in a channel. """
try: channel = ievent.args[0]
except IndexError: channel = ievent.channel
result = watcher.getfeeds(bot.cfg.name, bot.type, channel)
if result: ievent.reply("feeds running in %s: " % channel, result)
else: ievent.reply('%s has no feeds running' % channel)
cmnds.add('rss-feeds', handle_rssfeeds, ['USER', 'RSS'])
examples.add('rss-feeds', 'rss-feeds <name> .. show what feeds are running in a channel', '1) rss-feeds 2) rss-feeds #dunkbots')
## rss-link command
def handle_rsslink(bot, ievent):
""" search link entries in cached data. """
try: feed, rest = ievent.rest.split(' ', 1)
except ValueError: ievent.missing('<feed> <words to search>') ; return
rest = rest.strip().lower()
try:
res = watcher.search(feed, 'link', rest)
if not res: res = watcher.search(feed, 'feedburner:origLink', rest)
if res: ievent.reply("link: ", res, dot=" \002||\002 ")
except KeyError: ievent.reply('no %s feed data available' % feed) ; return
cmnds.add('rss-link', handle_rsslink, ['RSS', 'USER'])
examples.add('rss-link', 'give link of item which title matches search key', 'rss-link jsonbot gozer')
## rss-description commmand
def handle_rssdescription(bot, ievent):
""" search descriptions in cached data. """
try: feed, rest = ievent.rest.split(' ', 1)
except ValueError: ievent.missing('<feed> <words to search>') ; return
rest = rest.strip().lower()
res = ""
try: ievent.reply("results: ", watcher.search(feed, 'summary', rest))
except KeyError: ievent.reply('no %s feed data available' % feed) ; return
cmnds.add('rss-description', handle_rssdescription, ['RSS', 'USER'])
examples.add('rss-description', 'give description of item which title \
matches search key', 'rss-description jsonbot gozer')
## rss-all command
def handle_rssall(bot, ievent):
""" search titles of all cached data. """
try: feed = ievent.args[0]
except IndexError: ievent.missing('<feed>') ; return
try: ievent.reply('results: ', watcher.all(feed, 'title'), dot=" \002||\002 ")
except KeyError: ievent.reply('no %s feed data available' % feed) ; return
cmnds.add('rss-all', handle_rssall, ['RSS', 'USER'])
examples.add('rss-all', "give titles of a feed", 'rss-all jsonbot')
## rss-search
def handle_rsssearch(bot, ievent):
""" search in titles of cached data. """
try: txt = ievent.args[0]
except IndexError: ievent.missing('<txt>') ; return
try: ievent.reply("results: ", watcher.searchall('title', txt))
except KeyError: ievent.reply('no %s feed data available' % feed) ; return
cmnds.add('rss-search', handle_rsssearch, ['RSS', 'USER'])
examples.add('rss-search', "search titles of all current feeds", 'rss-search goz')
def handle_rssimport(bot, ievent):
""" import feeds uses OPML. """
if not ievent.rest: ievent.missing("<url>") ; return
import xml.etree.ElementTree as etree
data = geturl2(ievent.rest)
if not data: ievent.reply("can't fetch data from %s" % ievent.rest)
try: element = etree.fromstring(data)
except Exception, ex: ievent.reply("error reading %s: %s" % (ievent.rest, str(ex))) ; return
teller = 0
errors = {}
for elem in element.getiterator():
name = elem.get("keyname") or elem.get("text")
if name: name = "+".join(name.split())
url = elem.get('url') or elem.get("xmlUrl")
try:
assert(name)
assert(url)
logging.warn("import - adding %s - %s" % (name, url))
watcher.add(fromenc(name), fromenc(url), ievent.userhost)
teller += 1
except Exception, ex:
errors[name] = str(ex)
ievent.reply("added %s items" % teller)
if errors:
errlist = []
for name, err in errors.iteritems():
errlist.append("%s - %s" % (name, err))
ievent.reply("there were errors: ", errlist)
cmnds.add('rss-import', handle_rssimport, ['OPER', ])
| Python |
# jsb/plugs/common/imdb.py
#
# author: melmoth
""" query the imdb database. """
## jsb imports
from jsb.lib.examples import examples
from jsb.lib.commands import cmnds
from jsb.utils.url import geturl2, striphtml, decode_html_entities
from jsb.imports import getjson
## basic imports
import logging
## defines
URL = "http://www.deanclatworthy.com/imdb/?q=%s"
## imdb command
def handle_imdb(bot, event):
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, 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
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
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 )
cmnds.add("imdb", handle_imdb, ["OPER", "USER", "GUEST"])
examples.add("imdb", "query the imdb database.", "imdb the matrix")
| Python |
# jsb/plugs/common/controlchar.py
#
#
"""
command to control the control (command) characters. The cc is a string
containing the allowed control characters.
"""
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## cc command
def handle_cc(bot, ievent):
""" cc [<controlchar>] .. set/get control character of channel. """
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" % chan)
return
ievent.chan.save()
ievent.reply('control char set to %s' % what)
except IndexError:
try:
cchar = ievent.chan.data.cc
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):
""" 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
ievent.chan.save()
ievent.reply('control char %s added' % what)
except IndexError: ievent.missing('<cc> [<channel>]')
cmnds.add('cc-add', handle_ccadd, 'OPER', allowqueue=False)
examples.add('cc-add', 'cc-add <control char> .. add control character', 'cc-add #')
## cc-del command
def handle_ccdel(bot, ievent):
""" remove a control char from 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
if ievent.chan.data.cc:
ievent.chan.data.cc = ievent.chan.data.cc.replace(what, '')
ievent.chan.save()
ievent.reply('control char %s deleted' % what)
except IndexError: ievent.missing('<cc> [<channel>]')
cmnds.add('cc-del', handle_ccdel, 'OPER')
examples.add('cc-del', 'cc-del <control character> .. remove cc', 'cc-del #')
| Python |
# jsb/plugs/common/colors.py
#
#
""" use the morph to add color to selected words. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.callbacks import first_callbacks
from jsb.lib.morphs import outputmorphs
from jsb.lib.persiststate import PlugState
from jsb.utils.lazydict import LazyDict
## basic imports
import re
import logging
## defines
state = PlugState()
state.define("colormapping", {})
## the morph
def docolormorph(txt, event):
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
def handle_colordel(bot, event):
if not event.rest: event.missing("<txt>") ; return
try: del state.data.colormapping[event.rest] ; state.save()
except KeyError: event.reply("we are not morphing %s" % event.rest)
event.reply("color removed for %s" % event.rest)
cmnds.add("color-del", handle_colordel, ["OPER"])
examples.add("color-del", "remove a text color replacement from the morphs", "color-del dunker")
## start
def init():
outputmorphs.add(docolormorph)
def bogus(bot, event):
pass
first_callbacks.add("START", bogus)
| Python |
# jsb/plugs/common/seen.py
#
#
# Description: tracks when a nick is last seen
# Author: Wijnand 'tehmaze' Modderman
# Website: http://tehmaze.com
# License: BSD
""" nick tracking. """
from jsb.lib.callbacks import callbacks
from jsb.lib.commands import cmnds
from jsb.lib.datadir import getdatadir
from jsb.utils.pdod import Pdod
from jsb.lib.persistconfig import PersistConfig
from jsb.lib.examples import examples
## basic imports
import os
import time
## defines
cfg = PersistConfig()
cfg.define('tz', '+0100')
## Seen-class
class Seen(Pdod):
""" maintain last seen information. """
def __init__(self):
self.datadir = getdatadir() + os.sep + 'plugs' + os.sep + 'jsb.plugs.common.seen'
Pdod.__init__(self, os.path.join(self.datadir, 'seen.data'))
def privmsgcb(self, bot, ievent):
self.data[ievent.nick.lower()] = {
'time': time.time(),
'text': ievent.origtxt,
'bot': bot.cfg.name,
'server': bot.cfg.server,
'channel': ievent.channel,
'what': 'saying',
}
def joincb(self, bot, ievent):
self.data[ievent.nick.lower()] = {
'time': time.time(),
'text': '',
'bot': bot.cfg.name,
'server': bot.cfg.server,
'channel': ievent.channel,
'what': 'joining %s' % ievent.channel,
}
def partcb(self, bot, ievent):
self.data[ievent.nick.lower()] = {
'time': time.time(),
'text': ievent.txt,
'bot': bot.cfg.name,
'server': bot.cfg.server,
'channel': ievent.channel,
'what': 'parting %s' % ievent.channel,
}
def quitcb(self, bot, ievent):
self.data[ievent.nick.lower()] = {
'time': time.time(),
'text': ievent.txt,
'bot': bot.cfg.name,
'server': bot.cfg.server,
'channel': ievent.channel,
'what': 'quitting',
}
def xmppcb(self, bot, ievent):
if ievent.type == 'unavailable':
self.data[ievent.nick.lower()] = {
'time': time.time(),
'text': ievent.userhost,
'bot': bot.cfg.name,
'server': bot.cfg.server,
'channel': ievent.channel,
'what': 'saindo da sala %s' % ievent.channel,
}
else:
self.data[ievent.nick.lower()] = {
'time': time.time(),
'text': ievent.userhost,
'bot': bot.cfg.name,
'server': bot.cfg.server,
'channel': ievent.channel,
'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)
## seen command
def handle_seen(bot, ievent):
""" lookup last seen information. """
if not ievent.args: ievent.missing('<nick>') ; return
if True:
nick = ievent.args[0].lower()
if not seen.data.has_key(nick):
alts = [x for x in seen.data.keys() if nick in x]
if alts:
alts.sort()
if len(alts) > 10:
nums = len(alts) - 10
alts = ', '.join(alts[:10]) + ' + %d others' % nums
else:
alts = ', '.join(alts)
ievent.reply('no logs for %s, however, I remember seeing: %s' % (nick, alts))
else:
ievent.reply('no logs for %s' % nick)
else:
text = seen.data[nick]['text'] and ': %s' % seen.data[nick]['text'] or ''
try:
ievent.reply('%s was last seen on %s (%s) at %s, %s%s' % (nick, seen.data[nick]['channel'], seen.data[nick]['server'],
time.strftime('%a, %d %b %Y %H:%M:%S '+ str(cfg.get('tz')), time.localtime(seen.data[nick]['time'])),
seen.data[nick]['what'], text))
except KeyError:
ievent.reply('%s was last seen at %s, %s%s' % (nick,
time.strftime('%a, %d %b %Y %H:%M:%S '+ str(cfg.get('tz')), time.localtime(seen.data[nick]['time'])),
seen.data[nick]['what'], text))
cmnds.add('seen', handle_seen, ['OPER', 'USER', 'GUEST'])
examples.add('seen', 'show last spoken txt of <nikc>', 'seen dunker')
## shutdown
def shutdown(): seen.save()
## size
def size(): return seen.size()
| Python |
# jsb/plugs/common/relay.py
#
#
""" relay to other users/channels. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.callbacks import first_callbacks
from jsb.lib.persist import PlugPersist
from jsb.lib.examples import examples
from jsb.lib.fleet import getfleet
from jsb.lib.errors import NoSuchWave
from jsb.utils.exception import handle_exception
from jsb.utils.generic import stripcolor
## basic imports
import logging
from copy import deepcopy as cpy
# plugin state .. this is where the relay plugin data lives. It's JSON string
# put into the database with memcache in between. The data is accessible
# through object.data. When data changes call object.save()
# see jsb/persist/persist.py
block = PlugPersist('block')
relay = PlugPersist('relay')
## CALLBACKS
# these are the callbacks that do the hard work of the relay plugin takes
# place. The precondition is called to see whether the callback should fire
# or not. It should return True or False.
# see jsb/callbacks.py
def relayprecondition(bot, event):
""" check to see whether the callback needs to be executed. """
logging.debug("relay - event path is %s" % event.path)
if event.isrelayed: logging.info("relay - %s already relayed" % bot.cfg.name) ; return False
origin = event.printto or event.channel
logging.debug("relay - precondition - origin is %s" % origin)
if event.txt:
if origin and origin in relay.data: return True
return False
# CORE BUSINESS
# this callback does all the relaying. It receives the event that triggered
# the callback and checks whether there are relays for the channel the event
# took place (the bot uses the users JID in the jabber and web case (web users
# must be registered)
def relaycallback(bot, event):
""" this is the callbacks that handles the responses to questions. """
# determine where the event came from
e = cpy(event)
origin = e.channel
e.isrelayed = True
try:
# loop over relays for origin
for botname, type, target in relay.data[origin]:
try:
logging.debug('trying relay of %s to (%s,%s)' % (origin, type, target))
#if target == origin: continue
# tests to prevent looping
if botname == bot.cfg.name and origin == target: continue
# check whether relay is blocked
if block.data.has_key(origin):
if [botname, type, target] in block.data[origin]: continue
# retrieve the bot from fleet (based on type)
fleet = getfleet()
outbot = fleet.byname(botname)
if not outbot: outbot = fleet.makebot(type, botname)
if outbot:
logging.info('relay - outbot found - %s - %s' % (outbot.cfg.name, outbot.type))
# we got bot .. use it to send the relayed message
if e.nick == bot.cfg.nick: txt = "[!] %s" % e.txt
else: txt = "[%s] %s" % (e.nick, e.txt)
if event: t = "[%s]" % outbot.cfg.nick
logging.debug("relay - sending to %s (%s)" % (target, outbot.cfg.name))
outbot.outnocb(target, txt, event=e)
else: logging.error("can't find bot for (%s,%s,%s)" % (botname, type, target))
except Exception, ex: handle_exception()
except KeyError: pass
# MORE CORE BUSINESS
# this is the place where the callbacks get registered. The first argument is
# the string representation of the event type, MESSAGE is for jabber message,
# EXEC is for the gadget handling, WEB for the website, BLIP_SUBMITTED for
# wave and OUTPUT for the outputcache (both used in wave and web).
first_callbacks.add('MESSAGE', relaycallback, relayprecondition)
first_callbacks.add('EXEC', relaycallback, relayprecondition)
first_callbacks.add('WEB', relaycallback, relayprecondition)
first_callbacks.add('BLIP_SUBMITTED', relaycallback, relayprecondition)
first_callbacks.add('OUTPUT', relaycallback, relayprecondition)
first_callbacks.add('PRIVMSG', relaycallback, relayprecondition)
first_callbacks.add('CONVORE', relaycallback, relayprecondition)
## COMMANDS
# this is where the commands for the relay plugin are defined, Arguments to a
# command function are the bot that the event occured on and the event that
# triggered the command. Think the code speaks for itself here ;]
## relay command
def handle_relay(bot, event):
""" [<botname>] <type> <target> .. open a relay to a user. all input from us will be relayed. """
try: (botname, type, target) = event.args
except ValueError:
try: botname = bot.cfg.name ; (type, target) = event.args
except ValueError: event.missing('[<botname>] <bottype> <target>') ; return
origin = event.channel
if not relay.data.has_key(origin): relay.data[origin] = []
try:
if not [type, target] in relay.data[origin]:
relay.data[origin].append([botname, type, target])
relay.save()
except KeyError: relay.data[origin] = [[botname, type, target], ] ; relay.save()
event.done()
cmnds.add('relay', handle_relay, ['OPER',])
examples.add('relay', 'open a relay to another user', 'relay bthate@gmail.com')
## relay-stop command
def handle_relaystop(bot, event):
""" stop a relay to a user. all relaying to target will be ignore. """
try: (botname, type, target) = event.args
except ValueError:
try: botname = bot.cfg.name ; (type, target) = event.args
except (IndexError, ValueError): botname = bot.cfg.name ; type = bot.type ; target = event.channel
origin = event.origin or event.channel
try:
logging.debug('trying to remove relay (%s,%s)' % (type, target))
relay.data[origin].remove([botname, type, target])
relay.save()
except (KeyError, ValueError): pass
event.done()
cmnds.add('relay-stop', handle_relaystop, ['OPER',' USER'])
examples.add('relay-stop', 'close a relay to another user', 'relay-stop bthate@gmail.com')
## relay-clear command
def handle_relayclear(bot, event):
""" clear all relays from a channel. all relaying to target will be ignored. """
origin = event.origin or event.channel
try:
logging.debug('clearing relay for %s' % origin)
relay.data[origin] = []
relay.save()
except (KeyError, ValueError): pass
event.done()
cmnds.add('relay-clear', handle_relayclear, ['OPER',])
examples.add('relay-clear', 'clear all relays from a channel', 'relay-clear')
## relay-list command
def handle_askrelaylist(bot, event):
""" show all relay's of a user. """
origin = event.origin or event.channel
try: event.reply('relays for %s: ' % origin, relay.data[origin])
except KeyError: event.reply('no relays for %s' % origin)
cmnds.add('relay-list', handle_askrelaylist, ['OPER', 'USER'])
examples.add('relay-list', 'show all relays of user/channel/wave.', 'relay-list')
## relay-block command
def handle_relayblock(bot, event):
""" <type> <target> .. block a user/channel/wave from relaying to us. """
try: (type, target) = event.args
except ValueError: event.missing('<type> <target>') ; return
origin = event.origin or event.channel
if not block.data.has_key(origin): block.data[origin] = []
if not [type, origin] in block.data[target]: block.data[target].append([type, origin]) ; block.save()
event.done()
cmnds.add('relay-block', handle_relayblock, ['OPER', 'USER'])
examples.add('relay-block', 'block a relay from another user', 'relay-block bthate@gmail.com')
## relay-unblock command
def handle_relayunblock(bot, event):
""" <target> .. remove a relay block of an user. """
try: target = event.args[0]
except IndexError: event.missing('<target>') ; return
origin = event.origin or event.channel
try: block.data[origin].remove([bot.cfg.name, target]) ; block.save()
except (KeyError, ValueError): pass
event.done()
cmnds.add('relay-unblock', handle_relaystop, ['OPER', 'USER'])
examples.add('relay-unblock', 'remove a block of another user', 'relay-unblock bthate@gmail.com')
## relay-blocklist command
def handle_relayblocklist(bot, event):
""" show all blocks of a user/channel.wave. """
origin = event.origin or event.channel
try: event.reply('blocks for %s: ' % origin, block.data[origin])
except KeyError: event.reply('no blocks for %s' % origin)
cmnds.add('relay-blocklist', handle_relayblocklist, ['OPER', 'USER'])
examples.add('relay-blocklist', 'show blocked relays to us', 'relay-blocklist')
| Python |
# jsb/plugs/common/tinyurl.py
#
#
""" tinyurl.com feeder """
__author__ = "Wijnand 'tehmaze' Modderman - http://tehmaze.com"
__license__ = 'BSD'
## jsb imports
from jsb.lib.commands import cmnds
from jsb.utils.url import striphtml, useragent
from jsb.lib.examples import examples
from jsb.utils.exception import handle_exception
from jsb.lib.persistconfig import PersistConfig
## google imports
try:
import waveapi
from google.appengine.api.memcache import get, set
except ImportError:
from jsb.lib.cache import get, set
## plug config
plugcfg = PersistConfig()
plugcfg.define("url", 'http://tinyurl.com/create.php')
## simpljejson
from jsb.imports import getjson
json = getjson()
## basic imports
import urllib
import urllib2
import urlparse
import re
import logging
## defines
re_url_match = re.compile(u'((?:http|https)://\S+)')
urlcache = {}
## functions
def valid_url(url):
""" check if url is valid """
if not re_url_match.search(url): return False
parts = urlparse.urlparse(url)
cleanurl = '%s://%s' % (parts[0], parts[1])
if parts[2]: cleanurl = '%s%s' % (cleanurl, parts[2])
if parts[3]: cleanurl = '%s;%s' % (cleanurl, parts[3])
if parts[4]: cleanurl = '%s?%s' % (cleanurl, parts[4])
return cleanurl
## callbacks
def precb(bot, ievent):
test_url = re_url_match.search(ievent.txt)
if test_url: return True
def privmsgcb(bot, ievent):
""" callback for urlcaching """
test_url = re_url_match.search(ievent.txt)
if test_url:
url = test_url.group(1)
if not urlcache.has_key(bot.cfg.name): urlcache[bot.cfg.name] = {}
urlcache[bot.cfg.name][ievent.target] = url
# not enabled right now
#callbacks.add('PRIVMSG', privmsgcb, precb)
def get_tinyurl(url):
""" grab a tinyurl. """
res = get(url, namespace='tinyurl') ; logging.debug('tinyurl - cache - %s' % unicode(res))
if res and res[0] == '[': return json.loads(res)
postarray = [
('submit', 'submit'),
('url', url),
]
postdata = urllib.urlencode(postarray)
req = urllib2.Request(url=plugcfg.url, data=postdata)
req.add_header('User-agent', useragent())
try: res = urllib2.urlopen(req).readlines()
except urllib2.URLError, e: logging.warn('tinyurl - %s - URLError: %s' % (url, str(e))) ; return
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
## tinyurl command
def handle_tinyurl(bot, ievent):
""" 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')
| Python |
# jsb/plugs/common/urlinfo.py
# -*- coding: utf-8 -*-
#
#
"""
Catches URLs on channel and gives information about them like title, image size, etc.
Uses http://whatisthisfile.appspot.com/ via XMLRPC
Example:
19:20 <@raspi> http://www.youtube.com/watch?v=9RZ-hYPAMFQ
19:20 <@bot> Title: "YouTube - Black Knight Holy Grail"
19:28 <@raspi> test http://www.raspi.fi foobar http://raspi.fi/wp-includes/images/rss.png
19:28 <@bot> 1. Title: "raspi.fi" Redirect: http://raspi.fi/ 2. Image: 14x14
"""
__author__ = u"Pekka 'raspi' Järvinen - http://raspi.fi/"
__license__ = 'BSD'
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.lib.callbacks import callbacks
from jsb.lib.commands import cmnds
from jsb.lib.persist import PlugPersist
from jsb.lib.examples import examples
from jsb.plugs.common.tinyurl import get_tinyurl
## basic import
import re
import urlparse
import xmlrpclib
import socket
import logging
## defines
cfg = PlugPersist('urlinfo', {})
## sanitize function
def sanitize(text):
""" Remove non-urls word by word. """
text = text.strip()
text = re.sub('\s\s+', ' ', text)
tmp = ''
for i in text.split(' '):
if len(i) >= 5:
if i.find('www.') != -1 or i.find('http') != -1: tmp += i + ' '
tmp = tmp.strip()
tmp2 = ''
for i in tmp.split(' '):
if (i[0] == '(' and i[-1] == ')') or (i[0] == '[' and i[-1] == ']') or (i[0] == '<' and i[-1] == '>') or (i[0] == '{' and i[-1] == '}'):
# First and last character is one of ()[]{}<>
tmp2 += i[1:-1:1] + ' '
else: tmp2 += i + ' '
tmp2 = tmp2.strip();
tmp = ''
for i in tmp2.split(' '):
if i.find('www.') == 0: tmp += 'http://' + i + ' '
else: tmp += i + ' '
tmp = tmp.strip();
out = tmp;
return out;
## getUrls function
def getUrls(text):
""" get valid urls. """
regex = r"http[s]?://[-A-Za-z0-9+&@#/%=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]"
p = re.compile(regex)
urls = []
for i in text.split(' '):
for x in p.findall(i):
url = urlparse.urlparse(x)
if url.geturl() not in urls: urls.append(url.geturl())
return urls
## getUrlInfo function
def getUrlInfo(text):
""" get info of urls in given txt. """
out = ''
text = sanitize(text)
urls = getUrls(text)
if urls:
idx = 1
for i in urls:
o = ''
try:
server = xmlrpclib.ServerProxy("http://whatisthisfile.appspot.com/xmlrpc")
logging.info('urlinfo - XMLRPC query: %s' % i)
urlinfo = server.app.query(i)
if urlinfo.has_key('html'):
if urlinfo['html'].has_key('title'): o += 'Title: "%s" ' % urlinfo['html']['title'].strip()
elif urlinfo.has_key('image'): o += 'Image: %dx%d ' % (urlinfo['image']['width'], urlinfo['image']['height'])
if not o: continue
if len(o):
if len(urls) > 1: out += ' ' + str(idx) + '. ' ; idx += 1
out += o
if "tinyurl" in i: out = out.strip() ; out += " - %s" % i
elif not "http://" in out: out = out.strip() ; out += " - %s" % get_tinyurl(i)[0]
except Exception: pass
return out.strip()
## callbacks
# Catch channel chat for possible URLs
def catchHasUrls(bot, ievent):
if ievent.how == "background": return 0
if cfg.data.has_key(ievent.channel) and cfg.data[ievent.channel]:
if len(ievent.txt) >= 5:
if (ievent.txt.find('www.') != -1) or (ievent.txt.find('http') != -1): return 1
return 0
# Catch channel chat
def catchUrls(bot, ievent):
bot.say(ievent.channel, getUrlInfo(ievent.txt))
callbacks.add('PRIVMSG', catchUrls, catchHasUrls, threaded=True)
callbacks.add('CONSOLE', catchUrls, catchHasUrls, threaded=True)
callbacks.add('MESSAGE', catchUrls, catchHasUrls, threaded=True)
callbacks.add('DISPATCH', catchUrls, catchHasUrls, threaded=True)
callbacks.add('CMND', catchUrls, catchHasUrls, threaded=True)
## urlinfo-enable command
def handle_urlinfo_enable(bot, ievent):
""" 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):
""" 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')
## urlinfo-list command
def handle_urlinfo_list(bot, ievent):
""" list what channels are using urlinfo. """
chans = []
names = cfg.data.keys()
names.sort()
for name in names:
targets = cfg.data.keys()
targets.sort()
chans.append('%s: %s' % (name, ' '.join(targets)))
if not chans: ievent.reply('none')
else: ievent.reply('urlinfo enabled on channels: %s' % ', '.join(chans))
cmnds.add('urlinfo-list', handle_urlinfo_list, 'OPER')
examples.add('urlinfo-list', 'show in which channels urlinfo is enabled', 'urlinfo-list')
| Python |
# jsb/plugs/common/learn.py
#
#
""" learn information items .. facts .. factoids. """
## jsb imports
from jsb.lib.callbacks import callbacks
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.lazydict import LazyDict
from jsb.lib.persist import PlugPersist
## basic imports
import logging
## learn command
def handle_learn(bot, event):
"""" 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()
items = PlugPersist(event.channel)
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 %s database" % (what, event.channel))
cmnds.add('learn', handle_learn, ['OPER', 'USER', 'GUEST'])
examples.add('learn', 'learn the bot a description of an item.', "learn dunk is botpapa")
## forget command
def handle_forget(bot, event):
"""" set an information item. """
if not event.rest: event.missing("<item> and <match>") ; return
try: (what, match) = event.rest.split(" and ", 2)
except ValueError: event.missing("<item> and <match>") ; return
what = what.lower()
items = PlugPersist(event.channel)
if not items.data: items.data = LazyDict()
if items.data.has_key(what):
for i in range(len(items.data[what])):
if match in items.data[what][i]:
del items.data[what][i]
items.save()
break
event.reply("item removed from %s database" % event.channel)
cmnds.add('forget', handle_forget, ['OPER', 'USER'])
examples.add('forget', 'forget a description of an item.', "forget dunk and botpapa")
## whatis command
def handle_whatis(bot, event):
""" show what the bot has learned about a factoid. """
items = PlugPersist(event.channel)
what = event.rest.lower().split('!')[0].strip()
if what in items.data and items.data[what]: event.reply("%s is " % event.rest, items.data[what], dot=", ")
else: event.reply("no information known about %s" % what)
cmnds.add('whatis', handle_whatis, ['OPER', 'USER', 'GUEST'])
examples.add("whatis", "whatis learned about a subject", "whatis jsb")
## items command
def handle_items(bot, event):
""" show what items the bot has learned. """
items = PlugPersist(event.channel).data.keys()
event.reply("i know %s items: " % len(items), items)
cmnds.add('items', handle_items, ['OPER', 'USER', 'GUEST'])
examples.add("items", "show what items the bot knows", "items")
## callbacks
def prelearn(bot, event):
if len(event.txt) < 2: return
if event.txt and (event.txt[0] == "?" or event.txt[-1] == "?") and not event.forwarded: return True
return False
def learncb(bot, event):
if bot.type == "convore" and not event.chan.data.enable: return
event.bind(bot)
items = PlugPersist(event.channel)
target = event.txt.lower().split('!')[0]
if target[0] == "?": target = target[1:]
if target[-1] == "?": target = target[:-1]
if target in items.data: event.reply("%s is " % target, items.data[target], dot=", ")
event.ready()
callbacks.add("PRIVMSG", learncb, prelearn)
callbacks.add("MESSAGE", learncb, prelearn)
callbacks.add("DISPATCH", learncb, prelearn)
callbacks.add("CONSOLE", learncb, prelearn)
callbacks.add("CMND", learncb, prelearn)
callbacks.add("CONVORE", learncb, prelearn)
| Python |
# jsb/plugs/common/googletranslate.py
#
#
# author: melmoth
""" use google translate. """
## jsb imports
from jsb.lib.examples import examples
from jsb.lib.commands import cmnds
from jsb.utils.url import geturl2
from jsb.imports import getjson
## basic imports
import re
from urllib import quote
## defines
URL = r"http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%(text)s&langpair=%(from)s|%(to)s"
def parse_pair(text):
trans = re.match("^(?P<from>[a-z]{2}) +(?P<to>[a-z]{2}) +(?P<txt>.*)$", text)
if not trans: return {}
return {'from': trans.group('from'),
'to': trans.group('to'),
'text': quote(trans.group('txt'))}
## translate command
def handle_translate(bot, event):
""" translate <from> <to> <text>. """
if not event.rest: event.missing("<from> <to> <text>") ; return
query = parse_pair(event.rest.strip())
if not query: event.missing("<from> <to> <text>") ; return
rawresult = {}
try: rawresult = getjson().loads(geturl2(URL % query))
except: event.reply("query to google failed") ; return
# rawresult = {"responseData": {"translatedText":"test"}, "responseDetails": None, "responseStatus": 201}
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"])
examples.add("translate", "use google translate to translate txt.", "translate nl en top bot")
| Python |
# jsb/plugs/common/shop.py
#
#
""" maitain a shopping list (per user). """
## jsb imports
from jsb.utils.generic import getwho, jsonstring
from jsb.lib.users import users
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.pdol import Pdol
## basic imports
import os
## functions
def size():
""" return number of shops entries """
return len(shops.data)
def sayshop(bot, ievent, shoplist):
""" output shoplist """
if not shoplist: ievent.reply('nothing to shop ;]') ; return
result = []
teller = 0
for i in shoplist: result.append('%s) %s' % (teller, i)) ; teller += 1
ievent.reply("shoplist: ", result, dot=" ")
## shop command
def handle_shop(bot, ievent):
""" shop [<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', 'shop [<item>] .. show shop items or add a shop item', '1) shop 2) shop bread')
## got command
def handle_got(bot, ievent):
""" got <listofnrs> .. 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()
teller = 0
for i in range(len(shop)-1, -1 , -1):
if i in nrs:
try: del shop[i] ; teller += 1
except IndexError: pass
ievent.user.state.save()
ievent.reply('%s shop item(s) deleted' % teller)
cmnds.add('got', handle_got, ['USER', 'GUEST'])
examples.add('got', 'got <listofnrs> .. remove item <listofnrs> from shop list','1) got 3 2) got 1 6 8')
| Python |
# jsb/plugs/common/url.py
#
#
""" maintain log of urls. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.lib.callbacks import callbacks
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persiststate import PlugState
## basic imports
import re
import os
## defines
re_url_match = re.compile(u'((?:http|https)://\S+)')
state = None
initdone = False
## init function
def init():
global state
global initdone
state = PlugState()
state.define('urls', {})
initdone = True
return 1
## size function
def size():
""" show number of urls. """
s = 0
if not initdone: return s
for i in state['urls'].values():
for j in i.values(): s += len(j)
return s
## search function
def search(what, queue):
""" search the url database. """
global initdone
result = []
if not initdone: return result
try:
for i in state['urls'].values():
for urls in i.values():
for url in urls:
if what in url: result.append(url)
except KeyError: pass
for url in result: queue.put_nowait(url)
## url callbacks
def urlpre(bot, ievent):
return re_url_match.findall(ievent.txt)
def urlcb(bot, ievent):
if not state: return
try:
test_urls = re_url_match.findall(ievent.txt)
for i in test_urls:
if not state['urls'].has_key(bot.cfg.name):
state['urls'][bot.cfg.name] = {}
if not state['urls'][bot.cfg.name].has_key(ievent.channel):
state['urls'][bot.cfg.name][ievent.channel] = []
if not i in state['urls'][bot.cfg.name][ievent.channel]:
state['urls'][bot.cfg.name][ievent.channel].append(i)
state.save()
except Exception, ex: handle_exception()
callbacks.add('PRIVMSG', urlcb, urlpre, threaded=True)
## url-search commands
def handle_urlsearch(bot, ievent):
""" search the per channel url database for a search term. """
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'][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):
""" search all urls. """
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:
if ievent.rest in url: result.append(url)
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-searchall', handle_urlsearchall, ['OPER', 'USER', 'GUEST'])
examples.add('url-searchall', 'search matching url entries', 'url-searchall jsonbot')
## url-size command
def handle_urlsize(bot, ievent):
""" show number of urls stored. """
ievent.reply(str(size()))
cmnds.add('url-size', handle_urlsize, 'OPER')
examples.add('url-size', 'show number of urls in cache', 'url-size')
| Python |
# jsb/plugs/common/ipcalc.py
#
# IP subnet calculator
# (c) 2007 Wijnand 'tehmaze' Modderman - http://tehmaze.com
# BSD License
""" IP subnet calculator. this module allows you to perform network calculations. """
"""
# IP subnet calculator
# (C) 2007 Wijnand 'tehmaze' Modderman - http://tehmaze.com
# BSD License
#
# ABOUT
# This module allows you to perform network calculations.
#
# CHANGELOG
# 2007-10-26: Added IPv6 support, as well as a lot of other functions,
# refactored the calculations.
# 2007-10-25: Initial writeup, because I could not find any other workable
# implementation.
#
# TODO
# * add CLI parser
#
# REFERENCES
# * http://www.estoile.com/links/ipv6.pdf
# * http://www.iana.org/assignments/ipv4-address-space
# * http://www.iana.org/assignments/multicast-addresses
# * http://www.iana.org/assignments/ipv6-address-space
# * http://www.iana.org/assignments/ipv6-tla-assignments
# * http://www.iana.org/assignments/ipv6-multicast-addresses
# * http://www.iana.org/assignments/ipv6-anycast-addresses
#
# THANKS (testing, tips)
# * Bastiaan (trbs)
# * Peter van Dijk (Habbie)
# * Hans van Kranenburg (Knorrie)
#
"""
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
__version__ = '0.2a'
## basic imports
import types
import socket
## IP class
class IP(object):
# Hex-to-Bin conversion masks
_bitmask = {
'0': '0000', '1': '0001', '2': '0010', '3': '0011',
'4': '0100', '5': '0101', '6': '0110', '7': '0111',
'8': '1000', '9': '1001', 'a': '1010', 'b': '1011',
'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111'
}
# IP range specific information, see IANA allocations.
_range = {
4: {
'01' : 'CLASS A',
'10' : 'CLASS B',
'110' : 'CLASS C',
'1110' : 'CLASS D MULTICAST',
'11100000' : 'CLASS D LINKLOCAL',
'1111' : 'CLASS E',
'00001010' : 'PRIVATE RFC1918', # 10/8
'101011000001' : 'PRIVATE RFC1918', # 172.16/12
'1100000010101000' : 'PRIVATE RFC1918', # 192.168/16
},
6: {
'00000000' : 'RESERVED', # ::/8
'00000001' : 'UNASSIGNED', # 100::/8
'0000001' : 'NSAP', # 200::/7
'0000010' : 'IPX', # 400::/7
'0000011' : 'UNASSIGNED', # 600::/7
'00001' : 'UNASSIGNED', # 800::/5
'0001' : 'UNASSIGNED', # 1000::/4
'0010000000000000' : 'RESERVED', # 2000::/16 Reserved
'0010000000000001' : 'ASSIGNABLE', # 2001::/16 Sub-TLA Assignments [RFC2450]
'00100000000000010000000': 'ASSIGNABLE IANA', # 2001:0000::/29 - 2001:01F8::/29 IANA
'00100000000000010000001': 'ASSIGNABLE APNIC', # 2001:0200::/29 - 2001:03F8::/29 APNIC
'00100000000000010000010': 'ASSIGNABLE ARIN', # 2001:0400::/29 - 2001:05F8::/29 ARIN
'00100000000000010000011': 'ASSIGNABLE RIPE', # 2001:0600::/29 - 2001:07F8::/29 RIPE NCC
'0010000000000010' : '6TO4', # 2002::/16 "6to4" [RFC3056]
'0011111111111110' : '6BONE TEST', # 3ffe::/16 6bone Testing [RFC2471]
'0011111111111111' : 'RESERVED', # 3fff::/16 Reserved
'010' : 'GLOBAL-UNICAST', # 4000::/3
'011' : 'UNASSIGNED', # 6000::/3
'100' : 'GEO-UNICAST', # 8000::/3
'101' : 'UNASSIGNED', # a000::/3
'110' : 'UNASSIGNED', # c000::/3
'1110' : 'UNASSIGNED', # e000::/4
'11110' : 'UNASSIGNED', # f000::/5
'111110' : 'UNASSIGNED', # f800::/6
'1111110' : 'UNASSIGNED', # fc00::/7
'111111100' : 'UNASSIGNED', # fe00::/9
'1111111010' : 'LINKLOCAL', # fe80::/10
'1111111011' : 'SITELOCAL', # fec0::/10
'11111111' : 'MULTICAST', # ff00::/8
'0' * 96 : 'IPV4COMP', # ::/96
'0' * 80 + '1' * 16 : 'IPV4MAP', # ::ffff:0:0/96
'0' * 128 : 'UNSPECIFIED', # ::/128
'0' * 127 + '1' : 'LOOPBACK' # ::1/128
}
}
def __init__(self, ip, mask=None, version=0):
self.mask = mask
self.v = 0
# Parse input
if isinstance(ip, IP):
self.ip = ip.ip
self.dq = ip.dq
self.v = ip.v
self.mask = ip.mask
elif type(ip) in [types.IntType, types.LongType]:
self.ip = long(ip)
if self.ip <= 0xffffffff:
self.v = version or 4
self.dq = self._itodq(ip)
else:
self.v = version or 4
self.dq = self._itodq(ip)
else:
# If string is in CIDR notation
if '/' in ip:
ip, mask = ip.split('/', 1)
self.mask = int(mask)
self.v = version or 0
self.dq = ip
self.ip = self._dqtoi(ip)
assert self.v != 0, 'Could not parse input'
# Netmask defaults to one ip
if self.mask is None:
self.mask = self.v == 4 and 32 or 128
# Validate subnet size
if self.v == 6:
self.dq = self._itodq(self.ip)
if self.mask < 0 or self.mask > 128:
raise ValueError, "IPv6 subnet size must be between 0 and 128"
elif self.v == 4:
if self.mask < 0 or self.mask > 32:
raise ValueError, "IPv4 subnet size must be between 0 and 32"
def bin(self):
'''
Full-length binary representation of the IP address.
'''
h = hex(self.ip).lower().rstrip('l')
b = ''.join(self._bitmask[x] for x in h[2:])
l = self.v == 4 and 32 or 128
return ''.join('0' for x in xrange(len(b), l)) + b
def hex(self):
'''
Full-length hexadecimal representation of the IP address.
'''
if self.v == 4:
return '%08x' % self.ip
else:
return '%032x' % self.ip
def subnet(self):
return self.mask
def version(self):
return self.v
def info(self):
'''
Show IANA allocation information for the current IP address.
'''
b = self.bin()
l = self.v == 4 and 32 or 128
for i in range(len(b), 0, -1):
if self._range[self.v].has_key(b[:i]):
return self._range[self.v][b[:i]]
return 'UNKNOWN'
def _dqtoi(self, dq):
'''
Convert dotquad or hextet to long.
'''
# hex notation
if dq.startswith('0x'):
ip = long(dq[2:], 16)
if ip > 0xffffffffffffffffffffffffffffffffL:
raise ValueError, "%r: IP address is bigger than 2^128" % dq
if ip <= 0xffffffff:
self.v = 4
else:
self.v = 6
return ip
# IPv6
if ':' in dq:
hx = dq.split(':') # split hextets
if ':::' in dq:
raise ValueError, "%r: IPv6 address can't contain :::" % dq
# Mixed address (or 4-in-6), ::ffff:192.0.2.42
if '.' in dq:
return self._dqtoi(hx[-1])
if len(hx) > 8:
raise ValueError, "%r: IPv6 address with more than 8 hexletts" % dq
elif len(hx) < 8:
# No :: in address
if not '' in hx:
raise ValueError, "%r: IPv6 address invalid: compressed format malformed" % dq
elif not (dq.startswith('::') or dq.endswith('::')) and len([x for x in hx if x == '']) > 1:
raise ValueError, "%r: IPv6 address invalid: compressed format malformed" % dq
ix = hx.index('')
px = len(hx[ix+1:])
for x in xrange(ix+px+1, 8):
hx.insert(ix, '0')
elif dq.endswith('::'):
pass
elif '' in hx:
raise ValueError, "%r: IPv6 address invalid: compressed format detected in full notation" % dq
ip = ''
hx = [x == '' and '0' or x for x in hx]
for h in hx:
if len(h) < 4:
h = '%04x' % int(h, 16)
if 0 > int(h, 16) > 0xffff:
raise ValueError, "%r: IPv6 address invalid: hextets should be between 0x0000 and 0xffff" % dq
ip += h
self.v = 6
return long(ip, 16)
elif len(dq) == 32:
# Assume full heximal notation
self.v = 6
return long(h, 16)
# IPv4
if '.' in dq:
q = dq.split('.')
if len(q) > 4:
raise ValueError, "%r: IPv4 address invalid: more than 4 bytes" % dq
for x in q:
if 0 > int(x) > 255:
raise ValueError, "%r: IPv4 address invalid: bytes should be between 0 and 255" % dq
self.v = 4
return long(q[0])<<24 | long(q[1])<<16 | long(q[2])<<8 | long(q[3])
raise ValueError, "Invalid address input"
def _itodq(self, n):
'''
Convert long to dotquad or hextet.
'''
if self.v == 4:
return '.'.join(map(str, [(n>>24) & 0xff, (n>>16) & 0xff, (n>>8) & 0xff, n & 0xff]))
else:
n = '%032x' % n
return ':'.join(n[4*x:4*x+4] for x in xrange(0, 8))
def __str__(self):
return self.dq
def __int__(self):
return int(self.ip)
def __long__(self):
return self.ip
def size(self):
return 1
def clone(self):
'''
Return a new <IP> object with a copy of this one.
'''
return IP(self)
def to_ipv4(self):
'''
Convert (a IPv6) IP address to an IPv4 address, if possible. Only works
for IPv4-compat (::/96) and 6-to-4 (2002::/16) addresses.
'''
if self.v == 4:
return self
else:
if self.bin().startswith('0' * 96):
return IP(long(self), version=4)
elif long(self) & 0x20020000000000000000000000000000L:
return IP((long(self)-0x20020000000000000000000000000000L)>>80, version=4)
else:
return ValueError, "%r: IPv6 address is not IPv4 compatible, nor a 6-to-4 IP" % self.dq
def to_ipv6(self, type='6-to-4'):
'''
Convert (a IPv4) IP address to an IPv6 address.
'''
assert type in ['6-to-4', 'compat'], 'Conversion type not supported'
if self.v == 4:
if type == '6-to-4':
return IP(0x20020000000000000000000000000000L | long(self)<<80, version=6)
elif type == 'compat':
return IP(long(self), version=6)
else:
return self
def to_tuple(self):
'''
Used for comparisons.
'''
return (self.dq, self.mask)
## Network class
class Network(IP):
'''
Network slice calculations.
'''
def netmask(self):
'''
Network netmask derived from subnet size.
'''
if self.version() == 4:
return IP((0xffffffffL >> (32-self.mask)) << (32-self.mask), version=self.version())
else:
return IP((0xffffffffffffffffffffffffffffffffL >> (128-self.mask)) << (128-self.mask), version=self.version())
def network(self):
'''
Network address.
'''
return IP(self.ip & long(self.netmask()), version=self.version())
def broadcast(self):
'''
Broadcast address.
'''
# XXX: IPv6 doesn't have a broadcast address, but it's used for other
# calculations such as <Network.host_last>.
if self.version() == 4:
return IP(long(self.network()) | (0xffffffff - long(self.netmask())), version=self.version())
else:
return IP(long(self.network()) | (0xffffffffffffffffffffffffffffffffL - long(self.netmask())), version=self.version())
def host_first(self):
'''
First available host in this subnet.
'''
if (self.version() == 4 and self.mask == 32) or (self.version() == 6 and self.mask == 128):
return self
return IP(long(self.network())+1, version=self.version())
def host_last(self):
'''
Last available host in this subnet.
'''
if (self.version() == 4 and self.mask == 32) or (self.version() == 6 and self.mask == 128):
return self
return IP(long(self.broadcast())-1, version=self.version())
def in_network(self, other):
'''
Check if the given IP address is within this network.
'''
other = Network(other)
return long(other) >= long(self) and long(other) < long(self) + self.size() - other.size() + 1
def __contains__(self, ip):
'''
Check if the given ip is part of the network.
>>> '192.0.2.42' in Network('192.0.2.0/24')
True
>>> '192.168.2.42' in Network('192.0.2.0/24')
False
'''
return self.in_network(ip)
def __lt__(self, other):
return self.size() < IP(other).size()
def __le__(self, other):
return self.size() <= IP(other).size()
def __gt__(self, other):
return self.size() > IP(other).size()
def __ge__(self, other):
return self.size() >= IP(other).size()
def __iter__(self):
'''
Generate a range of ip addresses within the network.
>>> for ip in Network('192.168.114.0/30'): print str(ip)
...
192.168.114.0
192.168.114.1
192.168.114.2
192.168.114.3
'''
for ip in [IP(long(self)+x) for x in xrange(0, self.size())]:
yield ip
def has_key(self, ip):
'''
Check if the given ip is part of the network.
>>> net = Network('192.0.2.0/24')
>>> 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):
""" <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')
| Python |
# jsb/plugs/common/gcalc.py
# encoding: utf-8
#
#
""" use google to calculate e.g. !gcalc 1 + 1 """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.url import useragent
## basic imports
import urllib2
## gcalc command
def handle_gcalc(bot, ievent):
""" use google calc . """
if len(ievent.args) > 0: expr = " ".join(ievent.args).replace("+", "%2B").replace(" ", "+")
else: ievent.missing('Missing an expression') ; return
req = urllib2.Request("http://www.google.com/ig/calculator?hl=en&q=%s" % expr, None, {'User-agent': useragent()})
data = urllib2.urlopen(req).read()
try:
rhs = data.split("rhs")[1].split("\"")[1]
lhs = data.split("lhs")[1].split("\"")[1]
if rhs and lhs:
ievent.reply("%s = %s" % (lhs,rhs.replace('\\x26#215;', '*').replace('\\x3csup\\x3e', '**').replace('\\x3c/sup\\x3e', '')))
else: ievent.reply("hmmm can't get a result ..")
except Exception, ex:
ievent.reply(str(ex))
cmnds.add('gcalc', handle_gcalc, ['OPER', 'USER', 'GUEST'])
examples.add('gcalc', 'calculate an expression using the google calculator', 'gcalc 1 + 1')
| Python |
# jsb/plugs/common/idle.py
#
#
""" show how long someone has been idle. """
## jsb imports
from jsb.utils.timeutils import elapsedstring
from jsb.utils.generic import getwho
from jsb.lib.commands import cmnds
from jsb.lib.callbacks import callbacks
from jsb.lib.examples import examples
from jsb.lib.persist import PlugPersist
## basic imports
import time
import os
import logging
## defines
idle = PlugPersist('idle.data')
if not idle.data:
idle.data = {}
## callbacks
def preidle(bot, event):
""" idle precondition aka check if it is not a command """
if event.iscmnd() or (bot.isgae and event.userhost not in bot.cfg.followlist):
return False
else:
return True
def idlecb(bot, event):
""" idle PRIVMSG callback .. set time for channel and nick """
ttime = time.time()
idle.data[event.userhost] = ttime
idle.data[event.channel] = ttime
idle.save()
callbacks.add('PRIVMSG', idlecb, preidle)
callbacks.add('MESSAGE', idlecb, preidle)
callbacks.add('WEB', idlecb, preidle)
callbacks.add('CONSOLE', idlecb, preidle)
callbacks.add('DISPATCH', idlecb, preidle)
## idle command
def handle_idle(bot, ievent):
""" idle [<nick>] .. show how idle an channel/user has been """
try:
who = ievent.args[0]
except IndexError:
handle_idle2(bot, ievent)
return
userhost = getwho(bot, who)
if not userhost:
ievent.reply("can't get userhost of %s" % who)
return
logging.warn("idle - userhost is %s" % userhost)
try:
elapsed = elapsedstring(time.time() - idle.data[userhost])
except KeyError:
ievent.reply("i haven't seen %s" % who)
return
if elapsed:
ievent.reply("%s is idle for %s" % (who, elapsed))
return
else:
ievent.reply("%s is not idle" % who)
return
def handle_idle2(bot, ievent):
""" show how idle a channel has been """
chan = ievent.channel
try:
elapsed = elapsedstring(time.time()-idle.data[chan])
except KeyError:
ievent.reply("nobody said anything on channel %s yet" % chan)
return
if elapsed:
ievent.reply("channel %s is idle for %s" % (chan, elapsed))
else:
ievent.reply("channel %s is not idle" % chan)
cmnds.add('idle', handle_idle, ['OPER', 'USER', 'GUEST'])
examples.add('idle', 'idle [<nick>] .. show how idle the channel is or show how idle <nick> is', '1) idle 2) idle test')
| Python |
# jsb/plugs/common/remind.py
#
#
""" remind people .. say txt when somebody gets active """
## jsb imports
from jsb.utils.generic import getwho
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.callbacks import callbacks
from jsb.lib.persist import PlugPersist
## basic imports
import time
import os
## Remind-class
class Remind(PlugPersist):
""" remind object """
def __init__(self, name):
PlugPersist.__init__(self, name)
def add(self, who, data):
""" add a remind txt """
if not self.data.has_key(who):
self.data[who] = []
self.data[who].append(data)
self.save()
def wouldremind(self, userhost):
""" check if there is a remind for userhost """
try:
reminds = self.data[userhost]
if reminds == None or reminds == []:
return False
except KeyError:
return False
return True
def remind(self, bot, userhost):
""" send a user all registered reminds """
reminds = self.data[userhost]
if not reminds:
return
for i in reminds:
ttime = None
try:
(tonick, fromnick, txt, ttime) = i
except ValueError:
(tonick, fromnick, txt) = i
txtformat = '[%s] %s wants to remind you of: %s'
if ttime:
timestr = time.ctime(ttime)
else:
timestr = None
bot.saynocb(tonick, txtformat % (timestr, fromnick, txt))
bot.saynocb(fromnick, '[%s] reminded %s of: %s' % (timestr, tonick, txt))
try: del self.data[userhost]
except KeyError: pass
self.save()
## defines
remind = Remind('remind.data')
assert remind
## callbacks
def preremind(bot, ievent):
""" remind precondition """
return remind.wouldremind(ievent.userhost)
def remindcb(bot, ievent):
""" remind callbacks """
remind.remind(bot, ievent.userhost)
callbacks.add('PRIVMSG', remindcb, preremind, threaded=True)
callbacks.add('JOIN', remindcb, preremind, threaded=True)
callbacks.add('MESSAGE', remindcb, preremind, threaded=True)
callbacks.add('WEB', remindcb, preremind, threaded=True)
## remind command
def handle_remind(bot, ievent):
""" remind <nick> <txt> .. add a remind. """
try: who = ievent.args[0] ; txt = ' '.join(ievent.args[1:])
except IndexError: ievent.missing('<nick> <txt>') ; return
if not txt: ievent.missing('<nick> <txt>') ; return
userhost = getwho(bot, who)
if not userhost: ievent.reply("can't find userhost for %s" % who) ; return
else:
remind.add(userhost, [who, ievent.nick, txt, time.time()])
ievent.reply("remind for %s added" % who)
cmnds.add('remind', handle_remind, ['OPER', 'USER', 'GUEST'], allowqueue=False)
examples.add('remind', 'remind <nick> <txt>', 'remind dunker check the bot !')
| Python |
# jsb/plugs/common/koffie.py
#
# Made by WildRover and Junke1990
""" schenk wat koffie! """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
import os
import string
import random
## defines
koffie = []
thee = []
bier = []
wijn = []
fris = []
taart = []
koek = []
chips = []
soep = []
sex = []
roken = []
beledig = []
## init function
def init():
global koffie
global thee
global bier
global wijn
global fris
global taart
global koek
global chips
global soep
global sex
global roken
global beledig
for i in koffietxt.split('\n'):
if i:
koffie.append(i.strip())
for i in theetxt.split('\n'):
if i:
thee.append(i.strip())
for i in biertxt.split('\n'):
if i:
bier.append(i.strip())
for i in wijntxt.split('\n'):
if i:
wijn.append(i.strip())
for i in fristxt.split('\n'):
if i:
fris.append(i.strip())
for i in taarttxt.split('\n'):
if i:
taart.append(i.strip())
for i in koektxt.split('\n'):
if i:
koek.append(i.strip())
for i in chipstxt.split('\n'):
if i:
chips.append(i.strip())
for i in soeptxt.split('\n'):
if i:
soep.append(i.strip())
for i in sextxt.split('\n'):
if i:
sex.append(i.strip())
for i in rokentxt.split('\n'):
if i:
roken.append(i.strip())
for i in beledigtxt.split('\n'):
if i:
beledig.append(i.strip())
return 1
## functions
def do(bot, ievent, txt):
if not bot.isgae 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):
""" get 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):
""" get 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')
## bier command
def handle_bier(bot, ievent):
""" get a beer """
rand = random.randint(0,len(bier)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, bier[rand] + " " + nick)
cmnds.add('bier', handle_bier, 'USER')
examples.add('bier', 'get a bier', 'bier')
## wijn command
def handle_wijn(bot, ievent):
""" get a wine """
rand = random.randint(0,len(wijn)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, wijn[rand] + " " + nick)
cmnds.add('wijn', handle_wijn, 'USER')
examples.add('wijn', 'get a wijn', 'wijn')
## fris command
def handle_fris(bot, ievent):
""" get a fris """
rand = random.randint(0,len(fris)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, fris[rand] + " " + nick)
cmnds.add('fris', handle_fris, 'USER')
examples.add('fris', 'get a fris', 'fris')
## taart command
def handle_taart(bot, ievent):
""" get a taart """
rand = random.randint(0,len(taart)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, taart[rand] + " " + nick)
cmnds.add('taart', handle_taart, 'USER')
examples.add('taart', 'get a taart', 'taart')
## koek command
def handle_koek(bot, ievent):
""" get a koek """
rand = random.randint(0,len(koek)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, koek[rand] + " " + nick)
cmnds.add('koek', handle_koek, 'USER')
examples.add('koek', 'get a koek', 'koek')
cmnds.add('koekje', handle_koek, 'USER')
examples.add('koekje', 'get a koekje', 'koekje')
## chips command
def handle_chips(bot, ievent):
""" get a chips """
rand = random.randint(0,len(chips)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, chips[rand] + " " + nick)
cmnds.add('chips', handle_chips, 'USER')
examples.add('chips', 'get a chips', 'chips')
## soep command
def handle_soep(bot, ievent):
""" get a soep """
rand = random.randint(0,len(soep)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, soep[rand] + " " + nick)
cmnds.add('soep', handle_soep, 'USER')
examples.add('soep', 'get a soep', 'soep')
## sex command
def handle_sex(bot, ievent):
""" get a sex """
rand = random.randint(0,len(sex)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, sex[rand] + " " + nick)
cmnds.add('sex', handle_sex, 'USER')
examples.add('sex', 'get a sex', 'sex')
## roken command
def handle_roken(bot, ievent):
""" get a roken """
rand = random.randint(0,len(roken)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, roken[rand] + " " + nick)
cmnds.add('roken', handle_roken, 'USER')
examples.add('roken', 'get a roken', 'roken')
## beledig command
def handle_beledig(bot, ievent):
""" get/give an belediging """
rand = random.randint(0,len(beledig)-1)
try:
input = ievent.args[0]
nick = '%s' % input
except:
if len('%s') >= 0: nick = ievent.nick
do(bot, ievent, beledig[rand] + " " + nick)
cmnds.add('beledig', handle_beledig, 'USER')
examples.add('beledig', 'get/give an belediging ', 'beledig')
## text definitions
koffietxt = """ schenkt een kopje koffie in voor
schenkt een kopje koffie wiener melange in voor
schenkt een kopje espresso voor je in voor
schenkt een kopje arabica voor je in voor
schenkt je een kopje koffie verkeerd in voor
schenkt een kopje cappuccino voor je in voor
schenkt een kopje cafe choco voor je in voor
schenkt je een kopje koffie van gisteren in voor
vult een kopje met decafe voor
schenkt een kopje toebroek in voor
maak het gerust zelf,
geeft een glas irish-coffee aan
geeft een glas french-coffee aan
schenkt een kopje turkse koffie in voor
schenkt een kopje americano in voor
schenkt een kopje doppio in voor
schenkt een kopje espresso ristretto in voor
schenkt een kopje caffe latte in voor
schenkt een kopje espresso macchiato in voor
schenkt een kopje latte macchiato in voor
schenkt een kopje espresso romano in voor
schenkt een kopje con panna voor in voor
schenkt een kopje mocha in voor
"""
theetxt = """ maak het gerust zelf,
schenkt een kopje groene thee in voor
ja lekker heh,
schenkt een kopje mintthee in voor
schenkt een kopje brandnetelthee in voor
schenkt een kopje bosvruchtenthee in voor
schenkt een kopje citroenthee in voor
schenkt een kopje rooibosthee in voor
schenkt een heerlijk kopje lavendelthee in voor
maakt een kopje fruity forest voor
maakt een kopje tempting red voor
maakt een kopje early grey voor
"""
biertxt = """ reikt een flesje hertog-jan aan voor
tapt een glas witbier voor
geeft een flesje amstel aan
geeft een flesje jupiler aan
geeft een flesje bavaria aan
geeft een flesje grolsch aan
pak het gerust zelf,
geeft een flesje hoegaarden aan
geeft een flesje grimbergen aan
reikt een flesje dommelsch aan voor
reikt een flesje brand aan voor
schenkt een glas duvel in voor
schenkt een glas chouffe in voor
"""
wijntxt = """ trekt een fles rode wijn open.
geeft een glas rode wijn aan
geeft een glas witte wijn aan
geeft een glas rose aan
geeft een glas champagne aan
trekt een fles appelwijn open, tast toe,
geeft een glas cider aan
geeft een glas champagne aan
pak het gerust zelf maar,
morst rode wijn over je witte shirt, oops... sorry,
ja lekker,
witte, rode of rose,
geeft een glas droge witte wijn aan
geeft een glas zoete witte wijn aan
trekt de kurk van een fles witte wijn, zuipt hem helemaal leeg *hips* en proost,
schenkt een glas goedkope tafelwijn in voor
een glas chateaux-migraine voor
trekt een fles hema-huiswijn open en schenkt vast een kom in voor
"""
fristxt = """ zet de deur en het raam open voor
geeft een glas cola aan
geeft een glas cola light aan
geeft een glas cherry coke aan
geeft een glas pepsi max aan
geeft een glas sinas aan
geeft een glas fanta aan
geeft een glas sprite aan
geeft een glas 7-up aan
pakt een flesje chocomel voor
geeft een glas jus d'orange aan
schenkt een glas appelsap in voor
sorry, het is te koud voor fris,
wijst naar een lege koelkast. sorry
ja lekker, doe mij ook wat,
"""
taarttxt = """ geeft je een punt appletaart met lekker veel slagroom.
bak het gerust zelf, alles ligt klaar voor je,
geeft een taart met kaas, salami, oregano en knoflook aan
geeft een punt chocoladetaart aan
geeft een punt slagroomtaart aan
geeft een punt appeltaart aan
geeft een punt aardbeientaart aan
geeft een punt vruchtentaart aan
geeft een punt advocaattaart aan
geeft een punt abrikozentaart aan
geeft een punt appelcitroentaart aan
geeft een punt appelkruimeltaart aan
geeft een punt bananentaart aan
geeft een punt boerenjongenstaart aan
geeft een punt bosvruchtentaart aan
geeft een punt champagnetaart aan
geeft een punt kersentaart aan
geeft een punt rijsttaart aan
geeft een punt mokkataart aan
geeft een punt notentaart aan
geeft een punt peche-melbataart aan
geeft een punt perentaart aan
geeft een punt schwarzwaldertaart aan
geeft een punt stroopwafeltaart aan
geeft een punt tiramisutaart aan
geeft een punt yoghurt-sinaastaart aan
geeft een punt zwitserse-roomtaart aan
"""
koektxt = """ geeft een lange vinger aan
geeft een speculaasje aan
geeft een stroopwafel aan
geeft een zandkoekje aan
geeft een sprits aan
geeft een muffin aan
geeft een slagroomsoesje aan
geeft een walnootkoekje aan
geeft een lekker kaaskoekje aan
geeft een honingkoekje aan
geeft een hazelnootkoekje aan
geeft een gemberkoekje aan
geeft een eclair aan
geeft een cremerolletje aan
geeft een chocoladekoekje aan
geeft een pindarotsje aan
geeft een bokkenpootje aan
geeft een lebkuchen aan
geeft een amandelkoekje aan
bak ze gerust zelf,
"""
chipstxt = """ geeft je een bakje bugles.
geeft een zakje naturel chips aan
pakt een zakje wokkels voor
geeft een zakje paprika chips aan
geeft een zakje bolognese chips aan
geeft een zakje barbecue ham chips aan
geeft een zakje cheese onion aan
geeft een zakje mexican salsa aan
pakt een zakje bugles voor
geeft een zakje hamka's.
*crunch* dank je,
loert tevergeefs in een lege chipszak voor
ja lekker,
"""
soeptxt = """ geeft een kom aspergesoep aan
geeft een kom bospaddestoelensoep aan
geeft een kom frisse erwtensoep aan
geeft een kom kip tikka soep aan
geeft een kom kruidige tomatensoep aan
geeft een kom mosterdsoep aan
geeft een kom ossenstaartsoep aan
geeft een kom pittige tomatensoep aan
geeft een kom romige kippensoep aan
geeft een kom romige tomatensoep aan
geeft een bord boerengroentesoep aan
geeft een kom champignonsoep aan
geeft een kom erwtensoep aan
geeft een kom goulashsoep aan
geeft een kom kippensoep aan
geeft een kom tomaten-creme soep aan
geeft een kom tomatensoep aan
geeft een kom bruine bonensoep aan
geeft een kom chinese tomatensoep aan
geeft een kom groentesoep aan
geeft een kom tomaten-groentesoep aan
geeft een kom uiensoep aan
geeft een kom kerrie-cremesoep aan
maak voor ons ook wat,
staart in een lege pan voor
vist een ouwe schoen uit de bouillon voor
"""
sextxt = """ huh? moeilijk? waar?
Snufj!
Nee nu niet, ik heb hoofdpijn.
Wacht dan doe ik een condoom aan.
Veel te koud voor sex.
Veel te warm voor sex.
Ja strakjes, eerst nog even dit afmaken...
Ja lekker!
Moo!
Heb je de sleutel van m'n kuisheidsgordel dan?
Rook jij ook na de sex?
Mag 't licht uit?
"""
rokentxt = """ Er is maar 1 weg na de longen en die moet geasfalteerd worden
Ohhh!!! heerlijk!!!.....
Riet rokers sterven ook!
Het nieuwe lied van K3: Rokus Spokus, iedereen kan roken!
Elk pakje sigaretten verkort je leven met 11 minuten, elke vrijjpartij verlengt je leven met 15 minuten. conclusie: ROKERS NEUK VOOR JE LEVEN!
Niet zeiken lekker ding, ik betaal jouw belasting!
Afspraak: Rook jij mijn laatste, koop jij een nieuwe.
Als mijn moeder dit pakje vind is het van jou!
Roken werkt ontspannend en is dus goed tegen hartklachten en algemene stress.
Ex-rokers moeten helemaal hun bek houden!
Niet roken bespaard geld? waarom heb jij t dan nooit?
Koop je eigen pakje KLOOTZAK!
Ik rook dus ik ben rijk, neuken?
Ik geef om jouw gezondheid dus blijf godverdomme van mijn peuken af!
Roken is slecht voor de zwangerschap, dat condoom kun je dus in je zak houden.
Roken is ongezond..... een dikke vatsige vetklep ook!
Roken na de sex houd mijn gezondheid in balans.
Moet ik er een bewaren voor na de sex of rook je niet?
Heb je last van je keel door mijn gerook? moet je er ook een opsteken, ik heb nooit last!
Wie meerookt hoort ook me te betalen!
Stoppen? Ik probeer het zo'n 20 keer per dag!
"""
beledigtxt = """schopt
misbruikt
verhuurt
slaat
mept
gooit koffie over
bitchslapt
schiet op
schijt in de mond van
vist in het aquarium van
pakt een koekenpan en slaat daarmee
hackt
stampt zo hard tusse de noten dat je je kindergeld kwijt bent,
moont
castreert
verloot
"""
| Python |
# jsb/plugs/common/watcher.py
#
#
""" watch channels. channels events can be of remote origin. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.callbacks import callbacks, remote_callbacks, last_callbacks, first_callbacks
from jsb.lib.persist import PlugPersist
from jsb.lib.fleet import getfleet
from jsb.utils.exception import handle_exception
from jsb.lib.examples import examples
from jsb.drivers.gae.wave.waves import Wave
from jsb.utils.locking import locked
from jsb.lib.eventbase import EventBase
## plugin imports
from jsb.utils.format import formatevent
## basic imports
import copy
import logging
## defines
cpy = copy.deepcopy
## Watched class
class Watched(PlugPersist):
""" Watched object contains channels and subscribers. """
def __init__(self, filename):
PlugPersist.__init__(self, filename)
self.data.channels = self.data.channels or {}
self.data.whitelist = self.data.whitelist or []
self.data.descriptions = self.data.descriptions or {}
def subscribe(self, botname, type, channel, jid):
""" subscrive a jid to a channel. """
channel = channel.lower()
jid = unicode(jid)
if not self.data.channels.has_key(channel):
self.data.channels[channel] = []
if not [botname, type, jid] in self.data.channels[channel]:
self.data.channels[channel].append([botname, type, jid])
self.save()
return True
def unsubscribe(self, botname, type, channel, jid):
""" unsubscribe a jid from a channel. """
channel = channel.lower()
try:
self.data.channels[channel].remove([botname, type, unicode(jid)])
except (KeyError, TypeError, ValueError):
return False
self.save()
return True
def reset(self, channel):
""" unsubscribe a jid from a channel. """
channel = channel.lower()
self.data.channels[channel] = []
self.save()
return True
def subscribers(self, channel):
""" get all subscribers of a channel. """
channel = channel.lower()
try:
return self.data.channels[channel]
except KeyError:
return []
def check(self, channel):
""" check if channel has subscribers. """
channel = channel.lower()
return self.data.channels.has_key(channel)
def enable(self, channel):
""" add channel to whitelist. """
channel = channel.lower()
if not channel in self.data.whitelist:
self.data.whitelist.append(channel)
self.save()
def disable(self, channel):
""" remove channel from whitelist. """
channel = channel.lower()
try:
self.data.whitelist.remove(channel)
except ValueError:
return False
self.save()
return True
def available(self, channel):
""" check if channel is on whitelist. """
channel = channel.lower()
return channel in self.data.whitelist
def channels(self, channel):
""" return channels on whitelist. """
channel = channel.lower()
res = []
for chan, targets in self.data.channels.iteritems():
if channel in str(targets):
res.append(chan)
return res
## watched object
watched = Watched('channels')
## functions
def writeout(botname, type, channel, txt, eventjson):
""" output the watched event to the channel. """
event = EventBase().load(eventjson)
watchbot = getfleet().byname(botname)
if not watchbot: watchbot = getfleet().makebot(type, botname)
if watchbot:
watchbot.outnocb(channel, txt, event=event)
## callbacks
def prewatchcallback(bot, event):
""" watch callback precondition. """
if event.isdcc: return False
logging.debug("watcher - checking %s - %s" % (event.channel, event.userhost))
if not event.channel: return False
if not event.txt: return
return watched.check(unicode(event.channel)) and event.how != "background" and event.forwarded
def watchcallback(bot, event):
""" the watcher callback, see if channels are followed and if so send data. """
#if not event.allowwatch: logging.warn("watch - allowwatch is not set - ignoring %s" % event.userhost) ; return
subscribers = watched.subscribers(event.channel)
watched.data.descriptions[event.channel.lower()] = event.title
logging.info("watcher - %s - %s" % (event.channel, str(subscribers)))
for item in subscribers:
try:
try: (botname, type, channel) = item
except ValueError: continue
if not event.allowatch: pass
elif channel not in event.allowwatch: logging.warn("watcher - allowwatch denied %s - %s" % (channel, event.allowwatch)) ; continue
m = formatevent(bot, event, subscribers, True)
if event.cbtype in ['OUTPUT', 'JOIN', 'PART', 'QUIT', 'NICK']: txt = u"[!] %s" % m.txt
else: txt = u"[%s] %s" % (m.nick or event.nick or event.auth, m.txt)
if txt.count('] [') > 2: logging.debug("watcher - %s - skipping %s" % (type, txt)) ; continue
logging.warn("watcher - forwarding to %s" % channel)
writeout(botname, type, channel, txt, event.tojson())
except Exception, ex: handle_exception()
first_callbacks.add('BLIP_SUBMITTED', watchcallback, prewatchcallback)
first_callbacks.add('PRIVMSG', watchcallback, prewatchcallback)
first_callbacks.add('JOIN', watchcallback, prewatchcallback)
first_callbacks.add('PART', watchcallback, prewatchcallback)
first_callbacks.add('QUIT', watchcallback, prewatchcallback)
first_callbacks.add('NICK', watchcallback, prewatchcallback)
first_callbacks.add('OUTPUT', watchcallback, prewatchcallback)
first_callbacks.add('MESSAGE', watchcallback, prewatchcallback)
first_callbacks.add('CONSOLE', watchcallback, prewatchcallback)
first_callbacks.add('WEB', watchcallback, prewatchcallback)
first_callbacks.add('DISPATCH', watchcallback, prewatchcallback)
## watcher-start command
def handle_watcherstart(bot, event):
""" [<channel>] .. start watching a target (channel/wave). """
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):
""" [<channel>] .. stop watching a channel/wave. """
watched.reset(event.channel)
event.done()
cmnds.add('watcher-reset', handle_watcherreset, 'OPER')
examples.add('watcher-reset', 'stop watching', 'watcher-reset')
## watcher-stop command
def handle_watcherstop(bot, event):
""" [<channel>] .. stop watching a channel/wave. """
if not event.rest: target = event.origin
else: target = event.rest
watched.unsubscribe(bot.cfg.name, bot.type, target, event.channel)
if target in event.chan.data.watched:
event.chan.data.watched.remove(target)
event.chan.save()
event.done()
cmnds.add('watcher-stop', handle_watcherstop, 'OPER')
examples.add('watcher-stop', 'stop watching a channel', 'watcher-stop #dunkbots')
## watcher-list command
def handle_watcherlist(bot, event):
""" see what channels we are watching. """
chans = watched.channels(event.channel)
if chans:
res = []
for chan in chans:
try: res.append(chan)
except KeyError: res.append(chan)
event.reply("channels watched on %s: " % event.channel, res)
cmnds.add('watcher-list', handle_watcherlist, ['OPER', 'USER', 'GUEST'])
examples.add('watcher-list', 'show what channels we are watching', 'watcher-channels')
## watcher-subscribers command
def handle_watchersubscribers(bot, event):
"""" show channels that are watching us. """
event.reply("watchers for %s: " % event.channel, watched.subscribers(event.channel))
cmnds.add('watcher-subscribers', handle_watchersubscribers, ['OPER', 'USER', 'GUEST'])
examples.add('watcher-subscribers', 'show channels that are watching us. ', 'watcher-list')
| Python |
# jsb/plugs/common/twitter.py
#
#
""" a twitter plugin for the JSONBOT. uses tweepy oauth. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.utils.pdol import Pdol
from jsb.utils.textutils import html_unescape
from jsb.utils.generic import waitforqueue, strippedtxt, splittxt
from jsb.lib.persist import PlugPersist
from jsb.utils.twitter import twitterapi, twittertoken
from jsb.lib.datadir import getdatadir
from jsb.lib.jsbimport import _import_byfile
## tweppy imports
from jsb.contrib.tweepy.auth import OAuthHandler
from jsb.contrib.tweepy.api import API
from jsb.contrib.tweepy import oauth
from jsb.contrib.tweepy.error import TweepError
from jsb.contrib.tweepy.models import Status, User
from jsb.contrib import tweepy
## basic imports
import os
import urllib2
import types
import logging
## credentials
def getcreds(datadir):
try:
mod = _import_byfile("credentials", datadir + os.sep + "config" + os.sep + "credentials.py")
except (IOError, ImportError):
logging.info("the twitter plugin needs the credentials.py file in the %s/config dir. see %s/examples" % (datadir, datadir))
return (None, None)
return mod.CONSUMER_KEY, mod.CONSUMER_SECRET
## defines
auth = None
go = True
def getauth(datadir):
global auth
if auth: return auth
key, secret = getcreds(datadir)
auth = OAuthHandler(key, secret)
return auth
## postmsg function
def postmsg(username, txt):
try:
result = splittxt(txt, 139)
twitteruser = TwitterUsers("users")
key, secret = getcreds(getdatadir())
token = twittertoken(key, secret, twitteruser, username)
if not token:
raise TweepError("Can't get twitter token")
twitter = twitterapi(key, secret, token)
for txt in result:
status = twitter.update_status(txt)
logging.info("logged %s tweets for %s" % (len(result), username))
except TweepError, ex: logging.error("twitter - error: %s" % str(ex))
return len(result)
## TwitterUsers class
class TwitterUsers(PlugPersist):
def add(self, user, token):
user = user.strip().lower()
self.data[user] = token
self.save()
def remove(self, user):
user = user.strip().lower()
if user in self.data:
del self.data[user]
self.save()
def size(self):
return len(self.data)
def __contains__(self, user):
user = user.strip().lower()
return user in self.data
## twitter command
def handle_twitter(bot, ievent):
""" send a twitter message. """
if not go: ievent.reply("the twitter plugin needs the credentials.py file in the .jsb/data/config dir. see .jsb/data/examples") ; return
if not ievent.rest: ievent.missing('<text>') ; return
else:
try: nritems = postmsg(ievent.user.data.name, ievent.rest) ; ievent.reply("%s tweet posted" % nritems)
except TweepError, ex:
if "token" in str(ex): ievent.reply("you are not registered yet.. use !twitter-auth")
except (TweepError, urllib2.HTTPError), e: ievent.reply('twitter failed: %s' % (str(e),))
cmnds.add('twitter', handle_twitter, ['USER', 'GUEST'])
examples.add('twitter', 'adds a message to your twitter account', 'twitter just found the http://gozerbot.org project')
## twitter-cmnd command
def handle_twittercmnd(bot, ievent):
""" do a twitter API cmommand. """
if not go: ievent.reply("the twitter plugin needs the credentials.py file in the .jsb/data//config dir. see .jsb/data/examples") ; return
if not ievent.args: ievent.missing('<text>') ; return
target = strippedtxt(ievent.args[0])
try:
twitteruser = TwitterUsers("users")
token = twitteruser.data.get(ievent.user.data.name)
if not token: ievent.reply("you are not logged in yet .. run the twitter-auth command.") ; return
key, secret = getcreds(getdatadir())
token = oauth.OAuthToken(key, secret).from_string(token)
twitter = twitterapi(key, secret, token)
cmndlist = dir(twitter)
cmnds = []
for cmnd in cmndlist:
if cmnd.startswith("_") or cmnd == "auth": continue
else: cmnds.append(cmnd)
if target not in cmnds: ievent.reply("choose one of: %s" % ", ".join(cmnds)) ; return
try: method = getattr(twitter, target)
except AttributeError: ievent.reply("choose one of: %s" % ", ".join(cmnds)) ; return
result = method()
res = []
for item in result:
try: res.append("%s - %s" % (item.screen_name, item.text))
except AttributeError:
try: res.append("%s - %s" % (item.screen_name, item.description))
except AttributeError:
try: res.append(unicode(item.__getstate__()))
except AttributeError: res.append(dir(i)) ; res.append(unicode(item))
ievent.reply("result of %s: " % target, res)
except KeyError: ievent.reply('you are not logged in yet. see the twitter-auth command.')
except (TweepError, urllib2.HTTPError), e: ievent.reply('twitter failed: %s' % (str(e),))
cmnds.add('twitter-cmnd', handle_twittercmnd, 'OPER')
examples.add('twitter-cmnd', 'do a cmnd on the twitter API', 'twitter-cmnd home_timeline')
## twitter-confirm command
def handle_twitter_confirm(bot, ievent):
""" confirm auth with PIN. """
if not go: ievent.reply("the twitter plugin needs the credentials.py file in the %s/config dir. see .jsb/data/examples" % getdatadir()) ; return
pin = ievent.args[0]
if not pin: ievent.missing("<PIN> .. see the twitter-auth command.") ; return
try: access_token = getauth(getdatadir()).get_access_token(pin)
except (TweepError, urllib2.HTTPError), e: ievent.reply('twitter failed: %s' % (str(e),)) ; return
twitteruser = TwitterUsers("users")
twitteruser.add(ievent.user.data.name, access_token.to_string())
ievent.reply("access token saved.")
cmnds.add('twitter-confirm', handle_twitter_confirm, ['OPER', 'USER', 'GUEST'])
examples.add('twitter-confirm', 'confirm your twitter account', '1) twitter-confirm 6992762')
## twitter-auth command
def handle_twitter_auth(bot, ievent):
""" get auth url. """
if not go: ievent.reply("the twitter plugin needs the credentials.py file in the .jsb/data/config dir. see .jsb/data/examples") ; return
try: auth_url = getauth(getdatadir()).get_authorization_url()
except (TweepError, urllib2.HTTPError), e: ievent.reply('twitter failed: %s' % (str(e),)) ; return
if bot.type == "irc":
bot.say(ievent.nick, "sign in at %s" % auth_url)
bot.say(ievent.nick, "use the provided code in the twitter-confirm command.")
else:
ievent.reply("sign in at %s" % auth_url)
ievent.reply("use the provided code in the twitter-confirm command.")
cmnds.add('twitter-auth', handle_twitter_auth, ['OPER', 'USER', 'GUEST'])
examples.add('twitter-auth', 'adds your twitter account', '1) twitter-auth')
## twitter-friends command
def handle_twitterfriends(bot, ievent):
""" do a twitter API cmommand. """
if not go: ievent.reply("the twitter plugin needs the credentials.py file in the .jsb/data/config dir. see .jsb/data/examples") ; return
try:
twitteruser = TwitterUsers("users")
token = twitteruser.data.get(ievent.user.data.name)
if not token: ievent.reply("you are not logged in yet .. run the twitter-auth command.") ; return
key , secret = getcreds(getdatadir())
token = oauth.OAuthToken(key, secret).from_string(token)
twitter = twitterapi(key, secret, token)
method = getattr(twitter, "friends_timeline")
result = method()
res = []
for item in result:
try: res.append("%s - %s" % (item.author.screen_name, item.text))
except Exception, ex: handle_exception()
ievent.reply("results: ", res)
except KeyError: ievent.reply('you are not logged in yet. see the twitter-auth command.')
except (TweepError, urllib2.HTTPError), e: ievent.reply('twitter failed: %s' % (str(e),))
cmnds.add('twitter-friends', handle_twitterfriends, ['OPER', 'USER', 'GUEST'])
examples.add('twitter-friends', 'show your friends_timeline', 'twitter-friends')
| Python |
# jsb/plugs/common/8b.py
#
#
""" run the eight ball. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## basic imports
import re
import random
## defines
balltxt=[
"Signs point to yes.",
"Yes.",
"Most likely.",
"Without a doubt.",
"Yes - definitely.",
"As I see it, yes.",
"You may rely on it.",
"Outlook good.",
"It is certain.",
"It is decidedly so.",
"Reply hazy, try again.",
"Better not tell you now.",
"Ask again later.",
"Concentrate and ask again.",
"Cannot predict now.",
"My sources say no.",
"Very doubtful.",
"My reply is no.",
"Outlook not so good.",
"Don't count on it."
]
## 8b command
def handle_8b(bot, ievent):
""" throw the eight ball. """
ievent.reply(random.choice(balltxt))
cmnds.add('8b', handle_8b, ['OPER', 'USER', 'GUEST'])
examples.add('8b', 'show what the magic 8 ball has to say.', '8b')
| Python |
# jsb/plugs/common/karma.py
#
#
""" karma plugin. """
## jsb imports
from jsb.lib.callbacks import callbacks
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persist import PlugPersist
from jsb.utils.statdict import StatDict
## basic imports
import logging
import re
## defines
RE_KARMA = re.compile(r'^(?P<item>\([^\)]+\)|\[[^\]]+\]|\w+)(?P<mod>\+\+|--)( |$)')
## KarmaItem class
class KarmaItem(PlugPersist):
def __init__(self, name, default={}):
PlugPersist.__init__(self, name)
self.data.name = name
self.data.count = self.data.count or 0
self.data.whoup = self.data.whoup or {}
self.data.whodown = self.data.whodown or {}
self.data.whyup = self.data.whyup or []
self.data.whydown = self.data.whydown or []
## karma-precondition
def prekarma(bot, event):
# if not event.iscmnd(): return False
# we want to catch all the ++ and to avoid cheating
if event.userhost in bot.ignore: return False
karmastring = re.search(RE_KARMA, event.txt)
if karmastring:
# ignore the karma from the same user
if karmastring.group('item') == event.nick : return False
else: return True
return False
## karma-callbacks
def karmacb(bot, event):
event.bind(bot)
if bot.type == "convore" and not event.chan.data.enable: return
targets = re.findall(RE_KARMA, event.txt)
karma = []
try: reason = event.txt.split('#', 1)[1] ; reason = reason.strip()
except IndexError: reason = None
for target in targets:
try: item, what, bogus = target
except ValueError: print target ; continue
item = item.lower()
if what == "++":
i = KarmaItem(event.channel.lower() + "-" + item)
i.data.count += 1
if event.nick not in i.data.whoup: i.data.whoup[event.nick] = 0
i.data.whoup[event.nick] += 1
if reason and reason not in i.data.whyup: i.data.whyup.append(reason)
i.save()
else:
i = KarmaItem(event.channel.lower() + "-" + item)
i.data.count -= 1
if event.nick not in i.data.whodown: i.data.whodown[event.nick] = 0
i.data.whodown[event.nick] -= 1
if reason and reason not in i.data.whyup: i.data.whydown.append(reason)
i.save()
karma.append("%s: %s" % (item, i.data.count))
got = item or item2
if karma: event.reply("karma - ", karma) ; event.ready()
callbacks.add('PRIVMSG', karmacb, prekarma)
callbacks.add('MESSAGE', karmacb, prekarma)
callbacks.add('CONSOLE', karmacb, prekarma)
callbacks.add('CONVORE', karmacb, prekarma)
## karma command
def handle_karma(bot, event):
""" show karma of item. """
if not event.rest: event.missing("<what>") ; 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):
""" 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
def handle_karmawhoup(bot, event):
""" show who increased the karma of an item. """
k = event.rest.lower()
item = KarmaItem(event.channel.lower() + "-" + k)
sd = StatDict(item.data.whoup)
res = []
for i in sd.top():
res.append("%s: %s" % i)
if res: event.reply("uppers of %s are: " % k, res)
else: event.reply("nobody upped %s yet" % k)
cmnds.add("karma-whoup", handle_karmawhoup, ['OPER', 'USER', 'GUEST'])
examples.add("karma-whoup", "show who upped an item", "karma-whoup jsb")
## karma-whydown command
def handle_karmawhydown(bot, event):
""" show reason why karma was lowered. """
k = event.rest.lower()
item = KarmaItem(event.channel.lower() + "-" + k)
if item.data.whydown: event.reply("reasons for karmadown are: ", item.data.whydown)
else: event.reply("no reasons for karmadown of %s known yet" % k)
cmnds.add("karma-whydown", handle_karmawhydown, ['OPER', 'USER', 'GUEST'])
examples.add("karma-whydown", "show why a karma item is downed", "karma-whydown jsb")
## karma-whodown command
def handle_karmawhodown(bot, event):
""" show who lowered the karma of an item. """
k = event.rest.lower()
item = KarmaItem(event.channel.lower() + "-" + k)
sd = StatDict(item.data.whodown)
res = []
for i in sd.down():
res.append("%s: %s" % i)
if res: event.reply("downers of %s are: " % k, res)
else: event.reply("nobody downed %s yet" % k)
cmnds.add("karma-whodown", handle_karmawhodown, ['OPER', 'USER', 'GUEST'])
examples.add("karma-whodown", "show who downed an item", "karma-whodown jsb")
| Python |
# jsb common plugins
#
#
""" this package contains all the plugins common to all drivers. """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb/plugs/common/todo.py
#
#
""" manage todo lists per users .. a time/data string can be provided to set
time on a todo item.
"""
## jsb imports
from jsb.utils.generic import getwho
from jsb.utils.timeutils import strtotime, striptime, today
from jsb.utils.locking import lockdec
from jsb.utils.exception import handle_exception
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.users import users
from jsb.lib.persist import PlugPersist
from jsb.lib.persiststate import UserState
from jsb.utils.lazydict import LazyDict
## basic imports
import time
import thread
import os
from datetime import datetime, timedelta
from time import localtime
## defines
todolock = thread.allocate_lock()
locked = lockdec(todolock)
## Todo-class
class Todo(LazyDict):
pass
## TodoList class
class TodoList(UserState):
def __init__(self, name, *args, **kwargs):
UserState.__init__(self, name, "todo", *args, **kwargs)
if self.data.list: self.data.list = [LazyDict(x) for x in self.data.list]
else: self.data.list = []
def add(self, txt, ttime=0, duration=0, warnsec=0, priority=0):
""" add a todo """
todo = Todo()
todo.time = ttime
todo.duration = duration
todo.warnsec = warnsec
todo.priority = priority
todo.txt = txt.strip()
self.data.list.append(todo)
self.save()
return len(self.data.list)
def delete(self, indexnr):
del self.data.list[indexnr-1]
self.save()
return self
def clear(self):
self.data.list = []
self.save()
return self
def toolate(self):
res = []
now = time.time()
for todo in self.data.list:
if todo.time < now: res.append(todo)
return res
def withintime(self, before, after):
res = []
for todo in self.data.list:
if todo.time > before and todo.time < after: res.append(todo)
return res
def timetodo(self):
min = 0
res = []
for todo in self.data.list:
if todo.time > min: res.append(todo)
return res
## todo command
def handle_todo(bot, ievent):
""" todo [<item>] .. show todo's or set todo item .. a time/date can be given. """
if len(ievent.args) > 0: handle_todo2(bot, ievent) ; return
name = ievent.channel
try: todoos = TodoList(name).data.list
except KeyError: ievent.reply('i dont have todo info for %s' % user.name) ; return
saytodo(bot, ievent, todoos)
def handle_todo2(bot, ievent):
""" set todo item """
if not ievent.rest: ievent.missing("<what>") ; return
else: 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')
## todo-done command
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
nrdone = 0
failed = []
todo = TodoList(name)
for i in nrs[::-1]:
try: del todo.data.list[i-1] ; nrdone += 1
except IndexError: continue
except Exception, ex: failed.append(str(i)) ; handle_exception()
if failed: ievent.reply('failed to delete %s' % ' .. '.join(failed))
if nrdone == 1: todo.save() ; ievent.reply('%s item deleted' % nrdone)
elif nrdone == 0: ievent.reply('no items deleted')
else:todo.save() ; ievent.reply('%s items deleted' % nrdone)
cmnds.add('todo-done', handle_tododone, ['USER', 'GUEST'])
examples.add('todo-done', 'todo-done <listofnrs> .. remove items from todo list', '1) todo-done 1 2) todo-done 3 5 8')
## todo-time command
def handle_todotime(bot, ievent):
""" todo-time .. show time related todoos """
name = ievent.channel
todo = TodoList(name)
todoos = todo.timetodo()
saytodo(bot, ievent, todoos)
cmnds.add('todo-time', handle_todotime, ['USER', 'GUEST'])
examples.add('todo-time', 'todo-time .. show todo items with time fields', 'todo-time')
## todo-week command
def handle_todoweek(bot, ievent):
""" todo-week .. show time related todo items for this week """
todo = TodoList(ievent.channel)
todoos = todo.withintime(today(), today()+7*24*60*60)
saytodo(bot, ievent, todoos)
cmnds.add('todo-week', handle_todoweek, ['USER', 'GUEST'])
examples.add('todo-week', 'todo-week .. todo items for this week', 'todo-week')
## todo-today command
def handle_today(bot, ievent):
""" todo-today .. show time related todo items for today """
name = ievent.channel
todo = TodoList(name)
now = time.time()
todoos = todo.withintime(now, now+3600*24)
saytodo(bot, ievent, todoos)
cmnds.add('todo-today', handle_today, ['USER', 'GUEST'])
examples.add('todo-today', 'todo-today .. todo items for today', 'todo-today')
## todo-tomorrow command
def handle_tomorrow(bot, ievent):
""" todo-tomorrow .. show time related todo items for tomorrow """
username = ievent.channel
todo = TodoList(username)
if ievent.rest:
what = ievent.rest
ttime = strtotime(what)
if ttime != None:
if ttime < today() or ttime > today() + 24*60*60:
ievent.reply("%s is not tomorrow" % time.ctime(ttime + 24*60*60))
return
ttime += 24*60*60
ievent.reply('time detected ' + time.ctime(ttime))
what = striptime(what)
else: ttime = today() + 42*60*60
todo.add(what, ttime)
ievent.reply('todo added')
return
todoos = todo.withintime(today()+24*60*60, today()+2*24*60*60)
saytodo(bot, ievent, todoos)
cmnds.add('todo-tomorrow', handle_tomorrow, ['USER', 'GUEST'])
examples.add('todo-tomorrow', 'todo-tomorrow .. todo items for tomorrow', \
'todo-tomorrow')
## todo-setprio command
def handle_setpriority(bot, ievent):
""" todo-setprio [<channel|name>] <itemnr> <prio> .. show priority on todo item. """
try:
(who, itemnr, prio) = ievent.args
except ValueError:
try: (itemnr, prio) = ievent.args ; who = ievent.channel
except ValueError: ievent.missing('[<channe|namel>] <itemnr> <priority>') ; return
try: itemnr = int(itemnr) ; prio = int(prio)
except ValueError: ievent.missing('[<channel|name>] <itemnr> <priority>') ; return
todo = TodoList(who)
try:
todo.data.list[itemnr-1].priority = prio
todo.save()
ievent.reply('priority set')
except IndexError: ievent.reply("no %s item in todolist" % str(itemnr))
cmnds.add('todo-setprio', handle_setpriority, ['USER', 'GUEST'])
examples.add('todo-setprio', 'todo-setprio [<channel|name>] <itemnr> <prio> .. set todo priority', '1) todo-setprio #dunkbots 2 5 2) todo-setprio owner 3 10 3) todo-setprio 2 10')
## todo-settime command
def handle_todosettime(bot, ievent):
""" todo-settime [<channel|name>] <itemnr> <timestring> .. set time \
on todo item """
ttime = strtotime(ievent.rest)
if ttime == None: ievent.reply("can't detect time") ; return
txt = striptime(ievent.rest)
try: (who, itemnr) = txt.split()
except ValueError:
try: (itemnr, ) = txt.split() ; who = ievent.channel
except ValueError: ievent.missing('[<channel|name>] <itemnr> <timestring>') ; return
try: itemnr = int(itemnr)
except ValueError: ievent.missing('[<channel|name>] <itemnr> <timestring>') ; return
todo = TodoList(who)
try:
todo.data.list[itemnr-1].time = ttime
todo.save()
ievent.reply('time of todo %s set to %s' % (itemnr, time.ctime(ttime)))
except IndexError: ievent.reply("%s item in todolist" % str(itemnr))
cmnds.add('todo-settime', handle_todosettime, ['USER', 'GUEST'])
examples.add('todo-settime', 'todo-settime [<channel|name>] <itemnr> <timestring> .. set todo time', '1) todo-settime #dunkbots 2 13:00 2) todo-settime owner 3 2-2-2010 3) todo-settime 2 22:00')
## todo-getprio command
def handle_getpriority(bot, ievent):
""" todo-getprio <[channel|name]> <itemnr> .. get priority of todo item. """
try: (who, itemnr) = ievent.args
except ValueError:
try: itemnr = ievent.args[0] ; who = ievent.channel
except IndexError: ievent.missing('[<channel|name>] <itemnr>') ; return
if not who: ievent.reply("can't find username for %s" % ievent.auth) ; return
try: itemnr = int(itemnr)
except ValueError: ievent.missing('[<channel|name>] <itemnr>') ; return
todo = TodoList(who)
try: prio = todo.data.list[itemnr].priority ; ievent.reply('priority is %s' % prio)
except IndexError: ievent.reply("%s item in todolist" % str(itemnr))
cmnds.add('todo-getprio', handle_getpriority, ['USER', 'GUEST'])
examples.add('todo-getprio', 'todo-getprio [<channel|name>] <itemnr> .. get todo priority', '1) todo-getprio #dunkbots 5 2) todo-getprio 3')
## saytodo function
def saytodo(bot, ievent, todoos):
""" output todo items of <name> """
if not todoos: ievent.reply('nothing todo ;]') ; return
result = []
now = time.time()
counter = 1
todoos.sort(lambda a, b: cmp(b.priority,a.priority))
for i in todoos:
res = ""
res += "%s) " % counter
counter += 1
if i.priority: res += "[%s] " % i.priority
if i.time and not i.time == 0:
if i.time < now: res += 'TOO LATE: '
res += "%s %s " % (time.ctime(float(i.time)), i.txt)
else: res += "%s " % i.txt
result.append(res.strip())
if result: ievent.reply("todo for %s: " % ievent.channel, result, dot=" ")
| Python |
# jsb/plugs/common/quote.py
#
#
""" manage quotes. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persist import PlugPersist
## basic imports
import random
## defines
quotes = PlugPersist('quotes.data')
if not quotes.data.index:
quotes.data.index = 0
## quote-add command
def handle_quoteadd(bot, event):
""" add a quote. """
quotes.data.index += 1
quotes.data[quotes.data.index] = event.rest
quotes.save()
event.reply("quote %s added" % quotes.data.index)
cmnds.add('quote-add', handle_quoteadd, ['USER', 'GUEST'])
examples.add('quote-add' , 'add a quote to the bot', 'quote-add blablabla')
## quote command
def handle_quote(bot, event):
""" get a quote. """
possible = quotes.data.keys()
possible.remove('index')
if possible: nr = random.choice(possible) ; event.reply("#%s %s" % (nr, quotes.data[nr]))
else: event.reply("no quotes yet.")
cmnds.add('quote', handle_quote, ['USER', 'GUEST'])
examples.add('quote' , 'get a quote from the bot', 'quote')
| Python |
# jsb/plugs/gae/gae.py
#
#
""" Google Application Engine related commands. """
## jsb imports
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
## gae-flushcache command
def handle_gaeflushcache(bot, ievent):
""" flush the cache .. flush all with no arguments otherwise delete specific. """
from google.appengine.api.memcache import flush_all, delete
if not ievent.rest: flush_all()
else: delete(ievent.rest)
ievent.done()
cmnds.add('gae-flushcache', handle_gaeflushcache, 'OPER')
examples.add('gae-flushcache', 'flush the bots cache', 'gae-flushcache')
## gae-stats command
def handle_gaeadminstats(bot, ievent):
""" show bot stats. """
from google.appengine.api.memcache import get_stats
ievent.reply("cache: %s" % str(get_stats()))
cmnds.add('gae-stats', handle_gaeadminstats, 'OPER')
examples.add('gae-stats', 'show bots stats', 'gae-stats')
| Python |
# jsb basic plugins
#
#
""" register all .py files """
import os
(f, tail) = os.path.split(__file__)
__all__ = []
for i in os.listdir(f):
if i.endswith('.py'):
__all__.append(i[:-3])
elif os.path.isdir(f + os.sep + i) and not i.startswith('.'):
__all__.append(i)
try:
__all__.remove('__init__')
except:
pass
__plugs__ = __all__
| Python |
# jsb/imports.py
#
#
""" provide a import wrappers for the contrib packages. """
## lib imports
from lib.jsbimport import _import
## basic imports
import logging
## getjson function
def getjson():
try:
import wave
mod = _import("jsb.contrib.simplejson")
except ImportError:
try: mod = _import("json")
except:
try:
mod = _import("simplejson")
except:
mod = _import("jsb.contrib.simplejson")
logging.debug("imports - json module is %s" % str(mod))
return mod
## getfeedparser function
def getfeedparser():
try: mod = _import("feedparser")
except:
mod = _import("jsb.contrib.feedparser")
logging.info("imports - feedparser module is %s" % str(mod))
return mod
def getoauth():
try: mod = _import("oauth")
except:
mod = _import("jsb.contrib.oauth")
logging.info("imports - oauth module is %s" % str(mod))
return mod
def getrequests():
try: mod = _import("requests")
except:
mod = _import("jsb.contrib.requests")
logging.info("imports - requests module is %s" % str(mod))
return mod
| Python |
# jsb/datadir.py
#
#
""" the data directory of the bot. """
## jsb imports
from jsb.utils.source import getsource
## basic imports
import re
import os
import shutil
import logging
import os.path
import getpass
## the global datadir
try: homedir = os.path.abspath(os.path.expanduser("~"))
except: homedir = os.getcwd()
isgae = False
try: getattr(os, "mkdir") ; logging.info("datadir - shell detected") ; datadir = homedir + os.sep + ".jsb"
except AttributeError: logging.info("datadir - skipping makedirs") ; datadir = "data" ; isgae = True
## helper functions
def touch(fname):
""" touch a file. """
fd = os.open(fname, os.O_WRONLY | os.O_CREAT)
os.close(fd)
def doit(ddir, mod):
source = getsource(mod)
if not source: raise Exception("can't find %s package" % mod)
shutil.copytree(source, ddir + os.sep + mod.replace(".", os.sep))
## makedir function
def makedirs(ddir=None):
""" make subdirs in datadir. """
#if os.path.exists("/home/jsb/.jsb") and getpass.getuser() == 'jsb': ddir = "/home/jsb/.jsb"
global datadir
datadir = ddir or getdatadir()
logging.warn("datadir - set to %s" % datadir)
if isgae: return
if not os.path.isdir(ddir):
try: os.mkdir(ddir)
except: logging.warn("can't make %s dir" % ddir) ; os._exit(1)
logging.info("making dirs in %s" % ddir)
try: os.chmod(ddir, 0700)
except: pass
last = datadir.split(os.sep)[-1]
#if not os.path.isdir(ddir): doit(ddir, "jsb.data")
try: doit(ddir, "jsb.plugs.myplugs")
except: pass
try: doit(ddir, "jsb.data.examples")
except: pass
try: touch(ddir + os.sep + "__init__.py")
except: pass
if not os.path.isdir(ddir + os.sep + "config"): os.mkdir(ddir + os.sep + "config")
if not os.path.isfile(ddir + os.sep + 'config' + os.sep + "mainconfig"):
source = getsource("jsb.data.examples")
if not source: raise Exception("can't find jsb.data.examples package")
try: shutil.copy(source + os.sep + 'mainconfig.example', ddir + os.sep + 'config' + os.sep + 'mainconfig')
except (OSError, IOError), ex: logging.error("datadir - failed to copy jsb.data.config.mainconfig: %s" % str(ex))
if not os.path.isfile(ddir + os.sep + 'config' + os.sep + "credentials.py"):
source = getsource("jsb.data.examples")
if not source: raise Exception("can't find jsb.data.examples package")
try: shutil.copy(source + os.sep + 'credentials.py.example', ddir + os.sep + 'config' + os.sep + 'credentials.py')
except (OSError, IOError), ex: logging.error("datadir - failed to copy jsb.data.config: %s" % str(ex))
try: touch(ddir + os.sep + "config" + os.sep + "__init__.py")
except: pass
# myplugs
initsource = getsource("jsb.plugs.myplugs")
if not initsource: raise Exception("can't find jsb.plugs.myplugs package")
initsource = initsource + os.sep + "__init__.py"
if not os.path.isdir(ddir + os.sep + 'myplugs'): os.mkdir(ddir + os.sep + 'myplugs')
if not os.path.isfile(ddir + os.sep + 'myplugs' + os.sep + "__init__.py"):
try:
shutil.copy(initsource, os.path.join(ddir, 'myplugs', '__init__.py'))
except (OSError, IOError), ex: logging.error("datadir - failed to copy myplugs/__init__.py: %s" % str(ex))
# myplugs.common
if not os.path.isdir(os.path.join(ddir, 'myplugs', 'common')): os.mkdir(os.path.join(ddir, 'myplugs', 'common'))
if not os.path.isfile(os.path.join(ddir, 'myplugs', "common", "__init__.py")):
try:
shutil.copy(initsource, os.path.join(ddir, 'myplugs', 'common', '__init__.py'))
except (OSError, IOError), ex: logging.error("datadir - failed to copy myplugs/common/__init__.py: %s" % str(ex))
# myplugs.gae
if not os.path.isdir(os.path.join(ddir, 'myplugs', 'gae')): os.mkdir(os.path.join(ddir, 'myplugs', 'gae'))
if not os.path.isfile(os.path.join(ddir, 'myplugs', "gae", "__init__.py")):
try:
shutil.copy(initsource, os.path.join(ddir, 'myplugs', 'gae', '__init__.py'))
except (OSError, IOError), ex: logging.error("datadir - failed to copy myplugs/gae/__init__.py: %s" % str(ex))
# myplugs.socket
if not os.path.isdir(os.path.join(ddir, 'myplugs', 'socket')): os.mkdir(os.path.join(ddir, 'myplugs', 'socket'))
if not os.path.isfile(os.path.join(ddir, 'myplugs', 'socket', "__init__.py")):
try:
shutil.copy(initsource, os.path.join(ddir, 'myplugs', 'socket', '__init__.py'))
except (OSError, IOError), ex: logging.error("datadir - failed to copy myplugs/socket/__init__.py: %s" % str(ex))
if not os.path.isdir(ddir + os.sep +'botlogs'): os.mkdir(ddir + os.sep + 'botlogs')
if not os.path.isdir(ddir + '/run/'): os.mkdir(ddir + '/run/')
if not os.path.isdir(ddir + '/users/'): os.mkdir(ddir + '/users/')
if not os.path.isdir(ddir + '/channels/'): os.mkdir(ddir + '/channels/')
if not os.path.isdir(ddir + '/fleet/'): os.mkdir(ddir + '/fleet/')
if not os.path.isdir(ddir + '/pgp/'): os.mkdir(ddir + '/pgp/')
if not os.path.isdir(ddir + '/plugs/'): os.mkdir(ddir + '/plugs/')
if not os.path.isdir(ddir + '/old/'): os.mkdir(ddir + '/old/')
def getdatadir():
global datadir
return datadir
def setdatadir(ddir):
global datadir
datadir = ddir
| Python |
# jsb/users.py
#
#
""" bot's users in JSON file. NOT USED AT THE MOMENT. """
## lib imports
from jsb.utils.exception import handle_exception, exceptionmsg
from jsb.utils.generic import stripped
from jsb.utils.name import stripname
from persiststate import UserState
from persist import Persist
from jsb.utils.lazydict import LazyDict
from datadir import getdatadir
from errors import NoSuchUser
from config import Config
## basic imports
import re
import types
import os
import time
import logging
## JsonUser class
class JsonUser(Persist):
""" LazyDict representing a user. """
def __init__(self, name, userhosts=[], perms=[], permits=[], status=[], email=[]):
assert name
name = stripname(name.lower())
Persist.__init__(self, getdatadir() + os.sep + 'users' + os.sep + name)
self.data.datadir = self.data.datadir or getdatadir()
self.data.name = self.data.name or name
self.data.userhosts = self.data.userhosts or userhosts
self.data.perms = self.data.perms or perms
self.data.permits = self.data.permits or permits
self.data.status = self.data.status or status
self.data.email = self.data.email or email
self.state = UserState(name)
## Users class
class Users(Persist):
""" class representing all users. """
def __init__(self, ddir=None, filename=None):
self.datadir = ddir or getdatadir()
self.filename = filename or 'mainusers'
Persist.__init__(self, self.datadir + os.sep + self.filename)
if not self.data: self.data = LazyDict()
self.data.names = self.data.names or {}
def all(self):
""" get all users. """
result = []
for name in self.data['names'].values(): result.append(JsonUser(name).lower())
return result
## Misc. Functions
def size(self):
""" return nr of users. """
return len(self.data['names'])
def names(self):
""" get names of all users. """
return self.data.names
def byname(self, name):
""" return user by name. """
try:
name = name.lower()
name = stripname(name)
user = JsonUser(name)
if user.data.userhosts: return user
except KeyError: raise NoSuchUser(name)
def merge(self, name, userhost):
""" add userhosts to user with name """
name = name.lower()
user = self.byname(name)
if user:
if not userhost in user.data.userhosts:
user.data.userhosts.append(userhost)
user.save()
self.data.names[userhost] = name
self.save()
logging.warn("%s merged with %s" % (userhost, name))
return 1
def usersearch(self, userhost):
""" search for users with a userhost like the one specified """
result = []
for u, name in self.data.names.iteritems():
if userhost in u: result.append((name.lower(), u))
return result
def getuser(self, userhost):
""" get user based on userhost. """
try:
user = self.byname(self.data.names[userhost])
if user: return user
except KeyError:
logging.debug("can't find %s in names cache" % userhost)
## Check functions
def exist(self, name):
""" see if user with <name> exists """
return self.byname(name)
def allowed(self, userhost, perms, log=True, bot=None):
""" check if user with userhosts is allowed to execute perm command """
if not type(perms) == types.ListType: perms = [perms, ]
if 'ANY' in perms: return 1
if bot and bot.allowall: return 1
res = None
user = self.getuser(userhost)
if not user:
logging.warn('%s userhost denied' % userhost)
return res
else:
uperms = set(user.data.perms)
sperms = set(perms)
intersection = sperms.intersection(uperms)
res = list(intersection) or None
if not res and log: logging.warn("%s perm %s denied (%s)" % (userhost, str(perms), str(uperms)))
return res
def permitted(self, userhost, who, what):
""" check if (who,what) is in users permit list """
user = self.getuser(userhost)
res = None
if user:
if '%s %s' % (who, what) in user.data.permits: res = 1
return res
def status(self, userhost, status):
""" check if user with <userhost> has <status> set """
user = self.getuser(userhost)
res = None
if user:
if status.upper() in user.data.status: res = 1
return res
def gotuserhost(self, name, userhost):
""" check if user has userhost """
user = self.byname(name)
return userhost in user.data.userhosts
def gotperm(self, name, perm):
""" check if user had permission """
user = self.byname(name)
if user: return perm.upper() in user.data.perms
def gotpermit(self, name, permit):
""" check if user permits something. permit is a (who, what) tuple """
user = self.byname(name)
if user: return '%s %s' % permit in user.data.permits
def gotstatus(self, name, status):
""" check if user has status """
user = self.byname(name)
return status.upper() in user.data.status
## Get Functions
def getname(self, userhost):
""" get name of user belonging to <userhost> """
try: return self.data.names[userhost]
except KeyError:
try: return self.data.names[userhost]
except KeyError:
user = self.getuser(userhost)
if user: return user.data.name.lower()
def gethosts(self, userhost):
""" return the userhosts of the user associated with the specified userhost """
user = self.getuser(userhost)
if user: return user.data.userhosts
def getemail(self, userhost):
""" return the email of the specified userhost """
user = self.getuser(userhost)
if user:
if user.data.email: return user.data.email[0]
def getperms(self, userhost):
""" return permission of user"""
user = self.getuser(userhost)
if user: return user.data.perms
def getpermits(self, userhost):
""" return permits of the specified userhost"""
user = self.getuser(userhost)
if user: return user.data.permits
def getstatuses(self, userhost):
""" return the list of statuses for the specified userhost. """
user = self.getuser(userhost)
if user: return user.data.status
def getuserhosts(self, name):
""" return the userhosts associated with the specified user. """
user = self.byname(name)
if user: return user.data.userhosts
def getuseremail(self, name):
""" get email of user. """
user = self.byname(name)
if user:
if user.data.email: return user.data.email[0]
def getuserperms(self, name):
""" return permission of user. """
user = self.byname(name)
if user: return user.data.perms
def getuserpermits(self, name):
""" return permits of user. """
user = self.byname(name)
if user: return user.data.permits
def getuserstatuses(self, name):
""" return the list of statuses for the specified user. """
user = self.byname(name)
if user: return user.data.status
def getpermusers(self, perm):
""" return all users that have the specified perm. """
result = []
for name in self.data.names:
user = JsonUser(name)
if perm.upper() in user.data.perms: result.append(user.data.name)
return result
def getstatususers(self, status):
""" return all users that have the specified status. """
result = []
for name in self.data.names:
user = JsonUser(name.lower())
if status in user.data.status: result.append(user.data.name.lower())
return result
## Set Functions
def setemail(self, name, email):
""" set email of user. """
user = self.byname(name)
if user:
try: user.data.email.remove(email)
except: pass
user.data.email.insert(0, email)
user.save()
return True
return False
## Add functions
def add(self, name, userhosts, perms):
""" add an user. """
name = name.lower()
newuser = JsonUser(name, userhosts, perms)
for userhost in userhosts: self.data.names[userhost] = name
newuser.save()
self.save()
logging.warn('%s - %s - %s - added to user database' % (name, userhosts, perms))
return True
def addguest(self, userhost):
if not self.getname(userhost):
if Config().guestasuser: self.add(userhost, [userhost, ], ["USER",])
else: self.add(userhost, [userhost, ], ["GUEST",])
def addemail(self, userhost, email):
""" add an email address to the userhost. """
user = self.getuser(userhost)
if user:
user.data.email.append(email)
user.save()
return 1
def addperm(self, userhost, perm):
""" add the specified perm to the userhost. """
user = self.getuser(userhost)
if user:
user.data.perms.append(perm.upper())
user.save()
return 1
def addpermit(self, userhost, permit):
""" add the given (who, what) permit to the given userhost. """
user = self.getuser(userhost)
if user:
user.data.permits.append(permit)
user.save()
return 1
def addstatus(self, userhost, status):
""" add status to given userhost. """
user = self.getuser(userhost)
if user:
user.data.status.append(status.upper())
user.save()
return 1
def adduserhost(self, name, userhost):
""" add userhost. """
name = name.lower()
user = self.byname(name)
if not user: user = self.users[name] = JsonUser(name=name)
user.data.userhosts.append(userhost)
user.save()
self.data.names[userhost] = name
self.save()
return 1
def adduseremail(self, name, email):
""" add email to specified user. """
user = self.byname(name)
if user:
user.data.email.append(email)
user.save()
return 1
def adduserperm(self, name, perm):
""" add permission. """
user = self.byname(name)
if user:
perm = perm.upper()
user.data.perms.append(perm)
user.save()
return 1
def adduserpermit(self, name, who, permit):
""" add (who, what) permit tuple to sepcified user. """
user = self.byname(name)
if user:
p = '%s %s' % (who, permit)
user.data.permits.append(p)
user.save()
return 1
def adduserstatus(self, name, status):
""" add status to given user. """
user = self.byname(name)
if user:
user.data.status.append(status.upper())
user.save()
return 1
def addpermall(self, perm):
""" add permission to all users. """
for name in self.data.names:
user = JsonUser(name.lower())
user.data.perms.append(perm.upper())
user.save()
## Delete functions
def delemail(self, userhost, email):
""" delete email from userhost. """
user = self.getuser(userhost)
if user:
if email in user.emails:
user.data.emails.remove(email)
user.save()
return 1
def delperm(self, userhost, perm):
""" delete perm from userhost. """
user = self.getuser(userhost)
if user:
p = perm.upper()
if p in user.perms:
user.data.perms.remove(p)
user.save()
return 1
def delpermit(self, userhost, permit):
""" delete permit from userhost. """
user = self.getuser(userhost)
if user:
p = '%s %s' % permit
if p in user.permits:
user.data.permits.remove(p)
user.save()
return 1
def delstatus(self, userhost, status):
""" delete status from userhost. """
user = self.getuser(userhost)
if user:
st = status.upper()
if st in user.data.status:
user.data.status.remove(st)
user.save()
return 1
def delete(self, name):
""" delete user with name. """
try:
name = name.lower()
user = JsonUser(name)
user.data.deleted = True
user.save()
if user:
for userhost in user.data.userhosts:
try: del self.data.names[userhost]
except KeyError: pass
self.save()
return True
except NoSuchUser:
pass
def deluserhost(self, name, userhost):
""" delete the userhost entry. """
user = self.byname(name)
if user:
if userhost in user.data.userhosts:
user.data.userhosts.remove(userhost)
user.save()
try: del self.data.names[userhost] ; self.save()
except KeyError: pass
return 1
def deluseremail(self, name, email):
""" delete email. """
user = self.byname(name)
if user:
if email in user.data.email:
user.data.email.remove(email)
user.save()
return 1
def deluserperm(self, name, perm):
""" delete permission. """
user = self.byname(name)
if user:
p = perm.upper()
if p in user.data.perms:
user.data.perms.remove(p)
user.save()
return 1
def deluserpermit(self, name, permit):
""" delete permit. """
user = self.byname(name)
if user:
p = '%s %s' % permit
if p in user.data.permits:
user.data.permits.remove(p)
user.save()
return 1
def deluserstatus(self, name, status):
""" delete the status from the given user. """
user = self.byname(name)
if user:
st = status.upper()
if st in user.data.status:
user.data.status.remove(status)
user.save()
return 1
def delallemail(self, name):
""" delete all emails for the specified user. """
user = self.byname(name)
if user:
user.data.email = []
user.save()
return 1
def make_owner(self, userhosts):
""" see if owner already has a user account if not add it. """
if not userhosts:
logging.info("no usershosts provided in make_owner")
return
owner = []
if type(userhosts) != types.ListType: owner.append(userhosts)
else: owner = userhosts
for userhost in owner:
username = self.getname(unicode(userhost))
if not username or username != 'owner':
if not self.merge('owner', unicode(userhost)): self.add('owner', [unicode(userhost), ], ['USER', 'OPER', 'GUEST'])
## global users object
users = None
## users_boot function
def users_boot():
""" initialize global users object. """
global users
users = Users()
return users
| Python |
# jsb/gozerevent.py
#
#
"""
basic event used in jsb. supports json dumping and loading plus toxml
functionality.
"""
## jsb imports
from jsb.utils.url import striphtml
from jsb.lib.eventbase import EventBase
## dom imports
from jsb.contrib.xmlstream import NodeBuilder, XMLescape, XMLunescape
## for exceptions
import xml.parsers.expat
## xmpp imports
from jsb.drivers.xmpp.namespace import attributes, subelements
## basic imports
import logging
## GozerEvent class
class GozerEvent(EventBase):
""" dictionairy to store xml stanza attributes. """
def __init__(self, input={}):
if input == None: EventBase.__init__(self)
else: EventBase.__init__(self, input)
try: self['fromm'] = self['from']
except (KeyError, TypeError): self['fromm'] = ''
def __getattr__(self, name):
""" override getattribute so nodes in payload can be accessed. """
if not self.has_key(name) and self.has_key('subelements'):
for i in self['subelements']:
if name in i: return i[name]
return EventBase.__getattr__(self, name, default="")
def get(self, name):
""" get a attribute by name. """
if self.has_key('subelements'):
for i in self['subelements']:
if name in i: return i[name]
if self.has_key(name): return self[name]
return EventBase()
def tojabber(self):
""" convert the dictionary to xml. """
res = dict(self)
if not res:
raise Exception("%s .. toxml() can't convert empty dict" % self.name)
elem = self['element']
main = "<%s" % self['element']
for attribute in attributes[elem]:
if attribute in res:
if res[attribute]: main += u" %s='%s'" % (attribute, XMLescape(res[attribute]))
continue
main += ">"
gotsub = False
if res.has_key('html'):
if res['html']:
main += u'<html xmlns="http://jabber.org/protocol/xhtml-im"><body xmlns="http://www.w3.org/1999/xhtml">%s</body></html>' % res['html']
gotsub = True
if res.has_key('txt'):
if res['txt']:
main += u"<body>%s</body>" % XMLescape(res['txt'])
gotsub = True
for subelement in subelements[elem]:
if subelement == "body": continue
try:
data = res[subelement]
if data:
main += "<%s>%s</%s>" % (subelement, XMLescape(data), subelement)
gotsub = True
except KeyError: pass
if gotsub: main += "</%s>" % elem
else:
main = main[:-1]
main += "/>"
return main
def str(self):
""" convert to string. """
result = ""
elem = self['element']
for item, value in dict(self).iteritems():
if item in attributes[elem] or item in subelements[elem] or item == 'txt': result += "%s='%s' " % (item, value)
return result
| Python |
# gozerbot/morphs.py
#
#
""" convert input/output stream. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.utils.trace import calledfrom
## basic imports
import sys
import logging
## Morph claas
class Morph(object):
""" transform stream. """
def __init__(self, func):
self.modname = calledfrom(sys._getframe(1))
self.func = func
self.activate = True
def do(self, *args, **kwargs):
""" do the morphing. """
if not self.activate: logging.warn("morphs - %s morph is not enabled" % str(self.func)) ; return
#logging.warn("morphs - using morph function %s" % str(self.func))
try: return self.func(*args, **kwargs)
except Exception, ex: handle_exception()
class MorphList(list):
""" list of morphs. """
def add(self, func, index=None):
""" add morph. """
m = Morph(func)
if not index: self.append(m)
else: self.insert(index, m)
logging.warn("morphs - added morph function %s - %s" % (str(func), m.modname))
return self
def do(self, input, *args, **kwargs):
""" call morphing chain. """
for morph in self: input = morph.do(input, *args, **kwargs) or input
return input
def unload(self, modname):
""" unload morhps belonging to plug <modname>. """
for index in range(len(self)-1, -1, -1):
if self[index].modname == modname: del self[index]
def disable(self, modname):
""" disable morhps belonging to plug <modname>. """
for index in range(len(self)-1, -1, -1):
if self[index].modname == modname: self[index].activate = False
def activate(self, plugname):
""" activate morhps belonging to plug <plugname>. """
for index in range(len(self)-1, -1, -1):
if self[index].modname == modname: self[index].activate = True
## global morphs
inputmorphs = MorphList()
outputmorphs = MorphList()
| Python |
# jsb/reboot.py
#
#
""" reboot code. """
## jsb imports
from jsb.lib.fleet import getfleet
from jsb.imports import getjson
json = getjson()
## basic imports
import os
import sys
import pickle
import tempfile
import logging
## reboot function
def reboot():
""" reboot the bot. """
logging.warn("reboot - rebooting")
os.execl(sys.argv[0], *sys.argv)
## reboot_stateful function
def reboot_stateful(bot, ievent, fleet, partyline):
""" reboot the bot, but keep the connections (IRC only). """
logging.warn("reboot - doing statefull reboot")
session = {'bots': {}, 'name': bot.cfg.name, 'channel': ievent.nick, 'partyline': []}
for i in getfleet().bots:
logging.warn("reboot - updating %s" % i.cfg.name)
data = i._resumedata()
if not data: continue
session['bots'].update(data)
if i.type == "sxmpp": i.exit() ; continue
if i.type == "convore": i.exit()
session['partyline'] = partyline._resumedata()
sessionfile = tempfile.mkstemp('-session', 'jsb-')[1]
json.dump(session, open(sessionfile, 'w'))
getfleet().save()
os.execl(sys.argv[0], sys.argv[0], '-r', sessionfile)
| Python |
# jsb/botbase.py
#
#
""" base class for all bots. """
## jsb imports
from jsb.utils.exception import handle_exception
from runner import defaultrunner, callbackrunner, waitrunner
from eventhandler import mainhandler
from jsb.utils.lazydict import LazyDict
from plugins import plugs as coreplugs
from callbacks import callbacks, first_callbacks, last_callbacks, remote_callbacks
from eventbase import EventBase
from errors import NoSuchCommand, PlugsNotConnected, NoOwnerSet, NameNotSet, NoEventProvided
from commands import Commands, cmnds
from config import Config
from jsb.utils.pdod import Pdod
from channelbase import ChannelBase
from less import Less, outcache
from boot import boot, getcmndperms, default_plugins
from jsb.utils.locking import lockdec
from exit import globalshutdown
from jsb.utils.generic import splittxt, toenc, fromenc, waitforqueue, strippedtxt, waitevents, stripcolor
from jsb.utils.trace import whichmodule
from fleet import getfleet
from aliases import getaliases
from jsb.utils.name import stripname
from tick import tickloop
from threads import start_new_thread, threaded
from morphs import inputmorphs, outputmorphs
from gatekeeper import GateKeeper
from wait import waiter
## basic imports
import time
import logging
import copy
import sys
import getpass
import os
import thread
import types
import threading
import Queue
import re
## defines
cpy = copy.deepcopy
## locks
reconnectlock = threading.RLock()
reconnectlocked = lockdec(reconnectlock)
lock = thread.allocate_lock()
locked = lockdec(lock)
## classes
class BotBase(LazyDict):
""" base class for all bots. """
def __init__(self, cfg=None, usersin=None, plugs=None, botname=None, nick=None, *args, **kwargs):
logging.info("botbase - type is %s" % str(type(self)))
if cfg: cfg = LazyDict(cfg)
if cfg and not botname: botname = cfg.botname or cfg.name
if not botname: botname = u"default-%s" % str(type(self)).split('.')[-1][:-2]
if not botname: raise Exception("can't determine type")
self.fleetdir = u'fleet' + os.sep + stripname(botname)
self.cfg = Config(self.fleetdir + os.sep + u'config')
if cfg: self.cfg.merge(cfg)
self.cfg.name = botname
if not self.cfg.name: raise Exception("botbase - name is not set in %s config file" % self.fleetdir)
logging.info("botbase - name is %s" % self.cfg.name)
LazyDict.__init__(self)
self.ignore = []
self.ids = []
self.aliases = getaliases()
self.curevent = None
self.inqueue = Queue.Queue()
self.outqueue = Queue.Queue()
self.reconnectcount = 0
self.stopped = False
self.plugs = coreplugs
self.gatekeeper = GateKeeper(self.cfg.name)
self.gatekeeper.allow(self.user or self.jid or self.cfg.server or self.cfg.name)
self.closed = False
try:
import waveapi
self.isgae = True
logging.debug("botbase - bot is a GAE bot (%s)" % self.cfg.name)
except ImportError:
self.isgae = False
logging.debug("botbase - bot is a shell bot (%s)" % self.cfg.name)
self.starttime = time.time()
self.type = "base"
self.status = "init"
self.networkname = self.cfg.networkname or self.cfg.name or ""
if not self.uuid:
if self.cfg and self.cfg.uuid: self.uuid = self.cfg.uuid
else:
self.uuid = self.cfg.uuid = uuid.uuid4()
self.cfg.save()
if self.cfg and not self.cfg.followlist: self.cfg.followlist = [] ; self.cfg.save()
from jsb.lib.datadir import getdatadir
datadir = getdatadir()
self.datadir = datadir + os.sep + self.fleetdir
self.owner = self.cfg.owner
if not self.owner:
logging.debug(u"owner is not set in %s - using mainconfig" % self.cfg.cfile)
self.owner = Config().owner
self.setusers(usersin)
logging.info(u"botbase - owner is %s" % self.owner)
self.users.make_owner(self.owner)
self.outcache = outcache
self.userhosts = {}
self.connectok = threading.Event()
self.reconnectcount = 0
self.cfg.nick = nick or self.cfg.nick or u'jsb'
try:
if not os.isdir(self.datadir): os.mkdir(self.datadir)
except: pass
self.setstate()
self.stopreadloop = False
self.stopoutloop = False
self.outputlock = thread.allocate_lock()
self.outqueues = [Queue.Queue() for i in range(10)]
self.tickqueue = Queue.Queue()
self.encoding = self.cfg.encoding or "utf-8"
self.cmndperms = getcmndperms()
self.outputmorphs = outputmorphs
self.inputmorphs = inputmorphs
#fleet = getfleet(datadir)
#if not fleet.byname(self.cfg.name): fleet.bots.append(self) ;
if not self.isgae:
defaultrunner.start()
callbackrunner.start()
waitrunner.start()
tickloop.start(self)
def __deepcopy__(self, a):
""" deepcopy an event. """
logging.debug("botbase - cpy - %s" % type(self))
bot = BotBase(self.cfg)
bot.copyin(self)
return bot
def copyin(self, data):
self.update(data)
def _resume(self, data, botname, *args, **kwargs):
pass
def _resumedata(self):
""" return data needed for resuming. """
data = self.cfg
try: data.fd = self.sock.fileno()
except: pass
return {self.cfg.name: data}
def enable(self, modname):
""" enable plugin given its modulename. """
try: self.cfg.blacklist and self.cfg.blacklist.remove(modname)
except ValueError: pass
if self.cfg.loadlist and modname not in self.cfg.loadlist: self.cfg.loadlist.append(modname)
self.cfg.save()
def disable(self, modname):
""" disable plugin given its modulename. """
if self.cfg.blacklist and modname not in self.cfg.blacklist: self.cfg.blacklist.append(modname)
if self.cfg.loadlist and modname in self.cfg.loadlist: self.cfg.loadlist.remove(modname)
self.cfg.save()
def put(self, event):
""" put an event on the worker queue. """
if self.isgae:
from jsb.drivers.gae.tasks import start_botevent
start_botevent(self, event, event.speed)
else: self.inqueue.put_nowait(event)
def broadcast(self, txt):
""" broadcast txt to all joined channels. """
for chan in self.state['joinedchannels']:
self.say(chan, txt)
def _eventloop(self):
""" fetch events from the inqueue and handle them. """
logging.debug("%s - eventloop started" % self.cfg.name)
while not self.stopped:
event = self.inqueue.get()
if not event: break
self.doevent(event)
logging.error("%s - eventloop stopped" % self.cfg.name)
def _getqueue(self):
""" get one of the outqueues. """
go = self.tickqueue.get()
for index in range(len(self.outqueues)):
if not self.outqueues[index].empty(): return self.outqueues[index]
def _outloop(self):
""" output loop. """
logging.debug('%s - starting output loop' % self.cfg.name)
self.stopoutloop = 0
while not self.stopped and not self.stopoutloop:
queue = self._getqueue()
if queue:
try:
res = queue.get()
except Queue.Empty: continue
if not res: continue
if not self.stopped and not self.stopoutloop:
logging.debug("%s - OUT - %s - %s" % (self.cfg.name, self.type, str(res)))
self.out(*res)
time.sleep(0.1)
logging.debug('%s - stopping output loop' % self.cfg.name)
def putonqueue(self, nr, *args):
""" put output onto one of the output queues. """
self.outqueues[10-nr].put_nowait(args)
self.tickqueue.put_nowait('go')
def outputsizes(self):
""" return sizes of output queues. """
result = []
for q in self.outqueues:
result.append(q.qsize())
return result
def setstate(self, state=None):
""" set state on the bot. """
self.state = state or Pdod(self.datadir + os.sep + 'state')
if self.state and not 'joinedchannels' in self.state.data: self.state.data.joinedchannels = []
def setusers(self, users=None):
""" set users on the bot. """
if users:
self.users = users
return
import jsb.lib.users as u
if not u.users: u.users_boot()
self.users = u.users
def loadplugs(self, packagelist=[]):
""" load plugins from packagelist. """
self.plugs.loadall(packagelist)
return self.plugs
def joinchannels(self):
""" join channels. """
time.sleep(Config().waitforjoin or 5)
for i in self.state['joinedchannels']:
try:
logging.debug("%s - joining %s" % (self.cfg.name, i))
channel = ChannelBase(i, self.cfg.name)
if channel: key = channel.data.key
else: key = None
if channel.data.nick: self.ids.append("%s/%s" % (i, channel.data.nick))
start_new_thread(self.join, (i, key))
time.sleep(1)
except Exception, ex:
logging.warn('%s - failed to join %s: %s' % (self.cfg.name, i, str(ex)))
handle_exception()
def start(self, connect=True, join=True):
""" start the mainloop of the bot. """
if not self.isgae:
if connect: self.connect()
start_new_thread(self._outloop, ())
start_new_thread(self._eventloop, ())
start_new_thread(self._readloop, ())
if connect:
self.connectok.wait(120)
if self.connectok.isSet():
logging.warn('%s - logged on !' % self.cfg.name)
if join: start_new_thread(self.joinchannels, ())
elif self.type not in ["console", "base"]: logging.warn("%s - failed to logon - connectok is not set" % self.cfg.name)
self.status == "running"
self.dostart(self.cfg.name, self.type)
def doremote(self, event):
""" dispatch an event. """
if not event: raise NoEventProvided()
event.forwarded = True
logging.info("======== start handling REMOTE event ========")
event.prepare(self)
self.status = "callback"
starttime = time.time()
msg = "%s - %s - %s - %s" % (self.cfg.name, event.auth, event.how, event.cbtype)
if event.how == "background": logging.debug(msg)
else: logging.info(msg)
logging.debug("botbase - remote - %s" % event.dump())
if self.closed:
if self.gatekeeper.isblocked(event.origin): return
if event.status == "done":
logging.debug("%s - event is done .. ignoring" % self.cfg.name)
return
self.reloadcheck(event)
e0 = cpy(event)
e0.speed = 1
remote_callbacks.check(self, e0)
logging.info("======== start handling REMOTE event ========")
return
def doevent(self, event):
""" dispatch an event. """
time.sleep(0.001)
if not self.cfg: raise Exception("eventbase - cfg is not set .. can't handle event.") ; return
if not event: raise NoEventProvided()
try:
if event.isremote(): self.doremote(event) ; return
if event.type == "groupchat" and event.fromm in self.ids:
logging.warn("%s - receiving groupchat from self (%s)" % (self.cfg.name, event.fromm))
return
event.txt = self.inputmorphs.do(fromenc(event.txt, self.encoding), event)
except UnicodeDecodeError: logging.warn("%s - got decode error in input .. ingoring" % self.cfg.name) ; return
logtxt = "%s - %s ======== start handling local event ======== %s" % (self.cfg.name, event.cbtype, event.userhost)
if event.cbtype in ['NOTICE']: logging.warn("%s - %s - %s" % (self.cfg.name, event.nick, event.txt))
else:
try:
int(event.cbtype)
logging.debug(logtxt)
except (ValueError, TypeError):
if event.cbtype in ['PING', 'PRESENCE'] or event.how == "background":
logging.debug(logtxt)
else: logging.info(logtxt)
event.bind(self)
logging.debug("%s - event dump: %s" % (self.cfg.name, event.dump()))
self.status = "callback"
starttime = time.time()
if self.closed:
if self.gatekeeper.isblocked(event.origin): return
if event.status == "done":
logging.debug("%s - event is done .. ignoring" % self.cfg.name)
return
self.reloadcheck(event)
if event.msg or event.isdcc: event.speed = 2
e1 = cpy(event)
first_callbacks.check(self, e1)
if not e1.stop:
callbacks.check(self, e1)
if not e1.stop: last_callbacks.check(self, e1)
event.callbackdone = True
#if not self.isgae: import asyncore ; asyncore.loop(1)
waiter.check(self, event)
return event
def ownercheck(self, userhost):
""" check if provided userhost belongs to an owner. """
if self.cfg and self.cfg.owner:
if userhost in self.cfg.owner: return True
return False
def exit(self, stop=True):
""" exit the bot. """
logging.warn("%s - exit" % self.cfg.name)
if not self.stopped: self.quit()
if stop:
self.stopped = True
self.stopreadloop = True
self.connected = False
self.put(None)
self.tickqueue.put_nowait('go')
self.outqueue.put_nowait(None)
self.shutdown()
self.save()
def _raw(self, txt, *args, **kwargs):
""" override this. """
logging.debug(u"%s - out - %s" % (self.cfg.name, txt))
print txt
def makeoutput(self, printto, txt, result=[], nr=375, extend=0, dot=", ", origin=None, *args, **kwargs):
if not txt: return ""
txt = self.makeresponse(txt, result, dot)
res1, nritems = self.less(origin or printto, txt, nr+extend)
return res1
def out(self, printto, txt, how="msg", event=None, origin=None, html=False, *args, **kwargs):
self.outnocb(printto, txt, how, event=event, origin=origin, html=html, *args, **kwargs)
self.outmonitor(origin, printto, txt, event=event)
write = out
def outnocb(self, printto, txt, how="msg", event=None, origin=None, html=False, *args, **kwargs):
self._raw(txt)
writenocb = outnocb
def say(self, channel, txt, result=[], how="msg", event=None, nr=375, extend=0, dot=", ", *args, **kwargs):
if event and event.userhost in self.ignore: logging.warn("%s - ignore on %s - no output done" % (self.cfg.name, event.userhost)) ; return
if event and event.nooutput:
logging.debug("%s - event has nooutput set, not outputing" % self.cfg.name)
if event: event.outqueue.put_nowait(txt)
return
if event and event.how == "msg":
if self.type == "irc": target = event.nick
else: target = channel
else: target = channel
if event and event.showall: txt = self.makeresponse(txt, result, dot, *args, **kwargs)
else: txt = self.makeoutput(channel, txt, result, nr, extend, dot, origin=target, *args, **kwargs)
if txt:
if event:
event.resqueue.put_nowait(txt)
event.outqueue.put_nowait(txt)
if event.path != None and not self.cfg.name in event.path: event.path.append(self.cfg.name)
txt = self.outputmorphs.do(txt, event)
self.out(target, txt, how, event=event, origin=target, *args, **kwargs)
if event: event.result.append(txt)
def saynocb(self, channel, txt, result=[], how="msg", event=None, nr=375, extend=0, dot=", ", *args, **kwargs):
txt = self.makeoutput(channel, txt, result, nr, extend, dot, *args, **kwargs)
if event and not self.cfg.name in event.path: event.path.append(self.cfg.name)
txt = self.outputmorphs.do(txt, event)
if txt:
self.outnocb(channel, txt, how, event=event, origin=channel, *args, **kwargs)
if event: event.result.append(txt)
def less(self, printto, what, nr=365):
""" split up in parts of <nr> chars overflowing on word boundaries. """
if type(what) == types.ListType: txtlist = what
else:
what = what.strip()
txtlist = splittxt(what, nr)
size = 0
if not txtlist:
logging.debug("can't split txt from %s" % what)
return ["", ""]
res = txtlist[0]
length = len(txtlist)
if length > 1:
logging.info("addding %s lines to %s outputcache" % (len(txtlist), printto))
outcache.set(u"%s-%s" % (self.cfg.name, printto), txtlist[1:])
res += "<b> - %s more</b>" % (length - 1)
return [res, length]
def join(self, channel, password, *args, **kwargs):
""" join a channel. """
pass
def part(self, channel, *args, **kwargs):
""" leave a channel. """
pass
def action(self, channel, txt, event=None, *args, **kwargs):
""" send action to channel. """
pass
def reconnect(self):
""" reconnect to the server. """
if self.stopped: logging.warn("%s - bot is stopped .. not reconnecting" % self.cfg.name) ; return
try:
try: self.exit()
except Exception, ex: handle_exception()
self.reconnectcount += 1
logging.warn('%s - reconnecting .. sleeping %s seconds' % (self.cfg.name, self.reconnectcount*15))
time.sleep(self.reconnectcount * 15)
self.doreconnect()
except Exception, ex:
handle_exception()
def doreconnect(self):
self.start(connect=True)
def invite(self, *args, **kwargs):
""" invite another user/bot. """
pass
def donick(self, nick, *args, **kwargs):
""" do a nick change. """
pass
def shutdown(self, *args, **kwargs):
""" shutdown the bot. """
pass
def quit(self, reason="", *args, **kwargs):
""" close connection with the server. """
pass
def connect(self, reconnect=True, *args, **kwargs):
""" connect to the server. """
pass
def names(self, channel, *args, **kwargs):
""" request all names of a channel. """
pass
def save(self, *args, **kwargs):
""" save bot state if available. """
if self.state: self.state.save()
def makeresponse(self, txt, result=[], dot=", ", *args, **kwargs):
""" create a response from a string and result list. """
res = []
dres = []
if type(txt) == types.DictType or type(txt) == types.ListType:
result = txt
if type(result) == types.DictType:
for key, value in result.iteritems():
dres.append(u"%s: %s" % (key, unicode(value)))
if dres: target = dres
else: target = result
if target:
txt = u"<b>" + txt + u"</b>"
for i in target:
if not i: continue
if type(i) == types.ListType or type(i) == types.TupleType:
try:
res.append(dot.join(i))
except TypeError: res.extend(i)
elif type(i) == types.DictType:
for key, value in i.iteritems():
res.append(u"%s: %s" % (key, unicode(value)))
else: res.append(unicode(i))
ret = ""
if txt: ret = unicode(txt) + dot.join(res)
elif res: ret = dot.join(res)
if ret: return ret
return ""
def reloadcheck(self, event, target=None):
""" check if plugin need to be reloaded for callback, """
plugloaded = []
target = target or event.cbtype or event.cmnd
try:
from boot import getcallbacktable
p = getcallbacktable()[target]
except KeyError:
logging.debug("botbase - can't find plugin to reload for %s" % event.cmnd)
return
logging.debug("%s - checking %s" % (self.cfg.name, unicode(p)))
for name in p:
if name in self.plugs:
logging.debug("%s - %s is already loaded" % (self.cfg.name, name))
continue
if name in default_plugins: pass
elif self.cfg.blacklist and name in self.cfg.blacklist:
logging.warn("%s - %s is in blacklist" % (self.cfg.name, name))
continue
elif self.cfg.loadlist and name not in self.cfg.loadlist:
logging.warn("%s - %s is not in loadlist" % (self.cfg.name, name))
continue
logging.info("%s - on demand reloading of %s" % (self.cfg.name, name))
try:
mod = self.plugs.reload(name, force=True, showerror=False)
if mod: plugloaded.append(mod) ; continue
except Exception, ex: handle_exception(event)
return plugloaded
def send(self, *args, **kwargs):
pass
def sendnocb(self, *args, **kwargs):
pass
def normalize(self, what):
""" convert markup to IRC bold. """
txt = strippedtxt(what, ["\002", "\003"])
txt = re.sub("\s+", " ", what)
txt = stripcolor(txt)
txt = txt.replace("\002", "*")
txt = txt.replace("<b>", "")
txt = txt.replace("</b>", "")
txt = txt.replace("<i>", "")
txt = txt.replace("</i>", "")
txt = txt.replace("<b>", "*")
txt = txt.replace("</b>", "*")
txt = txt.replace("<i>", "")
txt = txt.replace("</i>", "")
return txt
def dostart(self, botname=None, bottype=None, *args, **kwargs):
""" create an START event and send it to callbacks. """
e = EventBase()
e.bot = self
e.botname = botname or self.cfg.name
e.bottype = bottype or self.type
e.origin = e.botname
e.ruserhost = self.cfg.name +'@' + self.uuid
e.userhost = e.ruserhost
e.channel = botname
e.origtxt = str(time.time())
e.txt = e.origtxt
e.cbtype = 'START'
e.botoutput = False
e.ttl = 1
e.nick = self.cfg.nick or self.cfg.name
self.doevent(e)
logging.debug("%s - START event send to callbacks" % self.cfg.name)
def outmonitor(self, origin, channel, txt, event=None):
""" create an OUTPUT event with provided txt and send it to callbacks. """
if event: e = cpy(event)
else: e = EventBase()
#e = EventBase()
if e.status == "done":
logging.debug("%s - outmonitor - event is done .. ignoring" % self.cfg.name)
return
e.bot = self
e.origin = origin
e.ruserhost = self.cfg.name +'@' + self.uuid
e.userhost = e.ruserhost
e.auth = e.userhost
e.channel = channel
e.origtxt = txt
e.txt = txt
e.cbtype = 'OUTPUT'
e.botoutput = True
e.nodispatch = True
e.ttl = 1
e.nick = self.cfg.nick or self.cfg.name
e.bind(self)
first_callbacks.check(self, e)
def docmnd(self, origin, channel, txt, event=None, wait=0, showall=False, nooutput=False):
""" do a command. """
if event: e = cpy(event)
else: e = EventBase()
e.cbtype = "CMND"
e.bot = self
e.origin = origin
e.ruserhost = origin
e.auth = origin
e.userhost = origin
e.channel = channel
e.txt = unicode(txt)
e.nick = e.userhost.split('@')[0]
e.usercmnd = e.txt.split()[0]
#e.iscommand = True
#e.iscallback = False
e.allowqueues = True
e.onlyqueues = False
e.closequeue = True
e.showall = showall
e.nooutput = nooutput
e.bind(self)
#if wait: e.direct = True ; e.nothreads = True ; e.wait = wait
if cmnds.woulddispatch(self, e) or e.txt[0] == "?": return self.doevent(e)
#self.put(e)
#return e
def putevent(self, origin, channel, txt, event=None, wait=0, showall=False, nooutput=False):
""" insert an event into the callbacks chain. """
assert origin
if event: e = cpy(event)
else: e = EventBase()
e.cbtype = "CMND"
e.bot = self
e.origin = origin
e.ruserhost = origin
e.auth = origin
e.userhost = origin
e.channel = channel
e.txt = unicode(txt)
e.nick = e.userhost.split('@')[0]
e.usercmnd = e.txt.split()[0]
e.iscommand = False
#e.iscallback = False
e.allowqueues = True
e.onlyqueues = False
e.closequeue = True
e.showall = showall
e.nooutput = nooutput
e.wait = wait
e.bind(self)
self.put(e)
return e
def execstr(self, origin, channel, txt, event=None, wait=0, showall=False, nooutput=False):
e = self.putevent(origin, channel, txt, event, wait, showall, nooutput)
waitevents([e, ])
return e.result
def settopic(self, channel, txt):
pass
def gettopic(self, channel):
pass
| Python |
# jsb/exit.py
#
#
""" jsb's finaliser """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.utils.trace import whichmodule
from runner import defaultrunner, cmndrunner, callbackrunner, waitrunner
## basic imports
import atexit
import os
import time
import sys
import logging
## functions
def globalshutdown():
""" shutdown the bot. """
try:
logging.warn('shutting down'.upper())
sys.stdout.write("\n")
from fleet import getfleet
fleet = getfleet()
if fleet:
logging.warn('shutting down fleet')
fleet.exit()
logging.warn('shutting down plugins')
from jsb.lib.plugins import plugs
plugs.exit()
logging.warn("shutting down runners")
cmndrunner.stop()
callbackrunner.stop()
waitrunner.stop()
logging.warn('done')
try:os.remove('jsb.pid')
except: pass
os._exit(0)
except Exception, ex: handle_exception()
#try: import google
#except ImportError: atexit.register(globalshutdown)
| Python |
# jsb/gatekeeper.py
#
#
""" keep a whitelist of allowed entities based on userhost. """
## jsb imports
from jsb.lib.persist import Persist
from jsb.lib.datadir import getdatadir
## basic imports
import logging
import os
## GateKeeper class
class GateKeeper(Persist):
""" keep a whitelist of allowed entities based on userhost. """
def __init__(self, name):
self.name = name
try: import waveapi
except:
if not os.path.exists(getdatadir() + os.sep +'gatekeeper'): os.mkdir(getdatadir() + os.sep + 'gatekeeper')
Persist.__init__(self, getdatadir() + os.sep + 'gatekeeper' + os.sep + name)
self.data.whitelist = self.data.whitelist or []
def isblocked(self, userhost):
""" see if userhost is blocked. """
if not userhost: return False
userhost = userhost.lower()
if userhost in self.data.whitelist:
logging.debug("%s - allowed %s" % (self.fn, userhost))
return False
logging.warn("%s - denied %s" % (self.fn, userhost))
return True
def allow(self, userhost):
""" allow userhost. """
userhost = userhost.lower()
if not userhost in self.data.whitelist:
self.data.whitelist.append(userhost)
self.save()
def deny(self, userhost):
""" deny access. """
userhost = userhost.lower()
if userhost in self.data.whitelist: self.data.whitelist.remove(userhost)
| Python |
# jsb/outputcache.py
#
#
## jsb imports
from persist import Persist
from jsb.utils.name import stripname
from datadir import getdatadir
from jsb.utils.timeutils import hourmin
## basic imports
import os
import logging
import time
## clear function
def clear(target):
""" clear target's outputcache. """
cache = Persist(getdatadir() + os.sep + 'run' + os.sep + 'outputcache' + os.sep + stripname(target))
try:
cache.data['msg'] = []
cache.save()
except KeyError: pass
return []
## add function
def add(target, txtlist):
""" add list of txt to target entry. """
logging.warn("outputcache - adding %s lines" % len(txtlist))
t = []
for item in txtlist:
t.append("[%s] %s" % (hourmin(time.time()), item))
cache = Persist(getdatadir() + os.sep + 'run' + os.sep + 'outputcache' + os.sep + stripname(target))
d = cache.data
if not d.has_key('msg'): d['msg'] = []
d['msg'].extend(t)
while len(d['msg']) > 10: d['msg'].pop(0)
cache.save()
## set function
def set(target, txtlist):
""" set target entry to list. """
cache = Persist(getdatadir() + os.sep + 'run' + os.sep + 'outputcache' + os.sep + stripname(target))
if not cache.data.has_key('msg'): cache.data['msg'] = []
cache.data['msg'] = txtlist
cache.save()
## get function
def get(target):
""" get output for target. """
cache = Persist(getdatadir() + os.sep + 'run' + os.sep + 'outputcache' + os.sep + stripname(target))
try:
result = cache.data['msg']
if result: return result
except KeyError: pass
return []
| Python |
# jsb/tick.py
#
#
""" provide system wide clock tick. """
## jsb imports
from jsb.lib.threadloop import TimedLoop
from jsb.lib.eventbase import EventBase
from jsb.lib.callbacks import callbacks
## TickLoop class
class TickLoop(TimedLoop):
def start(self, bot=None):
""" start the loop. """
self.bot = bot
TimedLoop.start(self)
def handle(self):
""" send TICK events to callback. """
event = EventBase()
event.type = event.cbtype = 'TICK'
callbacks.check(self.bot, event)
## global tick loop
tickloop = TickLoop('tickloop', 60)
| Python |
# jsb/less.py
#
#
""" maintain bot output cache. """
# jsb imports
from jsb.utils.exception import handle_exception
from jsb.utils.limlist import Limlist
## google imports
try:
from google.appengine.api.memcache import get, set, delete
except ImportError:
from jsb.lib.cache import get, set, delete
## basic imports
import logging
## Less class
class Less(object):
""" output cache .. caches upto <nr> item of txt lines per channel. """
def clear(self, channel):
""" clear outcache of channel. """
channel = unicode(channel).lower()
try: delete(u"outcache-" + channel)
except KeyError: pass
def add(self, channel, listoftxt):
""" add listoftxt to channel's output. """
channel = unicode(channel).lower()
data = get("outcache-" + channel)
if not data: data = []
data.extend(listoftxt)
set(u"outcache-" + channel, data, 3600)
def set(self, channel, listoftxt):
""" set listoftxt to channel's output. """
channel = unicode(channel).lower()
set(u"outcache-" + channel, listoftxt, 3600)
def get(self, channel):
""" return 1 item popped from outcache. """
channel = unicode(channel).lower()
global get
data = get(u"outcache-" + channel)
if not data: txt = None
else:
try: txt = data.pop(0) ; set(u"outcache-" + channel, data, 3600)
except (KeyError, IndexError): txt = None
if data: size = len(data)
else: size = 0
return (txt, size)
def more(self, channel):
""" return more entry and remaining size. """
return self.get(channel)
outcache = Less() | Python |
# jsb/channelbase.py
#
#
""" provide a base class for channels. """
## jsb imports
from jsb.utils.name import stripname
from jsb.utils.lazydict import LazyDict
from jsb.lib.persist import Persist
from jsb.lib.datadir import getdatadir
from jsb.utils.trace import whichmodule
from jsb.lib.errors import NoChannelProvided, NoChannelSet
## basic imports
import time
import os
import logging
import uuid
## classes
class ChannelBase(Persist):
""" Base class for all channel objects. """
def __init__(self, id, botname=None, type="notset"):
if not id: raise NoChannelSet()
if not botname: Persist.__init__(self, getdatadir() + os.sep + 'channels' + os.sep + stripname(id))
else: Persist.__init__(self, getdatadir() + os.sep + 'fleet' + os.sep + stripname(botname) + os.sep + 'channels' + os.sep + stripname(id))
self.id = id
self.type = type
self.lastmodified = time.time()
self.data.id = id
self.data.enable = self.data.enable or False
self.data.silentcommands = self.data.silentcommands or []
self.data.allowcommands = self.data.allowcommands or []
self.data.feeds = self.data.feeds or []
self.data.forwards = self.data.forwards or []
self.data.allowwatch = self.data.allowwatch or []
self.data.watched = self.data.watched or []
self.data.passwords = self.data.passwords or {}
self.data.cc = self.data.cc or "!"
self.data.nick = self.data.nick or "jsb"
self.data.key = self.data.key or ""
self.data.denyplug = self.data.denyplug or []
self.data.createdfrom = whichmodule()
self.data.cacheindex = 0
self.data.tokens = self.data.tokens or []
self.data.webchannels = self.data.webchannels or []
logging.debug("channelbase - created channel %s" % id)
def setpass(self, type, key):
""" set channel password based on type. """
self.data.passwords[type] = key
self.save()
def getpass(self, type='IRC'):
""" get password based of type. """
try:
return self.data.passwords[type]
except KeyError: return
def delpass(self, type='IRC'):
""" delete password. """
try:
del self.data.passwords[type]
self.save()
return True
except KeyError: return
def parse(self, event, wavelet=None):
"""
parse an event for channel related data and constuct the
channel with it. Overload this.
"""
pass
def gae_create(self):
try: from google.appengine.api import channel
except ImportError: return (None, None)
webchan = self.id + "-" + str(time.time())
token = channel.create_channel(webchan)
if token and token not in self.data.tokens:
self.data.tokens.insert(0, token)
self.data.tokens = self.data.tokens[:10]
if webchan not in self.data.webchannels:
self.data.webchannels.insert(0, webchan)
self.data.webchannels = self.data.webchannels[:10]
self.save()
return (webchan, token)
| Python |
# jsb/plugins.py
#
#
""" holds all the plugins. plugins are imported modules. """
## jsb imports
from commands import cmnds
from callbacks import callbacks, remote_callbacks, first_callbacks, last_callbacks
from eventbase import EventBase
from persist import Persist
from jsb.utils.lazydict import LazyDict
from jsb.utils.exception import handle_exception
from boot import cmndtable, plugin_packages, default_plugins
from errors import NoSuchPlugin
from jsb.utils.locking import lockdec
from jsbimport import force_import, _import
from morphs import outputmorphs, inputmorphs
from wait import waiter
## basic imports
import os
import logging
import Queue
import copy
import sys
import thread
## defines
cpy = copy.deepcopy
## locks
loadlock = thread.allocate_lock()
locked = lockdec(loadlock)
## Plugins class
class Plugins(LazyDict):
""" the plugins object contains all the plugins. """
def exit(self):
for plugname in self:
self.unload(plugname)
def reloadfile(self, filename, force=True):
logging.warn("plugs - reloading file %s" % filename)
mlist = filename.split(os.sep)
mod = []
for m in mlist[::-1]:
mod.insert(0, m)
if m == "myplugs": break
modname = ".".join(mod)[:-3]
logging.warn("plugs - using %s" % modname)
self.reload(modname, force)
def loadall(self, paths=[], force=True):
"""
load all plugins from given paths, if force is true ..
otherwise load all plugins for default_plugins list.
"""
if not paths: paths = plugin_packages
imp = None
for module in paths:
try: imp = _import(module)
except ImportError, ex:
#handle_exception()
logging.warn("no %s plugin package found - %s" % (module, str(ex)))
continue
except Exception, ex: handle_exception()
logging.debug("got plugin package %s" % module)
try:
for plug in imp.__plugs__:
try: self.reload("%s.%s" % (module,plug), force=force, showerror=True)
except KeyError: logging.debug("failed to load plugin package %s" % module)
except Exception, ex: handle_exception()
except AttributeError: logging.error("no plugins in %s .. define __plugs__ in __init__.py" % module)
def unload(self, modname):
""" unload plugin .. remove related commands from cmnds object. """
logging.debug("plugins - unloading %s" % modname)
try:
self[modname].shutdown()
logging.debug('called %s shutdown' % modname)
except KeyError:
logging.debug("no %s module found" % modname)
return False
except AttributeError: pass
try: cmnds.unload(modname)
except KeyError: pass
try: first_callbacks.unload(modname)
except KeyError: pass
try: callbacks.unload(modname)
except KeyError: pass
try: last_callbacks.unload(modname)
except KeyError: pass
try: remote_callbacks.unload(modname)
except KeyError: pass
try: outputmorphs.unload(modname)
except: handle_exception()
try: inputmorphs.unload(modname)
except: handle_exception()
try: waiter.remove(modname)
except: handle_exception()
return True
def load(self, modname, force=False, showerror=True, loaded=[]):
""" load a plugin. """
if not modname: raise NoSuchPlugin(modname)
if not force and modname in loaded: logging.warn("skipping %s" % modname) ; return loaded
if self.has_key(modname):
try:
logging.debug("%s already loaded" % modname)
if not force: return self[modname]
self[modname] = reload(self[modname])
except Exception, ex: raise
else:
logging.debug("trying %s" % modname)
mod = _import(modname)
if not mod: return None
try: self[modname] = mod
except KeyError:
logging.info("failed to load %s" % modname)
raise NoSuchPlugin(modname)
try: init = getattr(self[modname], 'init')
except AttributeError:
logging.warn("%s loaded" % modname)
return self[modname]
try:
init()
logging.debug('%s init called' % modname)
except Exception, ex: raise
logging.warn("%s loaded" % modname)
return self[modname]
def loaddeps(self, modname, force=False, showerror=False, loaded=[]):
try:
deps = self[modname].__depending__
if deps: logging.warn("dependcies detected: %s" % deps)
except (KeyError, AttributeError): deps = []
deps.insert(0, modname)
for dep in deps:
if dep not in loaded:
if self.has_key(dep): self.unload(dep)
try:
self.load(dep, force, showerror, loaded)
loaded.append(dep)
except Exception, ex: handle_exception()
return loaded
def reload(self, modname, force=False, showerror=False):
""" reload a plugin. just load for now. """
modname = modname.replace("..", ".")
if self.has_key(modname): self.unload(modname)
return self.loaddeps(modname, force, showerror, [])
def dispatch(self, bot, event, wait=0, *args, **kwargs):
""" dispatch event onto the cmnds object. check for pipelines first. """
result = []
if not event.pipelined and ' ! ' in event.txt: return self.pipelined(bot, event, wait=wait, *args, **kwargs)
self.reloadcheck(bot, event)
return cmnds.dispatch(bot, event, wait=wait, *args, **kwargs)
def pipelined(self, bot, event, wait=0, *args, **kwargs):
""" split cmnds, create events for them, chain the queues and dispatch. """
origqueues = event.queues
event.queues = []
event.allowqueue = True
event.closequeue = True
event.pipelined = True
events = []
splitted = event.txt.split(" ! ")
for item in splitted:
e = cpy(event)
e.queues = []
e.onlyqueues = True
e.dontclose = True
e.txt = item.strip()
e.usercmnd = e.txt.split()[0].lower()
if not cmnds.woulddispatch(bot, e): events.append(event) ; break
logging.debug('creating event for %s' % e.txt)
e.bot = bot
e.makeargs()
events.append(e)
prevq = None
for e in events[:-1]:
q = Queue.Queue()
e.queues.append(q)
if prevq:
e.inqueue = prevq
prevq = q
lq = events[-1]
lq.inqueue = prevq
lq.closequeue = True
lq.dontclose = False
if origqueues: lq.queues = origqueues
for e in events: self.dispatch(bot, e, wait=wait)
return lq
def reloadcheck(self, bot, event, target=None):
"""
check if event requires a plugin to be reloaded. if so
reload the plugin.
"""
logging.debug("checking for reload of %s (%s)" % (event.usercmnd, event.userhost))
plugloaded = None
try:
from boot import getcmndtable
plugin = getcmndtable()[target or event.usercmnd.lower()]
except KeyError:
logging.debug("can't find plugin to reload for %s" % event.usercmnd)
return
if plugin in self: logging.debug(" %s already loaded" % plugin) ; return plugloaded
if plugin in default_plugins: pass
elif bot.cfg.blacklist and plugin in bot.cfg.blacklist: return plugloaded
elif bot.cfg.loadlist and plugin not in bot.cfg.loadlist: return plugloaded
logging.info("loaded %s on demand (%s)" % (plugin, event.usercmnd))
plugloaded = self.reload(plugin)
return plugloaded
def getmodule(self, plugname):
for module in plugin_packages:
try: imp = _import(module)
except ImportError, ex:
if "No module" in str(ex):
logging.info("no %s plugin package found" % module)
continue
raise
except Exception, ex: handle_exception() ; continue
if plugname in imp.__plugs__: return "%s.%s" % (module, plugname)
## global plugins object
plugs = Plugins()
| Python |
# jsb/eventbase.py
#
#
""" base class of all events. """
## jsb imports
from channelbase import ChannelBase
from jsb.utils.lazydict import LazyDict
from jsb.utils.generic import splittxt, stripped, waitforqueue
from errors import NoSuchUser
from jsb.utils.opts import makeeventopts
from jsb.utils.trace import whichmodule
from jsb.utils.exception import handle_exception
from jsb.utils.locking import lockdec
from jsb.lib.config import Config
## basic imports
from xml.sax.saxutils import unescape
import copy
import logging
import Queue
import types
import socket
import threading
import time
import thread
## defines
cpy = copy.deepcopy
lock = thread.allocate_lock()
locked = lockdec(lock)
## classes
class EventBase(LazyDict):
""" basic event class. """
def __init__(self, input={}, bot=None):
LazyDict.__init__(self)
if bot: self.bot = bot
self.txt = ""
self.bottype = "botbase"
self.relayed = []
self.path = []
self.cbs = []
self.result = []
self.threads = self.threads or []
self.queues = self.queues or []
self.finished = self.finished or threading.Event()
self.resqueue = self.resqueue or Queue.Queue()
self.inqueue = self.inqueue or Queue.Queue()
self.outqueue = self.outqueue or Queue.Queue()
self.stop = False
self.bonded = False
self.copyin(input)
def __deepcopy__(self, a):
""" deepcopy an event. """
logging.debug("eventbase - cpy - %s" % type(self))
e = EventBase(self)
return e
def ready(self, finish=True):
""" signal the event as ready - push None to all queues. """
logging.debug("%s - %s - ready called from %s" % (self.cbtype, self.txt, whichmodule()))
time.sleep(0.01)
if self.closequeue and self.queues:
for q in self.queues:
q.put_nowait(None)
if not self.dontclose:
self.outqueue.put_nowait(None)
self.resqueue.put_nowait(None)
self.inqueue.put_nowait(None)
for cb in self.cbs:
try: cb(self.result)
except Exception, ex: handle_exception()
if finish: self.finished.set()
#self.stop = True
def prepare(self, bot=None):
""" prepare the event for dispatch. """
if bot: self.bot = bot
assert(self.bot)
self.origin = self.channel
self.origtxt = self.txt
self.makeargs()
logging.debug("%s - prepared event - %s" % (self.auth, self.cbtype))
def bind(self, bot=None, user=None, chan=None):
""" bind event.bot event.user and event.chan to execute a command on it. """
target = self.auth
bot = bot or self.bot
if not self.chan:
if chan: self.chan = chan
elif self.channel: self.chan = ChannelBase(self.channel, bot.cfg.name)
elif self.userhost: self.chan = ChannelBase(self.userhost, bot.cfg.name)
logging.debug("eventbase - binding channel - %s" % str(self.chan))
if not target: self.prepare(bot) ; self.bonded = True ; return
if not self.user and target:
cfg = Config()
if cfg.auto_register:
bot.users.addguest(target)
self.user = user or bot.users.getuser(target)
logging.debug("eventbase - binding user - %s - from %s" % (str(self.user), whichmodule()))
if not self.user and target: logging.info("eventbase - no %s user found .. setting nodispatch" % target) ; self.nodispatch = True
self.prepare(bot)
self.bonded = True
return self
def parse(self, event, *args, **kwargs):
""" overload this. """
self.bot = event.bot
self.origin = event.origin
self.ruserhost = self.origin
self.userhost = self.origin
self.channel = event.channel
self.auth = stripped(self.userhost)
def waitfor(self, cb):
""" wait for the event to finish. """
logging.warn("eventbase - waiting for %s" % self.txt)
#self.finished.wait(5)
self.cbs.append(cb)
return True
def copyin(self, eventin):
""" copy in an event. """
self.update(eventin)
try: self.path = eventin.path
except: pass
self.threads = self.threads or []
self.queues = self.queues or []
self.finished = self.finished or threading.Event()
self.resqueue = self.resqueue or Queue.Queue()
self.inqueue = self.inqueue or Queue.Queue()
self.outqueue = self.outqueue or Queue.Queue()
return self
@locked
def reply(self, txt, result=[], event=None, origin="", dot=u", ", nr=375, extend=0, *args, **kwargs):
""" reply to this event """
try: target = self.channel or self.arguments[1]
except IndexError: target = self.channel
if self.checkqueues(result): return self
if self.silent:
self.msg = True
self.bot.say(self.nick, txt, result, self.userhost, extend=extend, event=self, dot=dot, *args, **kwargs)
elif self.isdcc: self.bot.say(self.sock, txt, result, self.userhost, extend=extend, event=self, dot=dot, *args, **kwargs)
else: self.bot.say(target, txt, result, self.userhost, extend=extend, event=self, dot=dot, *args, **kwargs)
return self
def missing(self, txt):
""" display missing arguments. """
self.reply("%s %s" % (self.usercmnd, txt), event=self)
return self
def done(self):
""" tell the user we are done. """
self.reply('<b>done</b> - %s' % self.txt, event=self)
return self
def leave(self):
""" lower the time to leave. """
self.ttl -= 1
if self.ttl <= 0 : self.status = "done"
logging.info("======== STOP handling event ========")
def makeoptions(self):
""" check the given txt for options. """
try: self.options = makeeventopts(self.txt)
except: return
if not self.options: return
logging.debug("eventbase - options - %s" % unicode(self.options))
self.txt = ' '.join(self.options.args)
self.makeargs()
def makeargs(self):
""" make arguments and rest attributes from self.txt. """
if not self.txt:
self.args = []
self.rest = ""
else:
args = self.txt.split()
self.chantag = args[0]
if len(args) > 1:
self.args = args[1:]
self.rest = ' '.join(self.args)
else:
self.args = []
self.rest = ""
def checkqueues(self, resultlist):
""" check if resultlist is to be sent to the queues. if so do it. """
if self.queues:
for queue in self.queues:
for item in resultlist:
if item: queue.put_nowait(item)
for item in resultlist:
if item: self.outqueue.put_nowait(item)
return True
return False
def makeresponse(self, txt, result, dot=u", ", *args, **kwargs):
""" create a response from a string and result list. """
return self.bot.makeresponse(txt, result, dot, *args, **kwargs)
def less(self, what, nr=365):
""" split up in parts of <nr> chars overflowing on word boundaries. """
return self.bot.less(what, nr)
def isremote(self):
""" check whether the event is off remote origin. """
if self.txt: return self.txt.startswith('{"') or self.txt.startswith("{&")
def iscmnd(self):
""" check if event is a command. """
if not self.txt: logging.debug("eventbase - no txt set.") ; return
if self.iscommand: return self.txt
if self.isremote(): logging.info("eventbase - event is remote") ; return
logging.debug("eventbase - trying to match %s" % self.txt)
cc = "!"
if not self.chan: logging.warn("eventbase - channel is not set.") ; return False
cc = self.chan.data.cc
if not cc: self.chan.data.cc = "!" ; self.chan.save()
if not cc: cc = "!"
if self.type == "DISPATCH": cc += "!"
if not self.bot: logging.warn("eventbase - bot is not bind into event.") ; return False
logging.debug("eventbase - cc for %s is %s (%s)" % (self.title or self.channel or self.userhost, cc, self.bot.cfg.nick))
if self.txt[0] in cc: return self.txt[1:]
matchnick = unicode(self.bot.cfg.nick + u":")
if self.txt.startswith(matchnick): return self.txt[len(matchnick):]
return False
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.