IN THIS ARTICLE
Subscribe to Our Newsletter
In this blog post, we’ll give you a tutorial on how to send a self-destructing message. Once messages are sent in the chat application, they automatically delete themselves after a predetermined amount of time.
Here’s what we’ve covered so far:
- Part One: Set up a chat application and gave an overview of its architecture.
- Part Two: Built a key exchange system, enabling you to share public keys between users.
- Part Three: Walked you through how to send TLS encrypted chat messages.
- Part Five: Building a chatroom UI
This is a five part series on building Babel, an open source chat widget and API built with PubNub. Babel allows you to send and receive self destructing, encrypted chat messages and exchange 1024-bit RSA public keys in a chatroom.
How to Send a Self-Destructing Message
Step 2: Finding Users Using PubNub Presence
The first step in sending self destructing messages is to find another user to chat with. As shown in previous blog posts, this can be done quite easily with PubNub Presence. Presence allows you to detect whether users are online or offline in realtime.
We subscribe to a PubNub channel and also declare two functions,
onPresence, that we’ll initialize later when we need to.
onPresence will be called whenever someone joins or leaves this PubNub channel. Thus, we’ll initialize it so that it calls
here_now(), which returns a list of all currently connected users. Then we’ll store that list as the variable
Step 3: Sending a Self-Destructing Message
Once we’ve found another user on our PubNub channel, we can send him a message by publishing a message onto the PubNub channel. The messages will be objects with recipient, sender, message, and ttl properties. The recipient property allows our recipient to know that this message is intended for him, and the sender property let’s him know that we were the ones who sent the message. The message property is the actual text of the message, and ttl is the number of seconds before the message self destructs.
Step 4: Self Destruction of the Messages
Now that we can send messages, we also want to make these messages self destruct. We can achieve this with the
setInterval calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
Thus, we will initialize
onMessage so that it stores all the messages we receive, uses the
setInterval method to update the
TTL values of each message every second, and eventually deletes each message once their TTLs have expired.
Sending a Self-Destructing Message Demo
Stay tuned for the final part of this blog series, were I’ll show you how to implement these pretty effects and build a chatroom UI.