Example #1
0
def main():
    db = connect()

    # Keep a cache of recently notified trains.
    recent_notify = dict()

    while True:
        time.sleep(5)

        # Trains leaving within 2 minutes
        two_mins = datetime.utcnow() + timedelta(minutes=2)
        for train in db.query(Train).filter(Train.expires >= datetime.utcnow())\
                                    .filter(Train.expires <= two_mins)\
                                    .all():
            if train.id in recent_notify:
                continue

            print("Notify Slack: train {} is leaving soon".format(train.name))
            train_name = train.name
            if not train_name.lower().endswith("train"):
                train_name += " Train"

            # Get Slack names to ping.
            users = get_users([m.username for m in train.passengers])

            # Notify Slack
            post_message("*All aboooaaarrrd!* :train2:\n\n"
                "The *{name}* is leaving within 2 minutes! *Choo Choo!* "
                ":train: :dash: :dash:".format(
                name=train_name
                ), users)

            # Cache it so we don't notify twice within about 5 minutes
            recent_notify[train.id] = time.time()

        # Clear the cache of recent trains.
        for train_id, last_notify in recent_notify.items():
            if time.time() - last_notify > (5*60):
                del recent_notify[train_id]
                continue
Example #2
0
def make_train(name, expires):
    """Make a new train."""

    # Turn expiration into a datetime.
    expiration = datetime.utcnow() + timedelta(seconds=expires)

    # Make the train.
    train = Train(
        name=name,
        owner=g.user.id,
        expires=expiration,
    )
    train.passengers.append(g.user) # Creator is automatically on board
    g.db.add(train)
    g.db.commit()

    pingback = url_for("index", _external=True).strip("/") + "/#/?train={}".format(
        train.id
    )

    # Notify Slack
    train_name = name
    if not train_name.lower().endswith("train"):
        train_name += " Train"
    post_message("*A train has pulled into the station!* :train:\n\n"
        "{user} has created the *{name}*! Board the train at <{url}>\n"
        "It leaves the station in *{expires} minute{pl}*!".format(
            user=g.user.username.split("@")[0],
            name=train_name,
            url=pingback,
            expires=int(expires / 60),
            pl="s" if int(expires / 60) != 1 else "",
        )
    )

    return resp(train.serialize), CREATED