コード例 #1
0
ファイル: botbase.py プロジェクト: buzzworkers/Jsonbot
 def __init__(self, cfg=None, usersin=None, plugs=None, botname=None, nick=None, bottype=None, nocbs=None, *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 = u"default-%s" % str(type(self)).split('.')[-1][:-2]
     if not botname: raise Exception("can't determine  botname")
     self.fleetdir = u'fleet' + os.sep + stripname(botname)
     if not self.cfg: self.cfg = Config(self.fleetdir + os.sep + u'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)
     logging.debug("created bot with config %s" % self.cfg.tojson(full=True))
     self.ecounter = 0
     self.ids = []
     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 jsb.lib.datadir import getdatadir
     datadir = getdatadir()
     self.datadir = datadir + os.sep + self.fleetdir
     self.maincfg = getmainconfig()
     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 = self.maincfg.owner
     self.users = usersin or getusers()
     logging.debug(u"owner is %s" % self.owner)
     self.users.make_owner(self.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 u'jsb'
     try:
         if not os.isdir(self.datadir): os.mkdir(self.datadir)
     except: pass
     self.setstate()
     self.outputlock = thread.allocate_lock()
     try:
         self.outqueue = Queue.PriorityQueue()
         self.eventqueue = Queue.PriorityQueue()
     except AttributeError:
         self.outqueue = Queue.Queue()
         self.eventqueue = Queue.Queue()
     self.laterqueue = Queue.Queue()
     self.encoding = self.cfg.encoding or "utf-8"
     self.cmndperms = getcmndperms()
     self.outputmorphs = outputmorphs
     self.inputmorphs = inputmorphs
     try:
         if nocbs: self.nocbs = nocbs.split(",")
     except ValueError: logging.error("cannot determine %s nocbs argument" % self.nocbs)
     self.lastiter = 0
コード例 #2
0
ファイル: commands.py プロジェクト: NURDspace/jsonbot
    def reloadcheck(self, bot, event, target=None):
        """
            check if event requires a plugin to be reloaded. if so 
            reload the plugin.  

        """
        from boot import getcmndtable
        from boot import plugblacklist
        plugloaded = None
        plugin = None
        try:
            if not target:
                target = event.iscmnd().split()[0]
                if not target: target = evemt.txt.split()[0]
        except Exception, ex: target = None
        if not target: logging.debug("can't find target in %s" % event.txt) ; return
        from jsb.lib.aliases import getaliases
        aliases = getaliases()
        try: target = aliases[target]
        except KeyError:
            try: target = event.chan.data.aliases[target]
            except (AttributeError, KeyError, TypeError): pass
        cmndtable = getcmndtable()
        if not cmndtable.has_key(target):
            try:
                short = getshorttable()
                if short.has_key(target):
                    cmndlist = short[target]
                    if len(cmndlist) == 1: target = cmndlist[0]
            except Exception, ex: handle_exception()
        if target: target = target.split()[0]
        logging.info("checking for reload of %s" % target)
        try:
            plugin = cmndtable[target]
        except KeyError:
            logging.warn("no cmnd for %s .. trying REGEX" % target)
            try:
                retable = getretable()
                for regex, mod in retable.iteritems():
                    if re.search(regex, event.stripcc() or event.txt): plugin = mod ; break
            except Exception, ex: handle_exception()
        logging.info("plugin is %s" % plugin)
        if not plugin: logging.debug("can't find plugin to reload for %s" % target) ; return
        if plugin in bot.plugs: logging.info("%s already loaded" % plugin) ; return plugloaded
        elif plugin in plugblacklist.data: return plugloaded
        elif bot.cfg.loadlist and plugin not in bot.cfg.loadlist: logging.warn("plugin %s is blacklisted" % plugin) ; return plugloaded
        logging.info("loaded %s on demand" % plugin)
        plugloaded = bot.plugs.reload(plugin)
        return plugloaded
コード例 #3
0
ファイル: commands.py プロジェクト: NURDspace/jsonbot
    def woulddispatch(self, bot, event):
        """ 
            dispatch an event if cmnd exists and user is allowed to exec this 
            command.

        """
        event.bind(bot)
        aliased = False
        try:
            cmnd = event.stripcc().split()[0]
            if not cmnd: cmnd = event.execstr.split()[0]
            if not cmnd: cmnd = event.txt.split()[0]
        except Exception, ex: logging.warn("can't determine command from %s" % event.txt) ; return None
        try:
            a = event.chan.data.aliases[cmnd]
            if a: cmnd = a.split()[0] ; aliased = True
        except (KeyError, TypeError):
            try:
                a = getaliases()[cmnd]
                if a: cmnd = a.split()[0] ; aliased = True
            except (KeyError, TypeError): 
                if not self.has_key(cmnd):
                    try:
                        short = getshorttable()
                        if short.has_key(cmnd):
                            cmndlist = short[cmnd]
                            if len(cmndlist) == 1: cmnd = cmndlist[0]
                            else: event.reply("choose one of: ", cmndlist) ; return
                    except Exception, ex: handle_exception()
        logging.info("trying for %s" % cmnd)
        result = None
        try:
            result = self[cmnd]
        except KeyError: pass
        logging.debug("woulddispatch result: %s" % result)
        if result: event.bloh() ; event.makeargs()
        if aliased: event.usercmnd = cmnd
        return result
コード例 #4
0
ファイル: commands.py プロジェクト: Petraea/jsonbot
class Commands(LazyDict):
    """
        the commands object holds all commands of the bot.
 
    """

    regex = []

    def add(self,
            cmnd,
            func,
            perms,
            threaded=False,
            wait=False,
            orig=None,
            how=None,
            speed=None,
            regex=False,
            needcc=False,
            *args,
            **kwargs):
        """ add a command. """
        modname = calledfrom(sys._getframe())
        try:
            prev = self[cmnd]
        except KeyError:
            prev = None
        target = Command(modname,
                         cmnd,
                         func,
                         perms,
                         threaded,
                         wait,
                         orig,
                         how,
                         speed=speed,
                         needcc=needcc)
        if regex:
            logging.info("regex command detected - %s" % cmnd)
            self.regex.append(target)
            target.regex = cmnd
            return self
        self[cmnd] = target
        try:
            p = cmnd.split('-')[0]
            if not self.pre: self.pre = LazyDict()
            if self.pre.has_key(p):
                if not self.pre[p]: self.pre[p] = []
                if prev in self.pre[p]: self.pre[p].remove(prev)
                if target not in self.pre[p]: self.pre[p].append(target)
            else: self.pre[p] = [
                target,
            ]
        except IndexError:
            pass
        return self

    def checkre(self, bot, event):
        gotcc = event.gotcc()
        for r in self.regex:
            if not r.enable: continue
            if r.needcc and not event.gotcc():
                logging.debug("RE needs cc but not found")
                continue
            s = re.search(r.cmnd, event.txt)
            if s:
                logging.info("regex matches %s" % r.cmnd)
                event.groups = list(s.groups())
                return r

    def wouldmatchre(self, bot, event, cmnd=""):
        groups = self.checkre(bot, event)
        if groups: return groups

    def woulddispatch(self, bot, event):
        """ 
            dispatch an event if cmnd exists and user is allowed to exec this 
            command.

        """
        event.bind(bot)
        aliased = False
        try:
            cmnd = event.stripcc().split()[0]
            if not cmnd: cmnd = event.execstr.split()[0]
            if not cmnd: cmnd = event.txt.split()[0]
        except Exception, ex:
            logging.warn("can't determine command from %s" % event.txt)
            return None
        try:
            a = event.chan.data.aliases[cmnd]
            if a:
                cmnd = a.split()[0]
                aliased = True
        except (KeyError, TypeError):
            try:
                a = getaliases()[cmnd]
                if a:
                    cmnd = a.split()[0]
                    aliased = True
            except (KeyError, TypeError):
                if not self.has_key(cmnd):
                    try:
                        short = getshorttable()
                        if short.has_key(cmnd):
                            cmndlist = short[cmnd]
                            if len(cmndlist) == 1: cmnd = cmndlist[0]
                            else:
                                event.reply("choose one of: ", cmndlist)
                                return
                    except Exception, ex:
                        handle_exception()
コード例 #5
0
ファイル: commands.py プロジェクト: Petraea/jsonbot
 """
 from boot import getcmndtable
 from boot import plugblacklist
 plugloaded = None
 plugin = None
 try:
     if not target:
         target = event.iscmnd().split()[0]
         if not target: target = evemt.txt.split()[0]
 except Exception, ex:
     target = None
 if not target:
     logging.debug("can't find target in %s" % event.txt)
     return
 from jsb.lib.aliases import getaliases
 aliases = getaliases()
 try:
     target = aliases[target]
 except KeyError:
     try:
         target = event.chan.data.aliases[target]
     except (AttributeError, KeyError, TypeError):
         pass
 cmndtable = getcmndtable()
 if not cmndtable.has_key(target):
     try:
         short = getshorttable()
         if short.has_key(target):
             cmndlist = short[target]
             if len(cmndlist) == 1: target = cmndlist[0]
     except Exception, ex:
コード例 #6
0
 def __init__(self,
              cfg=None,
              usersin=None,
              plugs=None,
              botname=None,
              nick=None,
              bottype=None,
              nocbs=None,
              *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 = u"default-%s" % str(type(self)).split('.')[-1][:-2]
     if not botname: raise Exception("can't determine  botname")
     self.fleetdir = u'fleet' + os.sep + stripname(botname)
     if not self.cfg: self.cfg = Config(self.fleetdir + os.sep + u'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)
     logging.debug("created bot with config %s" %
                   self.cfg.tojson(full=True))
     self.ecounter = 0
     self.ids = []
     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 jsb.lib.datadir import getdatadir
     datadir = getdatadir()
     self.datadir = datadir + os.sep + self.fleetdir
     self.maincfg = getmainconfig()
     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 = self.maincfg.owner
     self.users = usersin or getusers()
     logging.debug(u"owner is %s" % self.owner)
     self.users.make_owner(self.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 u'jsb'
     try:
         if not os.isdir(self.datadir): os.mkdir(self.datadir)
     except:
         pass
     self.setstate()
     self.outputlock = thread.allocate_lock()
     try:
         self.outqueue = Queue.PriorityQueue()
         self.eventqueue = Queue.PriorityQueue()
     except AttributeError:
         self.outqueue = Queue.Queue()
         self.eventqueue = Queue.Queue()
     self.laterqueue = Queue.Queue()
     self.encoding = self.cfg.encoding or "utf-8"
     self.cmndperms = getcmndperms()
     self.outputmorphs = outputmorphs
     self.inputmorphs = inputmorphs
     try:
         if nocbs: self.nocbs = nocbs.split(",")
     except ValueError:
         logging.error("cannot determine %s nocbs argument" % self.nocbs)
     self.lastiter = 0
コード例 #7
0
ファイル: botbase.py プロジェクト: code2u/jsb
 def __init__(self, cfg=None, usersin=None, plugs=None, botname=None, nick=None, *args, **kwargs):
     logging.debug("type is %s" % str(type(self)))
     if cfg: cfg = LazyDict(cfg)
     if cfg and not botname: botname = 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(" name is not set in %s config file" % self.fleetdir)
     logging.debug("name is %s" % self.cfg.name)
     LazyDict.__init__(self)
     self.ignore = []
     self.ids = []
     self.started = False
     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("bot is a GAE bot (%s)" % self.cfg.name)
     except ImportError:
         self.isgae = False
         logging.debug("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 = getmainconfig().owner
     self.setusers(usersin)
     logging.debug(u"owner is %s" % self.owner)
     self.users.make_owner(self.owner)
     self.outcache = outcache
     self.userhosts = LazyDict()
     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
     if not self.isgae:
         defaultrunner.start()
         callbackrunner.start()
         waitrunner.start()
         tickloop.start(self)
コード例 #8
0
 def __init__(self,
              cfg=None,
              usersin=None,
              plugs=None,
              botname=None,
              nick=None,
              *args,
              **kwargs):
     if not botname and cfg and cfg.botname: botname = cfg.botname
     if botname: self.botname = botname
     else:
         self.botname = u"default-%s" % str(type(self)).split('.')[-1][:-2]
     logging.info("botbase - name is %s" % self.botname)
     self.fleetdir = u'fleet' + os.sep + stripname(self.botname)
     if cfg:
         self.cfg = Config(self.fleetdir + os.sep + u'config', input=cfg)
     else:
         self.cfg = Config(self.fleetdir + os.sep + u'config')
     LazyDict.__init__(self)
     self.update(self.cfg)
     self.ignore = []
     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.botname)
     self.gatekeeper.allow(self.user or self.jid or self.server
                           or self.botname)
     self.closed = False
     try:
         import waveapi
         self.isgae = True
         logging.debug("botbase - bot is a GAE bot (%s)" % self.botname)
     except ImportError:
         self.isgae = False
         logging.debug("botbase - bot is a shell bot (%s)" % self.botname)
     self.starttime = time.time()
     self.type = "base"
     self.status = "init"
     self.networkname = self.cfg.networkname or self.botname 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.name = self.botname
     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()
     if not self.nick: self.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.name): fleet.bots.append(self)
     if not self.isgae:
         defaultrunner.start()
         tickloop.start(self)