Example #1
0
 def __init__(self, botname=None, i=0, nick="", ttime=time.time(), txt="", printto=None, d={}):
     if not d: LazyDict.__init__(self)
     else:
         assert(type(d) == dict)
         LazyDict.__init__(self, d)
     if not self.botname: self.botname = botname or "default-irc"
     self.idnr = self.idnr or i
     self.nick = self.nick or nick
     self.time = self.ttime or ttime
     self.txt = self.txt or txt
     self.printto = self.printto or printto or nick or ""
Example #2
0
 def __init__(self, input={}, bot=None, parsetxt=None):
     LazyDict.__init__(self)
     if bot: self.bot = bot
     self.ctime = time.time()
     self.speed = 5
     self.nrout = 0
     self.nodispatch = True
     self.isready = threading.Event()
     self.dontbind = self.bot and self.bot.cfg and self.bot.cfg.strict or False
     if parsetxt: self.parse(parsetxt)
     if input: self.copyin(input)
     if not self.token: self.setup()
Example #3
0
def sync():
    target = ";".join(state.data.watch)
    if not target: logging.warn("no channels started yet") ; return
    res = gettimeline(target)
    if not res: logging.warn("no result from %s" % id) ; return
    todo = []
    for r in res:
        a = LazyDict(r)
        logging.debug("got %s" % a.tojson())
        if a.creation_date not in state.data.seen: state.data.seen.insert(0, a.creation_date) ; todo.append(a)
        #todo.append(a)
    state.data.seen = state.data.seen[:100]
    state.save()
    logging.info("returned %s items" % len(todo))
    return todo
Example #4
0
 def __init__(self, filename, verbose=False, input={}, ddir=None, nolog=False, *args, **kwargs):
     assert filename
     if ddir: ddir = normdir(ddir)
     if input: LazyDict.__init__(self, input, *args, **kwargs)
     else: LazyDict.__init__(self, *args, **kwargs)
     self.filename = filename
     self.setcfile(ddir, filename)
     if not self._comments: self._comments = {}
     logging.info("%s from %s" % (self._logname, whichmodule(2)))
     self.fromfile(self._cfile)
     self.cid = get_cid(self)
     self.init()
     if self.owner: logging.info("owner is %s" % self.owner)
     if "uuid" not in self: self.setuuid()
     if not self._origdir in self._cfile: raise WrongFileName("%s not in %s" % (self._origdir, self._cfile))
Example #5
0
 def __init__(self, modname, cmnd, func, perms=[], threaded=False, wait=False, orig=None, how=None, speed=None):
     LazyDict.__init__(self)
     if not modname: raise Exception("modname is not set - %s" % cmnd)
     self.modname = cpy(modname)
     self.plugname = self.modname.split('.')[-1]
     self.cmnd = cpy(cmnd)
     self.orig = cpy(orig)
     self.func = func
     if type(perms) == bytes: perms = [perms, ]
     self.perms = cpy(perms)
     self.plugin = self.plugname
     self.threaded = cpy(threaded)
     self.wait = cpy(wait)
     self.enable = True
     self.how = how or "overwrite"
     self.regex = None
     self.speed = speed
Example #6
0
def saveplugins(modname=None):
    """ save a list of available plugins to db backend. """
    global plugins
    if modname: target = LazyDict(plugins.data)
    else: target = LazyDict()
    if not target.available: target.available = []
    if not target.allowed: target.allowed = []
    if not target.refused: target.refused = []
    from tl.lib.commands import cmnds
    assert cmnds
    for cmndname, c in cmnds.items():
        if modname and c.modname != modname: continue
        if c and not c.plugname: logging.info("boot - not adding %s to pluginlist" % cmndname) ; continue
        if c and c.enable: target.available.append(c.plugname)
    assert target
    logging.warn("saving plugin list")
    assert plugins
    plugins.data = target
    plugins.save()
Example #7
0
def formatevent(bot, ievent, channels, forwarded=False):
    m = {
        'datetime': datetime.now(),
        'separator': format_opt('separator'),
        'event_prefix': format_opt('event_prefix'),
        'network': bot.cfg.networkname,
        'nick': ievent.nick,
        'target': stripname(ievent.channel),
        'botname': bot.cfg.name,
        'txt': ievent.txt,
        'type': ievent.cbtype
    }
    m = LazyDict(m)
    if ievent.cmnd == 'PRIVMSG':
        if ievent.txt.startswith('\001ACTION'): m.txt = '* %s %s' % (m.nick, ievent.txt[7:-1].strip())
        else:
             if bot.type == "irc": m.txt = '<%s> %s' % (m.nick, striphtml(ievent.txt))
             elif not forwarded: m.txt = '<%s> %s' % (m.nick, bot.normalize(ievent.txt))
             else: m.txt = bot.normalize(ievent.txt)
    elif ievent.cmnd == 'NOTICE':
            m.target = ievent.arguments[0]
            m.txt = "-%s- %s"%(ievent.nick, ievent.txt)
    elif ievent.cmnd == 'TOPIC': m.txt = '%s changes topic to "%s"'%(ievent.nick, ievent.txt)
    elif ievent.cmnd == 'MODE':
        margs = ' '.join(ievent.arguments[1:])
        m.txt = '%s sets mode: %s'% (ievent.nick, margs)
    elif ievent.cmnd == 'JOIN': m.txt = '%s (%s) has joined %s'%(ievent.nick, ievent.userhost, ievent.channel)
    elif ievent.cmnd == 'KICK': m.txt = '%s was kicked by %s (%s)'% (ievent.arguments[1], ievent.nick, ievent.txt)
    elif ievent.cmnd == 'PART': m.txt = '%s (%s) has left %s'% (ievent.nick, ievent.userhost, ievent.channel)
    elif ievent.cmnd in ('QUIT', 'NICK'):
        if not ievent.user or not ievent.user.data.channels:
            logging.debug("chatlog - can't find joined channels for %s" % ievent.userhost)
            return m
        cmd = ievent.cmnd
        nick = cmd == 'NICK' and ievent.txt or ievent.nick
        for c in event.user.channels:
            if [bot.cfg.name, c] in channels:
                if True:
                    if cmd == 'NICK': m.txt = '%s (%s) is now known as %s'% (ievent.nick, ievent.userhost, ievent.txt)
                    else: m.txt= '%s (%s) has quit: %s'% (ievent.nick, ievent.userhost, ievent.txt)
                    m.type = ievent.cmnd.lower()
                    m.target = c
    elif ievent.cbtype == 'PRESENCE':
            if ievent.type == 'unavailable': m.txt = "%s left" % ievent.nick
            else: m.txt = "%s joined" % ievent.nick
    elif ievent.cbtype == "MESSAGE": m.txt = "<%s> %s" % (m.nick, ievent.txt)
    elif ievent.cbtype == "OUTPUT": m.txt = "<%s> %s" % (bot.cfg.nick, ievent.txt)
    return m
Example #8
0
 def __init__(self, cfg=None, usersin=None, plugs=None, botname=None, nick=None, bottype=None, ordered=False, *args, **kwargs):
     logging.debug("type is %s" % str(type(self)))
     if cfg: self.cfg = cfg ; botname = botname or self.cfg.name
     if not botname: botname = "default-%s" % str(type(self)).split('.')[-1][:-2]
     if not botname: raise Exception("can't determine  botname")
     self.fleetdir = 'fleet' + os.sep + stripname(botname)
     if not self.cfg: self.cfg = Config(self.fleetdir + os.sep + 'config')
     self.cfg.name = botname or self.cfg.name
     if not self.cfg.name: raise Exception("name is not set in %s config file" % self.fleetdir)
     logging.debug("name is %s" % self.cfg.name)
     LazyDict.__init__(self)
     self.bid = get_bid(self)
     logging.warn("created bot on %s" % self.bid)
     logging.debug("created bot with config %s" % self.cfg.tojson(full=True))
     self.ecounter = 0
     self.ignore = []
     self.ids = []
     self.stats = StatDict()
     logging.warn("stats dict set to %s" % str(self.stats))
     self.aliases = getaliases()
     self.reconnectcount = 0
     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.starttime = time.time()
     self.type = bottype or "base"
     self.status = "init"
     self.networkname = self.cfg.networkname or self.cfg.name or ""
     from tl.lib.datadir import getdatadir
     datadir = getdatadir()
     self.datadir = datadir + os.sep + self.fleetdir
     self.maincfg = getmainconfig()
     if not self.cfg.owner:
         logging.debug("owner is not set in %s - using mainconfig" % self.cfg.cfile)
         self.cfg.owner = self.maincfg.owner
     self.users = usersin or getusers()
     logging.debug("owner is %s" % self.cfg.owner)
     self.users.make_owner(self.cfg.owner)
     self.outcache = outcache
     self.userhosts = LazyDict()
     self.nicks = LazyDict()
     self.connectok = threading.Event()
     self.reconnectcount = 0
     self.cfg.nick = nick or self.cfg.nick or 'tl'
     try:
         if not os.isdir(self.datadir): os.mkdir(self.datadir)
     except: pass
     self.setstate()
     self.outputlock = _thread.allocate_lock()
     if ordered:
         self.outqueue = queue.PriorityQueue()
         self.eventqueue = queue.PriorityQueue()
     else:
         self.outqueue = queue.Queue()
         self.eventqueue = queue.Queue()
     logging.debug("event queues is %s" % str(self.eventqueue))
     self.encoding = self.cfg.encoding or "utf-8"
     self.cmndperms = getcmndperms()
     self.outputmorphs = outputmorphs
     self.inputmorphs = inputmorphs
     tickloop.start(self)
Example #9
0
 def __getitem__(self, item):
     """ accessor function. """
     if item not in self: return None
     else: return LazyDict.__getitem__(self, item)
Example #10
0
 def set(self, item, value):
     """ set item to value. """
     LazyDict.__setitem__(self, item, value)
Example #11
0
 def status(self, filter=None):
     res = LazyDict()
     for runner in self.runners: res[runner.name] = runner.status(filter)
     return res.tojson()
Example #12
0
# tl/__init__.py
#
#

""" get/set globals. """

import tl.path
from tl.utils.lazydict import LazyDict

altar = LazyDict()
altar.errors = LazyDict()
altar.testerrors = LazyDict()

def setglobal(name, object):
    global altar
    altar[name] = object

def getglobal(name):
    try: return altar[name]
    except KeyError: return 
Example #13
0
 def __init__(self, *args, **kwargs):
     LazyDict.__init__(self, *args, **kwargs)
     self.__wait = threading.Event()