Exemple #1
0
    def _send_to_connect_channel(self, message):
        try:
            from evennia.comms.models import ChannelDB
            from django.utils import timezone

            try:
                chan = ChannelDB.objects.get(
                    db_key=settings.GUEST_CHANNEL_NAME)
            except ChannelDB.DoesNotExist:
                chan_dict = [
                    d for d in settings.DEFAULT_CHANNELS
                    if d["key"] == settings.GUEST_CHANNEL_NAME
                ][0]
                chan = create.create_channel(**chan_dict)
            now = timezone.now()
            now = "%02i:%02i" % (now.hour, now.minute)
            chan.tempmsg("[%s]: %s" % (now, message))
            try:
                gm_chan = ChannelDB.objects.get(
                    db_key=settings.STAFF_INFO_CHANNEL_NAME)
            except ChannelDB.DoesNotExist:
                chan_dict = [
                    d for d in settings.DEFAULT_CHANNELS
                    if d["key"] == settings.STAFF_INFO_CHANNEL_NAME
                ][0]
                gm_chan = create.create_channel(**chan_dict)
            addr = self.sessions.all()[0].address
            message += " from %s" % addr
            gm_chan.msg(message)
        except Exception as err:
            import traceback

            traceback.print_exc()
            print("Error in logging messages to guest channel: %s" % err)
 def test_create_msg__channel(self):
     chan1 = create.create_channel("DummyChannel1")
     chan2 = create.create_channel("DummyChannel2")
     msg = create.create_message(self.char1,
                                 self.msgtext,
                                 channels=[chan1, chan2],
                                 header="TestHeader")
     self.assertEqual(list(msg.channels), [chan1, chan2])
Exemple #3
0
    def at_post_portal_sync(self, mode):
        """
        This is called just after the portal has finished syncing back data to the server
        after reconnecting.

        Args:
            mode (str): One of reload, reset or shutdown.

        """

        from evennia.scripts.monitorhandler import MONITOR_HANDLER

        MONITOR_HANDLER.restore(mode == "reload")

        from evennia.scripts.tickerhandler import TICKER_HANDLER

        TICKER_HANDLER.restore(mode == "reload")

        # after sync is complete we force-validate all scripts
        # (this also starts any that didn't yet start)
        ScriptDB.objects.validate(init_mode=mode)

        # start the task handler
        from evennia.scripts.taskhandler import TASK_HANDLER

        TASK_HANDLER.load()
        TASK_HANDLER.create_delays()

        # check so default channels exist
        from evennia.comms.models import ChannelDB
        from evennia.accounts.models import AccountDB
        from evennia.utils.create import create_channel

        god_account = AccountDB.objects.get(id=1)
        # mudinfo
        mudinfo_chan = settings.CHANNEL_MUDINFO
        if not mudinfo_chan:
            raise RuntimeError("settings.CHANNEL_MUDINFO must be defined.")
        if not ChannelDB.objects.filter(db_key=mudinfo_chan["key"]):
            channel = create_channel(**mudinfo_chan)
            channel.connect(god_account)
        # connectinfo
        connectinfo_chan = settings.CHANNEL_MUDINFO
        if connectinfo_chan:
            if not ChannelDB.objects.filter(db_key=mudinfo_chan["key"]):
                channel = create_channel(**connectinfo_chan)
        # default channels
        for chan_info in settings.DEFAULT_CHANNELS:
            if not ChannelDB.objects.filter(db_key=chan_info["key"]):
                channel = create_channel(**chan_info)
                channel.connect(god_account)

        # delete the temporary setting
        ServerConfig.objects.conf("server_restart_mode", delete=True)
Exemple #4
0
 def setup_channels(self):
     if self.ic_channel:
         ic_channel = self.ic_channel
         ic_channel.key = 'group_%s_ic' % self.key
     else:
         self.ic_channel = create_channel('group_%s_ic' % self.key, typeclass='athanor.classes.channels.GroupIC')
         self.save(update_fields=['ic_channel'])
         self.ic_channel.init_locks(group=self)
     if self.ooc_channel:
         ooc_channel = self.ooc_channel
         ooc_channel.key = 'group_%s_ooc' % self.key
     else:
         self.ooc_channel = create_channel('group_%s_ooc' % self.key, typeclass='athanor.classes.channels.GroupOOC')
         self.save(update_fields=['ooc_channel'])
         self.ooc_channel.init_locks(group=self)
Exemple #5
0
    def func(self):
        """Implement the command"""

        caller = self.caller

        if not self.args:
            self.msg(
                "Usage ccreate <channelname>[;alias;alias..] = description")
            return

        description = ""

        if self.rhs:
            description = self.rhs
        lhs = self.lhs
        channame = lhs
        aliases = None
        if ";" in lhs:
            channame, aliases = lhs.split(";", 1)
            aliases = [alias.strip().lower() for alias in aliases.split(";")]
        channel = CHANNEL_DEFAULT_TYPECLASS.objects.channel_search(channame)
        if channel:
            self.msg("A channel with that name already exists.")
            return
        # Create and set the channel up
        lockstring = "send:all();listen:all();control:id(%s)" % caller.id
        new_chan = create.create_channel(channame.strip(),
                                         aliases,
                                         description,
                                         locks=lockstring)
        new_chan.connect(caller)
        CHANNELHANDLER.update()
        self.msg("Created channel %s and connected to it." % new_chan.key)
Exemple #6
0
    def func(self):
        "Implement the command"

        caller = self.caller

        if not self.args:
            self.msg("Usage @ccreate <channelname>[;alias;alias..] = description")
            return

        description = ""

        if self.rhs:
            description = self.rhs
        lhs = self.lhs
        channame = lhs
        aliases = None
        if ';' in lhs:
            channame, aliases = lhs.split(';', 1)
            aliases = [alias.strip().lower() for alias in aliases.split(';')]
        channel = ChannelDB.objects.channel_search(channame)
        if channel:
            self.msg("A channel with that name already exists.")
            return
        # Create and set the channel up
        lockstring = "send:all();listen:all();control:id(%s)" % caller.id
        new_chan = create.create_channel(channame.strip(),
                                         aliases,
                                         description,
                                         locks=lockstring)
        new_chan.connect(caller)
        CHANNELHANDLER.update()
        self.msg("Created channel %s and connected to it." % new_chan.key)
def create_channels():
    """
    Creates some sensible default channels.
    """
    print " Creating default channels ..."

    goduser = get_god_player()
    for channeldict in settings.DEFAULT_CHANNELS:
        channel = create.create_channel(**channeldict)
        channel.connect(goduser)
Exemple #8
0
    def test_create_channel__complex(self):
        locks = "foo:false();bar:true()"
        tags = ["tag1", "tag2", "tag3"]
        aliases = ['foo', 'bar', 'tst']

        chan = create.create_channel("TestChannel2", desc="Testing channel",
                                     aliases=aliases, locks=locks, tags=tags)
        self.assertTrue(all(lock in chan.locks.all() for lock in locks.split(";")))
        self.assertEqual(chan.tags.all(), tags)
        self.assertEqual(list(chan.aliases.all()).sort(), aliases.sort())
Exemple #9
0
def create_channels():
    """
    Creates some sensible default channels.
    """
    print " Creating default channels ..."

    goduser = get_god_player()
    for channeldict in settings.DEFAULT_CHANNELS:
        channel = create.create_channel(**channeldict)
        channel.connect(goduser)
Exemple #10
0
def create_channels():
    """
    Creates some sensible default channels.

    """
    logger.log_info("Initial setup: Creating default channels ...")

    goduser = get_god_account()
    for channeldict in settings.DEFAULT_CHANNELS:
        channel = create.create_channel(**channeldict)
        channel.connect(goduser)
Exemple #11
0
def create_channels():
    """
    Creates some sensible default channels.

    """
    logger.log_info("Creating default channels ...")

    goduser = get_god_account()
    for channeldict in settings.DEFAULT_CHANNELS:
        channel = create.create_channel(**channeldict)
        channel.connect(goduser)
Exemple #12
0
    def at_start(self):
        """Set up the event system when starting.

        Note that this hook is called every time the server restarts
        (including when it's reloaded).  This hook performs the following
        tasks:

        -   Create temporarily stored events.
        -   Generate locals (individual events' namespace).
        -   Load eventfuncs, including user-defined ones.
        -   Re-schedule tasks that aren't set to fire anymore.
        -   Effectively connect the handler to the main script.

        """
        self.ndb.events = {}
        for typeclass, name, variables, help_text, custom_call, custom_add in EVENTS:
            self.add_event(typeclass, name, variables, help_text, custom_call,
                           custom_add)

        # Generate locals
        self.ndb.current_locals = {}
        self.ndb.fresh_locals = {}
        addresses = ["evennia.contrib.ingame_python.eventfuncs"]
        addresses.extend(
            getattr(settings, "EVENTFUNCS_LOCATIONS", ["world.eventfuncs"]))
        for address in addresses:
            if pypath_to_realpath(address):
                self.ndb.fresh_locals.update(all_from_module(address))

        # Restart the delayed tasks
        now = datetime.now()
        for task_id, definition in tuple(self.db.tasks.items()):
            future, obj, event_name, locals = definition
            seconds = (future - now).total_seconds()
            if seconds < 0:
                seconds = 0

            delay(seconds, complete_task, task_id)

        # Place the script in the CallbackHandler
        from evennia.contrib.ingame_python import typeclasses

        CallbackHandler.script = self
        DefaultObject.callbacks = typeclasses.EventObject.callbacks

        # Create the channel if non-existent
        try:
            self.ndb.channel = ChannelDB.objects.get(db_key="everror")
        except ChannelDB.DoesNotExist:
            self.ndb.channel = create_channel(
                "everror",
                desc="Event errors",
                locks="control:false();listen:perm(Builders);send:false()",
            )
Exemple #13
0
def create_channels():
    """
    Creates some sensible default channels.

    """
    logger.log_info("Initial setup: Creating default channels ...")

    goduser = get_god_account()

    channel_mudinfo = settings.CHANNEL_MUDINFO
    if not channel_mudinfo:
        raise RuntimeError("settings.CHANNEL_MUDINFO must be defined.")
    channel = create.create_channel(**channel_mudinfo)
    channel.connect(goduser)

    channel_connectinfo = settings.CHANNEL_CONNECTINFO
    if channel_connectinfo:
        channel = create.create_channel(**channel_connectinfo)

    for channeldict in settings.DEFAULT_CHANNELS:
        channel = create.create_channel(**channeldict)
        channel.connect(goduser)
Exemple #14
0
    def at_start(self):
        """Set up the event system when starting.

        Note that this hook is called every time the server restarts
        (including when it's reloaded).  This hook performs the following
        tasks:

        -   Create temporarily stored events.
        -   Generate locals (individual events' namespace).
        -   Load eventfuncs, including user-defined ones.
        -   Re-schedule tasks that aren't set to fire anymore.
        -   Effectively connect the handler to the main script.

        """
        self.ndb.events = {}
        for typeclass, name, variables, help_text, custom_call, custom_add in EVENTS:
            self.add_event(typeclass, name, variables, help_text, custom_call, custom_add)

        # Generate locals
        self.ndb.current_locals = {}
        self.ndb.fresh_locals = {}
        addresses = ["evennia.contrib.ingame_python.eventfuncs"]
        addresses.extend(getattr(settings, "EVENTFUNCS_LOCATIONS", ["world.eventfuncs"]))
        for address in addresses:
            if pypath_to_realpath(address):
                self.ndb.fresh_locals.update(all_from_module(address))

        # Restart the delayed tasks
        now = datetime.now()
        for task_id, definition in tuple(self.db.tasks.items()):
            future, obj, event_name, locals = definition
            seconds = (future - now).total_seconds()
            if seconds < 0:
                seconds = 0

            delay(seconds, complete_task, task_id)

        # Place the script in the CallbackHandler
        from evennia.contrib.ingame_python import typeclasses
        CallbackHandler.script = self
        DefaultObject.callbacks = typeclasses.EventObject.callbacks

        # Create the channel if non-existent
        try:
            self.ndb.channel = ChannelDB.objects.get(db_key="everror")
        except ChannelDB.DoesNotExist:
            self.ndb.channel = create_channel("everror", desc="Event errors",
                    locks="control:false();listen:perm(Builders);send:false()")
Exemple #15
0
    def create(cls, key, account=None, *args, **kwargs):
        """
        Creates a basic Channel with default parameters, unless otherwise
        specified or extended.

        Provides a friendlier interface to the utils.create_channel() function.

        Args:
            key (str): This must be unique.
            account (Account): Account to attribute this object to.

        Keyword Args:
            aliases (list of str): List of alternative (likely shorter) keynames.
            description (str): A description of the channel, for use in listings.
            locks (str): Lockstring.
            keep_log (bool): Log channel throughput.
            typeclass (str or class): The typeclass of the Channel (not
                often used).
            ip (str): IP address of creator (for object auditing).

        Returns:
            channel (Channel): A newly created Channel.
            errors (list): A list of errors in string form, if any.

        """
        errors = []
        obj = None
        ip = kwargs.pop("ip", "")

        try:
            kwargs["desc"] = kwargs.pop("description", "")
            kwargs["typeclass"] = kwargs.get("typeclass", cls)
            obj = create.create_channel(key, *args, **kwargs)

            # Record creator id and creation IP
            if ip:
                obj.db.creator_ip = ip
            if account:
                obj.db.creator_id = account.id

        except Exception as exc:
            errors.append(
                "An error occurred while creating this '%s' object." % key)
            logger.log_err(exc)

        return obj, errors
 def test_create_channel__simple(self):
     chan = create.create_channel("TestChannel1", desc="Testing channel")
     self.assertEqual(chan.key, "TestChannel1")
     self.assertEqual(chan.db.desc, "Testing channel")
Exemple #17
0
 def setup(self):
     if not self.channel:
         self.channel = create_channel('%s' % self.key, typeclass='classes.channels.RadioChannel')
         self.channel.init_locks()
         self.save()