Ejemplo n.º 1
0
 def func(self):
     """Show server time data in a table."""
     table1 = EvTable("|wServer time", "", align="l", width=78)
     table1.add_row("Current uptime",
                    utils.time_format(gametime.uptime(), 3))
     table1.add_row("Total runtime",
                    utils.time_format(gametime.runtime(), 2))
     table1.add_row(
         "First start",
         datetime.datetime.fromtimestamp(gametime.server_epoch()))
     table1.add_row("Current time", datetime.datetime.now())
     table1.reformat_column(0, width=30)
     table2 = EvTable("|wIn-Game time",
                      "|wReal time x %g" % gametime.TIMEFACTOR,
                      align="l",
                      width=77,
                      border_top=0)
     epochtxt = "Epoch (%s)" % ("from settings" if settings.TIME_GAME_EPOCH
                                else "server start")
     table2.add_row(epochtxt,
                    datetime.datetime.fromtimestamp(gametime.game_epoch()))
     table2.add_row("Total time passed:",
                    utils.time_format(gametime.gametime(), 2))
     table2.add_row(
         "Current time ",
         datetime.datetime.fromtimestamp(gametime.gametime(absolute=True)))
     table2.reformat_column(0, width=30)
     self.caller.msg(unicode(table1) + "\n" + unicode(table2))
Ejemplo n.º 2
0
 def func(self):
     """Show server time data in a table."""
     table1 = EvTable("|wServer time", "", align="l", width=78)
     table1.add_row("Current uptime", utils.time_format(gametime.uptime(), 3))
     table1.add_row("Total runtime", utils.time_format(gametime.runtime(), 2))
     table1.add_row("First start", datetime.datetime.fromtimestamp(gametime.server_epoch()))
     table1.add_row("Current time", datetime.datetime.now())
     table1.reformat_column(0, width=30)
     table2 = EvTable("|wIn-Game time", "|wReal time x %g" % gametime.TIMEFACTOR, align="l", width=77, border_top=0)
     epochtxt = "Epoch (%s)" % ("from settings" if settings.TIME_GAME_EPOCH else "server start")
     table2.add_row(epochtxt, datetime.datetime.fromtimestamp(gametime.game_epoch()))
     table2.add_row("Total time passed:", utils.time_format(gametime.gametime(), 2))
     table2.add_row("Current time ", datetime.datetime.fromtimestamp(gametime.gametime(absolute=True)))
     table2.reformat_column(0, width=30)
     self.caller.msg(unicode(table1) + "\n" + unicode(table2))
Ejemplo n.º 3
0
def gametime():
    """Return the current game time as a datetime object.

    This returns a datetime opbject with an additional property: `season`.  It returns the current reason as a string (like "winter").

    """
    return GTime.fromtimestamp(gtime.gametime(absolute=True))
Ejemplo n.º 4
0
def real_seconds_until(**kwargs):
    """
    Return the real seconds until game time.

    If the game time is 5:00, TIME_FACTOR is set to 2 and you ask
    the number of seconds until it's 5:10, then this function should
    return 300 (5 minutes).

    Args:
        times (str: int): the time units.

    Example:
        real_seconds_until(hour=5, min=10, sec=0)

    Returns:
        The number of real seconds before the given game time is up.

    """
    current = gametime.gametime(absolute=True)
    units = sorted(set(UNITS.values()), reverse=True)
    # Remove seconds from the tuple
    del units[-1]
    divisors = list(time_to_tuple(current, *units))

    # For each keyword, add in the unit's
    units.append(1)
    higher_unit = None
    for unit, value in kwargs.items():
        # Get the unit's index
        if unit not in UNITS:
            raise ValueError("unknown unit".format(unit))

        seconds = UNITS[unit]
        index = units.index(seconds)
        divisors[index] = value
        if higher_unit is None or higher_unit > index:
            higher_unit = index

    # Check the projected time
    # Note that it can be already passed (the given time may be in the past)
    projected = 0
    for i, value in enumerate(divisors):
        seconds = units[i]
        projected += value * seconds

    if projected <= current:
        # The time is in the past, increase the higher unit
        if higher_unit:
            divisors[higher_unit - 1] += 1
        else:
            divisors[0] += 1

    # Get the projected time again
    projected = 0
    for i, value in enumerate(divisors):
        seconds = units[i]
        projected += value * seconds

    return (projected - current) / TIMEFACTOR
Ejemplo n.º 5
0
def real_seconds_until(**kwargs):
    """
    Return the real seconds until game time.

    If the game time is 5:00, TIME_FACTOR is set to 2 and you ask
    the number of seconds until it's 5:10, then this function should
    return 300 (5 minutes).

    Args:
        times (str: int): the time units.

    Example:
        real_seconds_until(hour=5, min=10, sec=0)

    Returns:
        The number of real seconds before the given game time is up.

    """
    current = gametime.gametime(absolute=True)
    units = sorted(set(UNITS.values()), reverse=True)
    # Remove seconds from the tuple
    del units[-1]
    divisors = list(time_to_tuple(current, *units))

    # For each keyword, add in the unit's
    units.append(1)
    higher_unit = None
    for unit, value in kwargs.items():
        # Get the unit's index
        if unit not in UNITS:
            raise ValueError("unknown unit".format(unit))

        seconds = UNITS[unit]
        index = units.index(seconds)
        divisors[index] = value
        if higher_unit is None or higher_unit > index:
            higher_unit = index

    # Check the projected time
    # Note that it can be already passed (the given time may be in the past)
    projected = 0
    for i, value in enumerate(divisors):
        seconds = units[i]
        projected += value * seconds

    if projected <= current:
        # The time is in the past, increase the higher unit
        if higher_unit:
            divisors[higher_unit - 1] += 1
        else:
            divisors[0] += 1

    # Get the projected time again
    projected = 0
    for i, value in enumerate(divisors):
        seconds = units[i]
        projected += value * seconds

    return (projected - current) / TIMEFACTOR
Ejemplo n.º 6
0
    def func(self):
        """ Execute the time command. """

        tempus = datetime.datetime.fromtimestamp(
            gametime.gametime(absolute=True))
        hōra = tempus.hour
        if hōra > 17 or hōra < 6:
            self.msg("Nox est.")
            # set outside rooms as dark
        else:
            self.msg(f"Nunc est hōra {hōra - 5}.")
Ejemplo n.º 7
0
    def ago(self):
        """Return the time since the notification was created."""
        if self.timestamp is None:
            return "now"

        gtime = gametime.gametime(absolute=True)
        seconds = gtime - self.timestamp
        if seconds < 5:
            return "a few seconds ago"

        ago = time_format(seconds, 4)
        return "{} ago".format(ago)
Ejemplo n.º 8
0
    def sent_ago(self):
        """Return the human-readable time since sent (X units ago)."""
        global _GAMETIME
        if not _GAMETIME:
            from evennia.utils import gametime as _GAMETIME

        gtime = datetime.datetime.fromtimestamp(
            _GAMETIME.gametime(absolute=True))
        gtime = make_aware(gtime)

        seconds = (gtime - self.date_sent).total_seconds()
        ago = time_format(seconds, 4)
        return "{} ago".format(ago)
Ejemplo n.º 9
0
    def send(self, sender, recipients, content):
        """Send a text message from `number` to `recipients`.

        Args:
            sender (str): the number (7-digit).
            recipients (list of str): a list of 7-digit strings.
            content (str): the text of the message.

        Returns:
            text (Text): the newly-sent text message.

        """
        global _GAMETIME, _THREAD, _NUMBER
        if not _GAMETIME:
            from evennia.utils import gametime as _GAMETIME
        if not _THREAD:
            from web.text.models import Thread as _THREAD
        if not _NUMBER:
            from web.text.models import Number as _NUMBER

        # First, get the sender's phone number
        recipients = [sender] + recipients
        try:
            sender = _NUMBER.objects.get(db_phone_number=sender)
        except _NUMBER.DoesNotExist:
            sender = _NUMBER(db_phone_number=sender)
            sender.save()

        gtime = datetime.datetime.fromtimestamp(_GAMETIME.gametime(absolute=True))
        gtime = make_aware(gtime)

        # Look for a thread or create one
        thread = _THREAD.objects.get_thread(recipients)
        if thread is None:
            thread = _THREAD()
            thread.save()

            # For every participant, add it as recipient
            for number in recipients:
                try:
                    recipient = _NUMBER.objects.get(db_phone_number=number)
                except _NUMBER.DoesNotExist:
                    recipient = _NUMBER(db_phone_number=number)
                    recipient.save()
                thread.db_recipients.add(recipient)

        thread.db_read.clear()
        thread.db_read.add(sender)
        return thread.text_set.create(
                db_sender=sender, db_content=content, db_date_sent=gtime)
Ejemplo n.º 10
0
    def func(self):
        "Updates the journal"
        caller = self.caller
        location = caller.location
        zone = "A Fake Dungeon"
        time = gametime()
        journal = caller.db.journal
        usage = "+journal <Your entry>"
        if not self.args:
            caller.msg(usage)
            return
        else:
            entry = self.lhs

        journal.append([time, zone, location, entry])
        caller.msg("Added to journal:\n%s" % entry)
Ejemplo n.º 11
0
def get_time(*args, **kwargs):
    time = datetime.datetime.fromtimestamp(gametime.gametime(absolute=True))
    hour = time.hour
    min = time.minute

    ampm = "AM"

    if hour >= 12:
        ampm = "PM"
    if hour > 12:
        hour = hour - 12

    if min < 10:
        min = f"0%s" % (str(min), )

    return f"%s:%s %s" % (hour, min, ampm)
Ejemplo n.º 12
0
 def func(self):
     "Show server time data in a table."
     table = prettytable.PrettyTable(["{wserver time statistic", "{wtime"])
     table.align = 'l'
     table.add_row(
         ["Current server uptime",
          utils.time_format(gametime.uptime(), 3)])
     table.add_row([
         "Total server running time",
         utils.time_format(gametime.runtime(), 2)
     ])
     table.add_row([
         "Total in-game time (realtime x %g)" % (gametime.TIMEFACTOR),
         utils.time_format(gametime.gametime(), 2)
     ])
     table.add_row(["Server time stamp", datetime.datetime.now()])
     self.caller.msg(str(table))
Ejemplo n.º 13
0
def custom_gametime(absolute=False):
    """
    Return the custom game time as a tuple of units, as defined in settings.

    Args:
        absolute (bool, optional): return the relative or absolute time.

    Returns:
        The tuple describing the game time.  The length of the tuple
        is related to the number of unique units defined in the
        settings.  By default, the tuple would be (year, month,
        week, day, hour, minute, second).

    """
    current = gametime.gametime(absolute=absolute)
    units = sorted(set(UNITS.values()), reverse=True)
    del units[-1]
    return time_to_tuple(current, *units)
Ejemplo n.º 14
0
def custom_gametime(absolute=False):
    """
    Return the custom game time as a tuple of units, as defined in settings.

    Args:
        absolute (bool, optional): return the relative or absolute time.

    Returns:
        The tuple describing the game time.  The length of the tuple
        is related to the number of unique units defined in the
        settings.  By default, the tuple would be (year, month,
        week, day, hour, minute, second).

    """
    current = gametime.gametime(absolute=absolute)
    units = sorted(set(UNITS.values()), reverse=True)
    del units[-1]
    return time_to_tuple(current, *units)
Ejemplo n.º 15
0
    def add(self,
            title,
            screen,
            app,
            folder="app",
            content="",
            db=None,
            group=None):
        """Add a new notificaiton.

        Args:
            title (str): title of the notification to add.
            screen (str): screen path when addressing the notification.
            app (str): app name that sent the application.
            folder (str, optional): the folder containing the app.
            content (str, optional): the content of the notification.
            db (dict, optional): db attributes to give to the screen.
            group (str, optional): a group identifier [1].

        [1] Notifications can be grouped using a group identifier.  Notifications
            that have this identifier can be removed.  This is useful in
            some apps that want to remove notifications based on certain
            actions: for instance, if you mark a text as read in the text
            app, you want to remove the unread notification for this thread.

        """
        timestamp = gametime.gametime(absolute=True)
        kwargs = {
            "title": title,
            "screen": screen,
            "app": app,
            "folder": folder,
            "content": content,
            "db": db,
            "group": group,
            "timestamp": timestamp,
        }
        notification = Notification(**kwargs)
        notification.obj = self.obj
        notification.handler = self
        self.db.append(kwargs)
        return notification
Ejemplo n.º 16
0
def return_appearance(type, looker, number=False, header=""):
    """Return the formatted appearance for a phone or computer."""
    phone_number = type.obj.tags.get(category="phone number")
    if not isinstance(phone_number, str):
        phone_number = "|gunset|n"
    else:
        phone_number = phone_number[:3] + "-" + phone_number[3:]

    date = datetime.datetime.fromtimestamp(gametime.gametime(absolute=True))
    text = dedent("""
        {header}


                                             {time}

                                 {date}
        """.strip("\n")).format(
        header=header,
        date=date.strftime("%A, %B {}, %Y".format(date.day)),
        time=date.strftime("%I:%M %p"),
    )

    # If a phone number, display it
    if number:
        text += "\n\n" + """
                                                                     {number}
        """.rstrip("\n").format(number=phone_number)

    # Display the notifications
    notifications = type.notifications.all()
    if notifications:
        text += "\n\n"
        for notification in notifications:
            title = crop(notification.title, 55, "...")
            content = "\n    ".join(wrap(notification.content, 74))
            text += "\n-   {:<55} ({})".format(title, notification.ago)
            if content:
                text += "\n    " + content

    return text
Ejemplo n.º 17
0
    def func(self):
        if not self.args:
            self.caller.msg("You must suply a target for the spell.")
            return
        if (self.args == "Use" or self.args == "use"):
            if (self.caller.db.astro == 0):
                self.caller.db.astro = 1
                self.caller.db.blessed = int(self.caller.db.blessed) + 1
                self.caller.msg("You are aligned with the universe.")
            else:
                self.caller.msg("Try again soon.")
            return

        hit = self.caller.search(self.args)
        if hit:
            t = gametime.gametime(absolute=True)
            tst = time.strftime("%m", time.gmtime(t))

            self.caller.msg("Month: %s" % int(tst))
            self.caller.msg("Star Sign: %s'" % int(hit.db.starsign))
            if (int(tst) == int(hit.db.starsign)):
                self.caller.msg("The stars are aligned for %s." % hit)
        else:
            self.caller.msg("You can't find that person.")
Ejemplo n.º 18
0
 def test_gametime_downtimes(self):
     gametime.IGNORE_DOWNTIMES = True
     self.assertAlmostEqual(gametime.gametime(), 630 * 5.0)
     gametime.IGNORE_DOWNTIMES = False
Ejemplo n.º 19
0
 def test_gametime_absolute(self):
     self.assertAlmostEqual(gametime.gametime(absolute=True), 1555597898.0)
Ejemplo n.º 20
0
 def test_gametime_simple(self):
     self.assertAlmostEqual(gametime.gametime(), 630.0 * 5)
Ejemplo n.º 21
0
 def func(self):
     "Show server time data in a table."
     table = prettytable.PrettyTable(["{wserver time statistic","{wtime"])
     table.align = 'l'
     table.add_row(["Current server uptime", utils.time_format(gametime.uptime(), 3)])
     table.add_row(["Total server running time", utils.time_format(gametime.runtime(), 2)])
     table.add_row(["Total in-game time (realtime x %g)" % (gametime.TIMEFACTOR), utils.time_format(gametime.gametime(), 2)])
     table.add_row(["Server time stamp", datetime.datetime.now()])
     self.caller.msg(str(table))
Ejemplo n.º 22
0
 def test_gametime_absolute(self):
     self.assertAlmostEqual(gametime.gametime(absolute=True),
                            datetime(2019, 4, 18, 14, 31, 38).timestamp())