Chat: Presence and Group Chats
Presence is knowing who is online at a given moment. This lesson deep-dives into presence and into group chats.
A heartbeat keeping a user marked online
Scripted heartbeats arrive at a fixed interval while the app stays open. The printout checks the gap since the last heartbeat at scripted check times.
heartbeats = [0, 30, 60]
checks = [60, 89, 91]
for now in checks:
last = max(t for t in heartbeats if t <= now)
gap = now - last
status = "online" if gap <= 30 else "offline"
print("at", now, "last heartbeat", last, "gap", gap, status)Sorting a contact list by last heartbeat
Each contact has a scripted last heartbeat time. The printout splits the contacts into online and offline at one scripted moment.
last_seen = {"Ana": 95, "Bo": 40, "Cy": 100, "Dee": 10}
now = 100
online = sorted(name for name, t in last_seen.items() if now - t <= 30)
offline = sorted(name for name, t in last_seen.items() if now - t > 30)
print("online:", online)
print("offline:", offline)One group message copied to each member
One member sends a single message to a small group. The printout shows the copy waiting in each other member inbox and the total copies made.
members = ["Ana", "Bo", "Cy", "Dee"]
sender = "Ana"
inboxes = {name: [] for name in members if name != sender}
message = "practice moves to Saturday"
for name in inboxes:
inboxes[name].append(message)
total = 0
for name in sorted(inboxes):
total += len(inboxes[name])
print(name, "has", len(inboxes[name]), "copy")
print("total copies:", total)Example
members = ["Ana", "Bo", "Cy", "Dee"]
sender = "Ana"
last_seen = {"Bo": 98, "Cy": 95, "Dee": 20}
now = 100
instant = 0
waiting = 0
for name in members:
if name == sender:
continue
if now - last_seen[name] <= 30:
instant += 1
print(name, "- online, copy delivered at once")
else:
waiting += 1
print(name, "- offline, copy waits in storage")
print("delivered at once:", instant)
print("waiting:", waiting)Key points
- Online presence: the live record the service keeps of which users are online now.
- Heartbeat: a small still-here message a phone sends at a fixed interval while the app is open.
- Heartbeat interval: this design uses one heartbeat every 30 seconds.
- Last seen: the time of the latest heartbeat from a phone, kept by the server.
- Stale presence: presence built from a last heartbeat that is too old to trust.
- Group delivery: one sent message is copied to each member of the group.
In this example, presence decides how each copy of one group message travels. Online members get a copy at once, and the offline member copy waits in storage until that member returns.
Note
presence can be briefly wrong, so the app treats it as a guide rather than a promise.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What tells the server that a phone is still online while the app stays open?