示例#1
0
def identify_object(inp):
    """
    Helper function. Identifies if an object is an account or an object;
    return its database model

    Args:
        inp (any): Entity to be idtified.

    Returns:
        identified (tuple): This is a tuple with (`inp`, identifier)
            where `identifier` is one of "account", "object", "channel",
            "string", "dbref" or None.

    """
    if hasattr(inp, "__dbclass__"):
        clsname = inp.__dbclass__.__name__
        if clsname == "AccountDB":
            return inp, "account"
        elif clsname == "ObjectDB":
            return inp, "object"
        elif clsname == "ChannelDB":
            return inp, "channel"
    if isinstance(inp, str):
        return inp, "string"
    elif dbref(inp):
        return dbref(inp), "dbref"
    else:
        return inp, None
示例#2
0
文件: comms.py 项目: jontsai/evennia
    def func(self):
        """Handles the functioning of the command."""

        if not self.args:
            self.msg(_list_bots(self))
            return
        # should always be on the form botname option
        args = self.args.split()
        if len(args) != 2:
            self.msg("Usage: ircstatus [#dbref ping||nicklist||reconnect]")
            return
        botname, option = args
        if option not in ("ping", "users", "reconnect", "nicklist", "who"):
            self.msg("Not a valid option.")
            return
        matches = None
        if utils.dbref(botname):
            matches = AccountDB.objects.filter(db_is_bot=True,
                                               id=utils.dbref(botname))
        if not matches:
            self.msg(
                "No matching IRC-bot found. Use ircstatus without arguments to list active bots."
            )
            return
        ircbot = matches[0]
        channel = ircbot.db.irc_channel
        network = ircbot.db.irc_network
        port = ircbot.db.irc_port
        chtext = "IRC bot '%s' on channel %s (%s:%s)" % (
            ircbot.db.irc_botname,
            channel,
            network,
            port,
        )
        if option == "ping":
            # check connection by sending outself a ping through the server.
            self.caller.msg("Pinging through %s." % chtext)
            ircbot.ping(self.caller)
        elif option in ("users", "nicklist", "who"):
            # retrieve user list. The bot must handles the echo since it's
            # an asynchronous call.
            self.caller.msg("Requesting nicklist from %s (%s:%s)." %
                            (channel, network, port))
            ircbot.get_nicklist(self.caller)
        elif self.caller.locks.check_lockstring(
                self.caller, "dummy:perm(ircstatus) or perm(Developer)"):
            # reboot the client
            self.caller.msg("Forcing a disconnect + reconnect of %s." % chtext)
            ircbot.reconnect()
        else:
            self.caller.msg(
                "You don't have permission to force-reload the IRC bot.")
示例#3
0
    def __set_obj(self, value):
        """
        Set account or obj to their right database field. If
        a dbref is given, assume ObjectDB.

        """
        try:
            value = _GA(value, "dbobj")
        except AttributeError:
            # deprecated ...
            pass
        if isinstance(value, (basestring, int)):
            from evennia.objects.models import ObjectDB
            value = to_str(value, force_string=True)
            if (value.isdigit() or value.startswith("#")):
                dbid = dbref(value, reqhash=False)
                if dbid:
                    try:
                        value = ObjectDB.objects.get(id=dbid)
                    except ObjectDoesNotExist:
                        # maybe it is just a name that happens to look like a dbid
                        pass
        if value.__class__.__name__ == "AccountDB":
            fname = "db_account"
            _SA(self, fname, value)
        else:
            fname = "db_obj"
            _SA(self, fname, value)
        # saving the field
        _GA(self, "save")(update_fields=[fname])
示例#4
0
    def __set_obj(self, value):
        """
        Set account or obj to their right database field. If
        a dbref is given, assume ObjectDB.

        """
        try:
            value = _GA(value, "dbobj")
        except AttributeError:
            # deprecated ...
            pass
        if isinstance(value, (basestring, int)):
            from evennia.objects.models import ObjectDB
            value = to_str(value, force_string=True)
            if (value.isdigit() or value.startswith("#")):
                dbid = dbref(value, reqhash=False)
                if dbid:
                    try:
                        value = ObjectDB.objects.get(id=dbid)
                    except ObjectDoesNotExist:
                        # maybe it is just a name that happens to look like a dbid
                        pass
        if value.__class__.__name__ == "AccountDB":
            fname = "db_account"
            _SA(self, fname, value)
        else:
            fname = "db_obj"
            _SA(self, fname, value)
        # saving the field
        _GA(self, "save")(update_fields=[fname])
示例#5
0
 def _set_foreign(cls, fname, value):
     "Setter only used on foreign key relations, allows setting with #dbref"
     if _GA(cls, "_is_deleted"):
         raise ObjectDoesNotExist("Cannot set %s to %s: Hosting object was already deleted!" % (fname, value))
     try:
         value = _GA(value, "dbobj")
     except AttributeError:
         pass
     if isinstance(value, (basestring, int)):
         value = to_str(value, force_string=True)
         if (value.isdigit() or value.startswith("#")):
             # we also allow setting using dbrefs, if so we try to load the matching object.
             # (we assume the object is of the same type as the class holding the field, if
             # not a custom handler must be used for that field)
             dbid = dbref(value, reqhash=False)
             if dbid:
                 model = _GA(cls, "_meta").get_field(fname).model
                 try:
                     value = model._default_manager.get(id=dbid)
                 except ObjectDoesNotExist:
                     # maybe it is just a name that happens to look like a dbid
                     pass
     _SA(cls, fname, value)
     # only use explicit update_fields in save if we actually have a
     # primary key assigned already (won't be set when first creating object)
     update_fields = [fname] if _GA(cls, "_get_pk_val")(_GA(cls, "_meta")) is not None else None
     _GA(cls, "save")(update_fields=update_fields)
示例#6
0
    def find_topicmatch(self, topicstr, exact=False):
        """
        Searches for matching topics or aliases based on player's
        input.

        Args:
            topcistr (str): Help topic to search for.
            exact (bool, optional): Require exact match
                (non-case-sensitive).  If `False` (default), match
                sub-parts of the string.

        Returns:
            matches (HelpEntries): Query results.

        """
        dbref = utils.dbref(topicstr)
        if dbref:
            return self.filter(id=dbref)
        topics = self.filter(db_key__iexact=topicstr)
        if not topics:
            topics = self.get_by_alias(topicstr)
        if not topics and not exact:
            topics = self.filter(db_key__istartswith=topicstr)
            if not topics:
                topics = self.filter(db_key__icontains=topicstr)
        return topics
示例#7
0
    def find_topicmatch(self, topicstr, exact=False):
        """
        Searches for matching topics or aliases based on player's
        input.

        Args:
            topcistr (str): Help topic to search for.
            exact (bool, optional): Require exact match
                (non-case-sensitive).  If `False` (default), match
                sub-parts of the string.

        Returns:
            matches (HelpEntries): Query results.

        """
        dbref = utils.dbref(topicstr)
        if dbref:
            return self.filter(id=dbref)
        topics = self.filter(db_key__iexact=topicstr)
        if not topics:
            topics = self.get_by_alias(topicstr)
        if not topics and not exact:
            topics = self.filter(db_key__istartswith=topicstr)
            if not topics:
                topics = self.filter(db_key__icontains=topicstr)
        return topics
示例#8
0
    def func(self):
        caller = self.caller

        if self.args is None or not utils.dbref(self.args):
            caller.msg("A puzzle recipe's #dbref must be specified")
            return

        puzzle = search.search_script(self.args)
        if not puzzle or not inherits_from(puzzle[0], PuzzleRecipe):
            caller.msg("Invalid puzzle %r" % (self.args))
            return

        puzzle = puzzle[0]
        caller.msg("Puzzle Recipe %s(%s) '%s' found.\nSpawning %d parts ..." %
                   (puzzle.name, puzzle.dbref, puzzle.db.puzzle_name,
                    len(puzzle.db.parts)))

        for proto_part in puzzle.db.parts:
            part = spawn(proto_part)[0]
            caller.msg(
                "Part %s(%s) spawned and placed at %s(%s)" %
                (part.name, part.dbref, part.location, part.location.dbref))
            part.tags.add(puzzle.db.puzzle_name,
                          category=_PUZZLES_TAG_CATEGORY)
            part.db.puzzle_name = puzzle.db.puzzle_name

        caller.msg("Puzzle armed |gsuccessfully|n.")
示例#9
0
    def __location_set(self, location):
        """Set location, checking for loops and allowing dbref"""
        if isinstance(location, (str, int)):
            # allow setting of #dbref
            dbid = dbref(location, reqhash=False)
            if dbid:
                try:
                    location = ObjectDB.objects.get(id=dbid)
                except ObjectDoesNotExist:
                    # maybe it is just a name that happens to look like a dbid
                    pass
        try:

            def is_loc_loop(loc, depth=0):
                """Recursively traverse target location, trying to catch a loop."""
                if depth > 10:
                    return None
                elif loc == self:
                    raise RuntimeError
                elif loc is None:
                    raise RuntimeWarning
                return is_loc_loop(loc.db_location, depth + 1)

            try:
                is_loc_loop(location)
            except RuntimeWarning:
                # we caught an infinite location loop!
                # (location1 is in location2 which is in location1 ...)
                pass

            # if we get to this point we are ready to change location

            old_location = self.db_location

            # this is checked in _db_db_location_post_save below
            self._safe_contents_update = True

            # actually set the field (this will error if location is invalid)
            self.db_location = location
            self.save(update_fields=["db_location"])

            # remove the safe flag
            del self._safe_contents_update

            # update the contents cache
            if old_location:
                old_location.contents_cache.remove(self)
            if self.db_location:
                self.db_location.contents_cache.add(self)

        except RuntimeError:
            errmsg = "Error: %s.location = %s creates a location loop." % (
                self.key, location)
            raise RuntimeError(errmsg)
        except Exception as e:
            errmsg = "Error (%s): %s is not a valid location." % (str(e),
                                                                  location)
            raise RuntimeError(errmsg)
        return
示例#10
0
 def check_holds(objid):
     # helper function. Compares both dbrefs and keys/aliases.
     objid = str(objid)
     dbref = utils.dbref(objid, reqhash=False)
     if dbref and any((True for obj in contents if obj.dbid == dbref)):
         return True
     objid = objid.lower()
     return any((True for obj in contents if obj.key.lower() == objid
                 or objid in [al.lower() for al in obj.aliases.all()]))
示例#11
0
 def check_holds(objid):
     # helper function. Compares both dbrefs and keys/aliases.
     objid = str(objid)
     dbref = utils.dbref(objid, reqhash=False)
     if dbref and any((True for obj in contents if obj.dbid == dbref)):
         return True
     objid = objid.lower()
     return any((True for obj in contents
                 if obj.key.lower() == objid or objid in [al.lower() for al in obj.aliases.all()]))
示例#12
0
文件: models.py 项目: JynxedJ/evennia
    def __location_set(self, location):
        "Set location, checking for loops and allowing dbref"
        if isinstance(location, (basestring, int)):
            # allow setting of #dbref
            dbid = dbref(location, reqhash=False)
            if dbid:
                try:
                    location = ObjectDB.objects.get(id=dbid)
                except ObjectDoesNotExist:
                    # maybe it is just a name that happens to look like a dbid
                    pass
        try:

            def is_loc_loop(loc, depth=0):
                "Recursively traverse target location, trying to catch a loop."
                if depth > 10:
                    return
                elif loc == self:
                    raise RuntimeError
                elif loc == None:
                    raise RuntimeWarning
                return is_loc_loop(loc.db_location, depth + 1)

            try:
                is_loc_loop(location)
            except RuntimeWarning:
                pass

            # if we get to this point we are ready to change location

            old_location = self.db_location

            # this is checked in _db_db_location_post_save below
            self._safe_contents_update = True

            # actually set the field (this will error if location is invalid)
            self.db_location = location
            self.save(update_fields=["db_location"])

            # remove the safe flag
            del self._safe_contents_update

            # update the contents cache
            if old_location:
                old_location.contents_cache.remove(self)
            if self.db_location:
                self.db_location.contents_cache.add(self)

        except RuntimeError:
            errmsg = "Error: %s.location = %s creates a location loop." % (self.key, location)
            logger.log_errmsg(errmsg)
            raise  # RuntimeError(errmsg)
        except Exception, e:
            errmsg = "Error (%s): %s is not a valid location." % (str(e), location)
            logger.log_errmsg(errmsg)
            raise  # Exception(errmsg)
示例#13
0
文件: comms.py 项目: Henddher/evennia
    def func(self):
        """Handles the functioning of the command."""

        if not self.args:
            self.msg(_list_bots())
            return
        # should always be on the form botname option
        args = self.args.split()
        if len(args) != 2:
            self.msg("Usage: @ircstatus [#dbref ping||nicklist||reconnect]")
            return
        botname, option = args
        if option not in ("ping", "users", "reconnect", "nicklist", "who"):
            self.msg("Not a valid option.")
            return
        matches = None
        if utils.dbref(botname):
            matches = AccountDB.objects.filter(db_is_bot=True, id=utils.dbref(botname))
        if not matches:
            self.msg("No matching IRC-bot found. Use @ircstatus without arguments to list active bots.")
            return
        ircbot = matches[0]
        channel = ircbot.db.irc_channel
        network = ircbot.db.irc_network
        port = ircbot.db.irc_port
        chtext = "IRC bot '%s' on channel %s (%s:%s)" % (ircbot.db.irc_botname, channel, network, port)
        if option == "ping":
            # check connection by sending outself a ping through the server.
            self.caller.msg("Pinging through %s." % chtext)
            ircbot.ping(self.caller)
        elif option in ("users", "nicklist", "who"):
            # retrieve user list. The bot must handles the echo since it's
            # an asynchronous call.
            self.caller.msg("Requesting nicklist from %s (%s:%s)." % (channel, network, port))
            ircbot.get_nicklist(self.caller)
        elif self.caller.locks.check_lockstring(self.caller, "dummy:perm(ircstatus) or perm(Developer)"):
            # reboot the client
            self.caller.msg("Forcing a disconnect + reconnect of %s." % chtext)
            ircbot.reconnect()
        else:
            self.caller.msg("You don't have permission to force-reload the IRC bot.")
示例#14
0
 def find_topicmatch(self, topicstr, exact=False):
     """
     Searches for matching topics based on player's input.
     """
     dbref = utils.dbref(topicstr)
     if dbref:
         return self.filter(id=dbref)
     topics = self.filter(db_key__iexact=topicstr)
     if not topics and not exact:
         topics = self.filter(db_key__istartswith=topicstr)
         if not topics:
             topics = self.filter(db_key__icontains=topicstr)
     return topics
示例#15
0
    def func(self):
        """Setup the irc-channel mapping"""

        if not settings.IRC_ENABLED:
            string = "IRC is not enabled. Activate it in game/settings.py."
            self.msg(string)
            return

        # If no args: list bots.
        if not self.args:
            # show all connections
            ircbots = [
                bot for bot in AccountDB.objects.filter(
                    db_is_bot=True, username__startswith="ircbot-")
            ]
            if ircbots:
                from evennia.utils.evtable import EvTable
                table = EvTable("|w#dbref|n",
                                "|wbotname|n",
                                "|wev-channel/location|n",
                                "|wirc-channel|n",
                                "|wSSL|n",
                                maxwidth=_DEFAULT_WIDTH)
                for ircbot in ircbots:
                    ircinfo = "%s (%s:%s)" % (ircbot.db.irc_channel,
                                              ircbot.db.irc_network,
                                              ircbot.db.irc_port)
                    table.add_row(
                        "#%i" % ircbot.id, ircbot.db.irc_botname,
                        ircbot.attributes.get("ev_channel",
                                              ircbot.db.ev_location.key),
                        ircinfo, ircbot.db.irc_ssl)
                self.msg(table)
                self.msg("Use 'help @puppetbot' for more infomation.")
            else:
                self.msg("No irc bots found.")
            return

        # Switch options available only if valid bot is given.
        if self.switches:
            botname = "ircbot-%s" % self.lhs
            matches = AccountDB.objects.filter(db_is_bot=True,
                                               username=botname)
            dbref = utils.dbref(self.lhs)
            if not matches and dbref:
                # try dbref match
                matches = AccountDB.objects.filter(db_is_bot=True, id=dbref)
            if not matches:
                self.msg("No valid bot given. Consult 'help @puppetbot'")
                return

            # Puppetbot/delete <bot> - Delete bot.
            if any(i in ['disconnect', 'remove', 'delete']
                   for i in self.switches):
                matches[0].delete()
                self.msg("IRC link/bot destroyed.")
                return

            # Puppetbot/ping <bot> - ping bot.
            if "ping" in self.switches:
                matches[0].ping(self.caller)
                self.msg("Pinging " + self.lhs)
                return

            # Puppetbot/about <bot> = msg - Set bot about message.
            if "about" in self.switches:
                if self.rhs:
                    matches[0].db.botdesc = self.rhs
                    self.msg("Bot about message changed to: " + self.rhs)
                else:
                    self.msg("No message given. 'About' desc change aborted.")
                return

            # Puppetbot/who <bot> - Get IRC user list..
            if "who" in self.switches:
                # retrieve user list. The bot must handles the echo since it's
                # an asynchronous call.
                self.caller.msg(
                    "Requesting nicklist from %s (%s:%s)." %
                    (matches[0].db.irc_channel, matches[0].db.irc_network,
                     matches[0].db.irc_port))
                matches[0].get_nicklist(self.caller)
                return

            # Puppetbot/reconnect <bot> - reconnect bot.
            if "reconnect" in self.switches:
                matches[0].reconnect()
                self.msg("Reconnecting " + self.lhs)
                return

            # Puppetbot/reload <bot> - Delete all bots, recreates bots from new user list.
            if "reload" in self.switches:
                matches[0].db.ev_location.msg_contents(
                    "Puppet reload in progress.")
                puppetlist = [
                    puppet
                    for puppet in search.search_tag(matches[0].key + "-puppet")
                ]
                for puppet in puppetlist:
                    puppet.delete()
                matches[0].get_nicklist()
                return

            # Puppetbot/ignore <bot> = puppet - Toggle ignore IRC user.
            if "ignore" in self.switches:
                if self.rhs:
                    user = self.rhs.strip()
                    # If already ignored, toggle off.
                    if user in matches[0].db.userignorelist:
                        matches[0].db.userignorelist.remove(user)
                        matches[0].get_nicklist()
                        return

                    # Else ignore user.
                    else:
                        matches[0].db.userignorelist.append(user)
                        if user in matches[0].db.puppetdict:
                            matches[0].db.puppetdict[user].delete()
                            del matches[0].db.puppetdict[user]
                        return
                else:
                    self.msg("Usage: Puppetbot/ignore <bot> = <puppet>")
                    return

            # Puppetbot/entrymsg <bot> = msg - Set default puppet creation message.
            if "entrymsg" in self.switches:
                if self.rhs:
                    matches[0].db.puppetentrymsg = " " + self.rhs
                    self.msg("Bot entry message changed to: " + " " + self.rhs)
                else:
                    self.msg("No message given. Message change aborted.")
                return

            # Puppetbot/exitmsg <bot> = msg - Set default puppet deletion message.
            if "exitmsg" in self.switches:
                if self.rhs:
                    matches[0].db.puppetexitmsg = " " + self.rhs
                    self.msg("Bot exit message changed to: " + " " + self.rhs)
                else:
                    self.msg("No message given. Message change aborted.")
                return

            # Puppetbot/prefix <bot> = msg - Set string put before username in puppet.key
            if "prefix" in self.switches:
                if self.rhs:
                    matches[0].db.puppetprefix = self.rhs
                    self.msg("Puppet prefix changed to: " + self.rhs)
                    self.msg(
                        "Use: '@puppetbot/reload <bot>' to implement changes.")
                else:
                    self.msg("No message given. Prefix change aborted.")
                return

            # Puppetbot/suffix <bot> = msg - Set string put after username in puppet.key
            if "suffix" in self.switches:
                if self.rhs:
                    matches[0].db.puppetsuffix = self.rhs
                    self.msg("Puppet suffix changed to: " + self.rhs)
                    self.msg(
                        "Use: '@puppetbot/reload <bot>' to implement changes.")
                else:
                    self.msg("No message given. Suffix change aborted.")
                return

            # Puppetbot/defaultdesc <bot> = msg - Set default puppet desc message.
            if "defaultdesc" in self.switches:
                if self.rhs:
                    matches[0].db.puppetlastdesc = matches[
                        0].db.puppetdefaultdesc
                    matches[0].db.puppetdefaultdesc = self.rhs
                    self.msg("Default puppet description changed to: " +
                             self.rhs)
                else:
                    self.msg("No message given. Message change aborted.")
                return

            # Puppetbot/softdesc <bot> = msg - Only changes non custom puppet descriptions to new default.
            if "softdesc" in self.switches:
                puppetlist = [
                    puppet
                    for puppet in search.search_tag(matches[0].key + "-puppet")
                ]
                for puppet in puppetlist:
                    if puppet.db.desc == matches[0].db.puppetlastdesc:
                        puppet.db.desc = matches[0].db.puppetdefaultdesc
                self.msg("Puppets description changed to: " +
                         matches[0].db.puppetdefaultdesc)
                return

            # Puppetbot/forcedesc <bot> = msg - Changes all puppet descriptions to new default.
            if "forcedesc" in self.switches:
                puppetlist = [
                    puppet
                    for puppet in search.search_tag(matches[0].key + "-puppet")
                ]
                for puppet in puppetlist:
                    puppet.db.desc = matches[0].db.puppetdefaultdesc
                self.msg("Puppets description changed to: " +
                         matches[0].db.puppetdefaultdesc)
                return

        # Create Bot.
        location = self.caller.location
        self.args = self.args.replace('#', ' ')  # Avoid Python comment issues
        try:
            irc_network, irc_port, irc_channel, irc_botname = \
                       [part.strip() for part in self.args.split(None, 4)]
            irc_channel = "#%s" % irc_channel
        except Exception:
            string = "IRC bot definition '%s' is not valid." % self.args
            self.msg(string)
            return

        botname = "ircbot-%s" % irc_botname
        # create a new bot
        bot = AccountDB.objects.filter(username__iexact=botname)
        if bot:
            # re-use an existing bot
            bot = bot[0]
            if not bot.is_bot:
                self.msg("'%s' already exists and is not a bot." % botname)
                return
        else:
            try:
                bot = create.create_account(botname,
                                            None,
                                            None,
                                            typeclass=ServerBot)
            except Exception as err:
                self.msg("|rError, could not create the bot:|n '%s'." % err)
                return
        bot.start(ev_location=location,
                  irc_botname=irc_botname,
                  irc_channel=irc_channel,
                  irc_network=irc_network,
                  irc_port=irc_port)
        self.msg("Connection created. Starting IRC bot.")
示例#16
0
    def func(self):
        """Setup the irc-channel mapping"""

        if not settings.IRC_ENABLED:
            string = "IRC is not enabled. Activate it in game/settings.py."
            self.msg(string)
            return

        # If no args: list bots.
        if not self.args:
            # show all connections
            ircbots = [
                bot for bot in AccountDB.objects.filter(
                    db_is_bot=True, username__startswith="ircbot-")
            ]
            if ircbots:
                from evennia.utils.evtable import EvTable
                table = EvTable("|w#dbref|n",
                                "|wbotname|n",
                                "|wev-channel/location|n",
                                "|wirc-channel|n",
                                "|wSSL|n",
                                maxwidth=_DEFAULT_WIDTH)
                for ircbot in ircbots:
                    ircinfo = "%s (%s:%s)" % (ircbot.db.irc_channel,
                                              ircbot.db.irc_network,
                                              ircbot.db.irc_port)
                    table.add_row(
                        "#%i" % ircbot.id, ircbot.db.irc_botname,
                        ircbot.attributes.get("ev_channel",
                                              ircbot.db.ev_location.key),
                        ircinfo, ircbot.db.irc_ssl)
                self.msg(table)
                self.msg("Use 'help @puppetbot' for more infomation.")
            else:
                self.msg("No irc bots found.")
            return

        # Switch options available only if valid bot is given.
        if self.switches:
            botname = "ircbot-%s" % self.lhs
            matches = AccountDB.objects.filter(db_is_bot=True,
                                               username=botname)
            dbref = utils.dbref(self.lhs)
            if not matches and dbref:
                # try dbref match
                matches = AccountDB.objects.filter(db_is_bot=True, id=dbref)
            if not matches:
                self.msg("No valid bot given. Consult 'help @puppetbot'")
                return

            # Puppetbot/delete <bot> - Delete bot.
            if any(i in ['disconnect', 'remove', 'delete']
                   for i in self.switches):
                matches[0].delete()
                self.msg("IRC link/bot destroyed.")
                return

            # Puppetbot/ping <bot> - ping bot.
            if "ping" in self.switches:
                matches[0].ping(self.caller)
                self.msg("Pinging " + self.lhs)
                return

            # Puppetbot/who <bot> - Get IRC user list..
            if "who" in self.switches:
                # retrieve user list. The bot must handles the echo since it's
                # an asynchronous call.
                self.caller.msg(
                    "Requesting nicklist from %s (%s:%s)." %
                    (matches[0].db.irc_channel, matches[0].db.irc_network,
                     matches[0].db.irc_port))
                matches[0].get_nicklist(self.caller)
                return

            # Puppetbot/reconnect <bot> - reconnect bot.
            if "reconnect" in self.switches:
                matches[0].reconnect()
                self.msg("Reconnecting " + self.lhs)
                return

            # Puppetbot/reload <bot> - Delete all bots, recreates bots from new user list.
            if "reload" in self.switches:
                matches[0].db.ev_location.msg_contents(
                    "Puppet reload in progress.")
                puppetlist = [
                    puppet
                    for puppet in search.search_tag(matches[0].key + "-puppet")
                ]
                for puppet in puppetlist:
                    puppet.delete()
                matches[0].get_nicklist()
                return

        # Create Bot.
        location = self.caller.location
        self.args = self.args.replace('#', ' ')  # Avoid Python comment issues
        try:
            irc_network, irc_port, irc_channel, irc_botname = \
                       [part.strip() for part in self.args.split(None, 4)]
            irc_channel = "#%s" % irc_channel
        except Exception:
            string = "IRC bot definition '%s' is not valid." % self.args
            self.msg(string)
            return

        botname = "ircbot-%s" % irc_botname
        # create a new bot
        bot = AccountDB.objects.filter(username__iexact=botname)
        if bot:
            self.msg("Account '%s' already exists." % botname)
            return
        else:
            password = "******"
            try:
                bot = create.create_account(botname,
                                            None,
                                            password,
                                            typeclass=AccountBot)
            except Exception as err:
                self.msg("|rError, could not create the bot:|n '%s'." % err)
                return
        bot.start(ev_location=location,
                  irc_botname=irc_botname,
                  irc_channel=irc_channel,
                  irc_network=irc_network,
                  irc_port=irc_port)
        self.msg("Connection created. Starting IRC bot.")
示例#17
0
文件: comms.py 项目: Henddher/evennia
    def func(self):
        """Setup the irc-channel mapping"""

        if not settings.IRC_ENABLED:
            string = """IRC is not enabled. You need to activate it in game/settings.py."""
            self.msg(string)
            return

        if 'list' in self.switches:
            # show all connections
            self.msg(_list_bots())
            return

        if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches:
            botname = "ircbot-%s" % self.lhs
            matches = AccountDB.objects.filter(db_is_bot=True, username=botname)
            dbref = utils.dbref(self.lhs)
            if not matches and dbref:
                # try dbref match
                matches = AccountDB.objects.filter(db_is_bot=True, id=dbref)
            if matches:
                matches[0].delete()
                self.msg("IRC connection destroyed.")
            else:
                self.msg("IRC connection/bot could not be removed, does it exist?")
            return

        if not self.args or not self.rhs:
            string = "Usage: @irc2chan[/switches] <evennia_channel> =" \
                     " <ircnetwork> <port> <#irchannel> <botname>[:typeclass]"
            self.msg(string)
            return

        channel = self.lhs
        self.rhs = self.rhs.replace('#', ' ')  # to avoid Python comment issues
        try:
            irc_network, irc_port, irc_channel, irc_botname = \
                [part.strip() for part in self.rhs.split(None, 4)]
            irc_channel = "#%s" % irc_channel
        except Exception:
            string = "IRC bot definition '%s' is not valid." % self.rhs
            self.msg(string)
            return

        botclass = None
        if ":" in irc_botname:
            irc_botname, botclass = [part.strip() for part in irc_botname.split(":", 2)]
        botname = "ircbot-%s" % irc_botname
        # If path given, use custom bot otherwise use default.
        botclass = botclass if botclass else bots.IRCBot
        irc_ssl = "ssl" in self.switches

        # create a new bot
        bot = AccountDB.objects.filter(username__iexact=botname)
        if bot:
            # re-use an existing bot
            bot = bot[0]
            if not bot.is_bot:
                self.msg("Account '%s' already exists and is not a bot." % botname)
                return
        else:
            password = hashlib.md5(str(time.time())).hexdigest()[:11]
            try:
                bot = create.create_account(botname, None, password, typeclass=botclass)
            except Exception as err:
                self.msg("|rError, could not create the bot:|n '%s'." % err)
                return
        bot.start(ev_channel=channel, irc_botname=irc_botname, irc_channel=irc_channel,
                  irc_network=irc_network, irc_port=irc_port, irc_ssl=irc_ssl)
        self.msg("Connection created. Starting IRC bot.")
示例#18
0
文件: comms.py 项目: jontsai/evennia
    def func(self):
        """Setup the irc-channel mapping"""

        if not settings.IRC_ENABLED:
            string = """IRC is not enabled. You need to activate it in game/settings.py."""
            self.msg(string)
            return

        if "list" in self.switches:
            # show all connections
            self.msg(_list_bots(self))
            return

        if "disconnect" in self.switches or "remove" in self.switches or "delete" in self.switches:
            botname = "ircbot-%s" % self.lhs
            matches = AccountDB.objects.filter(db_is_bot=True,
                                               username=botname)
            dbref = utils.dbref(self.lhs)
            if not matches and dbref:
                # try dbref match
                matches = AccountDB.objects.filter(db_is_bot=True, id=dbref)
            if matches:
                matches[0].delete()
                self.msg("IRC connection destroyed.")
            else:
                self.msg(
                    "IRC connection/bot could not be removed, does it exist?")
            return

        if not self.args or not self.rhs:
            string = (
                "Usage: irc2chan[/switches] <evennia_channel> ="
                " <ircnetwork> <port> <#irchannel> <botname>[:typeclass]")
            self.msg(string)
            return

        channel = self.lhs
        self.rhs = self.rhs.replace("#", " ")  # to avoid Python comment issues
        try:
            irc_network, irc_port, irc_channel, irc_botname = [
                part.strip() for part in self.rhs.split(None, 4)
            ]
            irc_channel = "#%s" % irc_channel
        except Exception:
            string = "IRC bot definition '%s' is not valid." % self.rhs
            self.msg(string)
            return

        botclass = None
        if ":" in irc_botname:
            irc_botname, botclass = [
                part.strip() for part in irc_botname.split(":", 2)
            ]
        botname = "ircbot-%s" % irc_botname
        # If path given, use custom bot otherwise use default.
        botclass = botclass if botclass else bots.IRCBot
        irc_ssl = "ssl" in self.switches

        # create a new bot
        bot = AccountDB.objects.filter(username__iexact=botname)
        if bot:
            # re-use an existing bot
            bot = bot[0]
            if not bot.is_bot:
                self.msg("Account '%s' already exists and is not a bot." %
                         botname)
                return
        else:
            try:
                bot = create.create_account(botname,
                                            None,
                                            None,
                                            typeclass=botclass)
            except Exception as err:
                self.msg("|rError, could not create the bot:|n '%s'." % err)
                return
        bot.start(
            ev_channel=channel,
            irc_botname=irc_botname,
            irc_channel=irc_channel,
            irc_network=irc_network,
            irc_port=irc_port,
            irc_ssl=irc_ssl,
        )
        self.msg("Connection created. Starting IRC bot.")
示例#19
0
文件: comms.py 项目: wty0512/evennia
    def func(self):
        "Setup the irc-channel mapping"

        if not settings.IRC_ENABLED:
            string = """IRC is not enabled. You need to activate it in game/settings.py."""
            self.msg(string)
            return

        if 'list' in self.switches:
            # show all connections
            ircbots = [
                bot for bot in PlayerDB.objects.filter(
                    db_is_bot=True, username__startswith="ircbot-")
            ]
            if ircbots:
                from evennia.utils.evtable import EvTable
                table = EvTable("{wdbid{n",
                                "{wbotname{n",
                                "{wev-channel{n",
                                "{wirc-channel{n",
                                "{wSSL{n",
                                maxwidth=_DEFAULT_WIDTH)
                for ircbot in ircbots:
                    ircinfo = "%s (%s:%s)" % (ircbot.db.irc_channel,
                                              ircbot.db.irc_network,
                                              ircbot.db.irc_port)
                    table.add_row(ircbot.id, ircbot.db.irc_botname,
                                  ircbot.db.ev_channel, ircinfo,
                                  ircbot.db.irc_ssl)
                self.caller.msg(table)
            else:
                self.msg("No irc bots found.")
            return

        if ('disconnect' in self.switches or 'remove' in self.switches
                or 'delete' in self.switches):
            botname = "ircbot-%s" % self.lhs
            matches = PlayerDB.objects.filter(db_is_bot=True, username=botname)
            dbref = utils.dbref(self.lhs)
            if not matches and dbref:
                # try dbref match
                matches = PlayerDB.objects.filter(db_is_bot=True, id=dbref)
            if matches:
                matches[0].delete()
                self.msg("IRC connection destroyed.")
            else:
                self.msg(
                    "IRC connection/bot could not be removed, does it exist?")
            return

        if not self.args or not self.rhs:
            string = "Usage: @irc2chan[/switches] <evennia_channel> = <ircnetwork> <port> <#irchannel> <botname>"
            self.msg(string)
            return

        channel = self.lhs
        self.rhs = self.rhs.replace('#', ' ')  # to avoid Python comment issues
        try:
            irc_network, irc_port, irc_channel, irc_botname = \
                       [part.strip() for part in self.rhs.split(None, 3)]
            irc_channel = "#%s" % irc_channel
        except Exception:
            string = "IRC bot definition '%s' is not valid." % self.rhs
            self.msg(string)
            return

        botname = "ircbot-%s" % irc_botname
        irc_ssl = "ssl" in self.switches

        # create a new bot
        bot = PlayerDB.objects.filter(username__iexact=botname)
        if bot:
            # re-use an existing bot
            bot = bot[0]
            if not bot.is_bot:
                self.msg("Player '%s' already exists and is not a bot." %
                         botname)
                return
        else:
            bot = create.create_player(botname,
                                       None,
                                       None,
                                       typeclass=bots.IRCBot)
        bot.start(ev_channel=channel,
                  irc_botname=irc_botname,
                  irc_channel=irc_channel,
                  irc_network=irc_network,
                  irc_port=irc_port,
                  irc_ssl=irc_ssl)
        self.msg("Connection created. Starting IRC bot.")
示例#20
0
    def func(self):
        "Setup the irc-channel mapping"

        if not settings.IRC_ENABLED:
            string = """IRC is not enabled. You need to activate it in game/settings.py."""
            self.msg(string)
            return

        if 'list' in self.switches:
            # show all connections
            ircbots = [bot for bot in PlayerDB.objects.filter(db_is_bot=True, username__startswith="ircbot-")]
            if ircbots:
                from evennia.utils.evtable import EvTable
                table = EvTable("{wdbid{n", "{wbotname{n", "{wev-channel{n", "{wirc-channel{n", "{wSSL{n", maxwidth=_DEFAULT_WIDTH)
                for ircbot in ircbots:
                    ircinfo = "%s (%s:%s)" % (ircbot.db.irc_channel, ircbot.db.irc_network, ircbot.db.irc_port)
                    table.add_row(ircbot.id, ircbot.db.irc_botname, ircbot.db.ev_channel, ircinfo, ircbot.db.irc_ssl)
                self.caller.msg(table)
            else:
                self.msg("No irc bots found.")
            return


        if('disconnect' in self.switches or 'remove' in self.switches or
                                                    'delete' in self.switches):
            botname = "ircbot-%s" % self.lhs
            matches = PlayerDB.objects.filter(db_is_bot=True, username=botname)
            dbref = utils.dbref(self.lhs)
            if not matches and dbref:
                # try dbref match
                matches = PlayerDB.objects.filter(db_is_bot=True, id=dbref)
            if matches:
                matches[0].delete()
                self.msg("IRC connection destroyed.")
            else:
                self.msg("IRC connection/bot could not be removed, does it exist?")
            return

        if not self.args or not self.rhs:
            string = "Usage: @irc2chan[/switches] <evennia_channel> = <ircnetwork> <port> <#irchannel> <botname>"
            self.msg(string)
            return

        channel = self.lhs
        self.rhs = self.rhs.replace('#', ' ') # to avoid Python comment issues
        try:
            irc_network, irc_port, irc_channel, irc_botname = \
                       [part.strip() for part in self.rhs.split(None, 3)]
            irc_channel = "#%s" % irc_channel
        except Exception:
            string = "IRC bot definition '%s' is not valid." % self.rhs
            self.msg(string)
            return

        botname = "ircbot-%s" % irc_botname
        irc_ssl = "ssl" in self.switches

        # create a new bot
        bot = PlayerDB.objects.filter(username__iexact=botname)
        if bot:
            # re-use an existing bot
            bot = bot[0]
            if not bot.is_bot:
                self.msg("Player '%s' already exists and is not a bot." % botname)
                return
        else:
            bot = create.create_player(botname, None, None, typeclass=bots.IRCBot)
        bot.start(ev_channel=channel, irc_botname=irc_botname, irc_channel=irc_channel,
                  irc_network=irc_network, irc_port=irc_port, irc_ssl=irc_ssl)
        self.msg("Connection created. Starting IRC bot.")
示例#21
0
    def func(self):
        self._USAGE = "Usage: @puzzleedit[/switches] <dbref>[/attribute = <value>]"
        caller = self.caller

        if not self.lhslist:
            caller.msg(self._USAGE)
            return

        if "/" in self.lhslist[0]:
            recipe_dbref, attr = self.lhslist[0].split("/")
        else:
            recipe_dbref = self.lhslist[0]

        if not utils.dbref(recipe_dbref):
            caller.msg("A puzzle recipe's #dbref must be specified.\n" +
                       self._USAGE)
            return

        puzzle = search.search_script(recipe_dbref)
        if not puzzle or not inherits_from(puzzle[0], PuzzleRecipe):
            caller.msg("%s(%s) is not a puzzle" %
                       (puzzle[0].name, recipe_dbref))
            return

        puzzle = puzzle[0]
        puzzle_name_id = "%s(%s)" % (puzzle.name, puzzle.dbref)

        if "delete" in self.switches:
            if not (puzzle.access(caller, "control")
                    or puzzle.access(caller, "delete")):
                caller.msg("You don't have permission to delete %s." %
                           puzzle_name_id)
                return

            puzzle.delete()
            caller.msg("%s was deleted" % puzzle_name_id)
            return

        elif "addpart" in self.switches:
            objs = self._get_objs()
            if objs:
                added = self._add_parts(objs, puzzle)
                caller.msg("%s were added to parts" % (", ".join(added)))
            return

        elif "delpart" in self.switches:
            objs = self._get_objs()
            if objs:
                removed = self._remove_parts(objs, puzzle)
                caller.msg("%s were removed from parts" % (", ".join(removed)))
            return

        elif "addresult" in self.switches:
            objs = self._get_objs()
            if objs:
                added = self._add_results(objs, puzzle)
                caller.msg("%s were added to results" % (", ".join(added)))
            return

        elif "delresult" in self.switches:
            objs = self._get_objs()
            if objs:
                removed = self._remove_results(objs, puzzle)
                caller.msg("%s were removed from results" %
                           (", ".join(removed)))
            return

        else:
            # edit attributes

            if not (puzzle.access(caller, "control")
                    or puzzle.access(caller, "edit")):
                caller.msg("You don't have permission to edit %s." %
                           puzzle_name_id)
                return

            if attr == "use_success_message":
                puzzle.db.use_success_message = self.rhs
                caller.msg("%s use_success_message = %s\n" %
                           (puzzle_name_id, puzzle.db.use_success_message))
                return
            elif attr == "use_success_location_message":
                puzzle.db.use_success_location_message = self.rhs
                caller.msg(
                    "%s use_success_location_message = %s\n" %
                    (puzzle_name_id, puzzle.db.use_success_location_message))
                return
            elif attr == "mask":
                puzzle.db.mask = tuple(self.rhslist)
                caller.msg("%s mask = %r\n" % (puzzle_name_id, puzzle.db.mask))
                return