Search code examples
javascriptpubnub

PubNub - send a "welcome" connection message


What's the best way to handle sending a message directly to the user once they connect to the socket?

Basically a "The word of the day is: Frog", but is only sent to the user that just connected.

My assumption is they'll join the global channel and also a channel that matches their uuid beholden-trans-am. Users are all anonymous (this is a public stream on a website)

Thanks for any pointers!


Solution

  • Hard-code in the Connected Status Event

    If you just want to say "welcome" every time a client is connected to a new channel, you can just hard-code that message into the status callback's PNConnectedCategory event, like this:

    status: function(event) {
      if (event.category == 'PNConnectedCategory') {
        displayMessage('Welcome to channel, : ' + event.affectedChannels);
      }
    }
    
    • If you subscribe to multiple channels at once then all of those channels will be in the affectedChannels property.
    • displayMessage is a custom function that you implement that displays the message somewhere in your UI. This code was pulled from the PubNub JavaScript Quickstart app so you can use that to get started quick :)

    Presence Webhooks Server Side Handling

    This is essentially the same solution but from your server. You can leverage Presence Webhooks so that your server is notified when a subscriber joins a channel (a presence join event) on any channel.

    Your server code (Node example here) would look something like this:

    app.post("/myapp/api/v1/wh/presence", (request, response) => {
        var event = request.body;
        console.info('entering presence webhook for uuid/user: ' + event.uuid);
    
        if ((!event) || (!event.action) || (!event.uuid)) {
            console.info("could not process event: " + JSON.stringify(event));
            response.status(200).end();
            return;
        }
        if (event.action === "join") {
            console.info(event.uuid + " has join " + event.channel);
    ////////////////////////////////////////////////////////
    // THIS IS WHERE YOU ADD YOUR WELCOME MESSAGE CODE
    ////////////////////////////////////////////////////////
          pubnub.publish({
            channel : event.channel,
            message : {'welcome' : "Welcome to channel, " + event.channel}
          },
          function(status, response) {
            // success/error check code goes here
          });
        }
    
        if (event.action === "state-change" && event.state) {
            console.info("state changed for " + event.uuid 
                + " new state " + event.state);
        }
    
        if ((event.action === "leave") || (event.action === "timeout")) {
            console.info(event.uuid + " has left or isn't reachable");
            // use pubnub.wherenow() if needed.
        }
    
        response.status(200).end();
    });
    

    Publish Caveat

    If you publish to the channel that the user just joined and there are other users subscribed to that channel, then everyone will get that Welcome message, so you probably want to publish the message to a channel that only the joining user is subscribed to. This should be some well-known "private" channel (at least well-known to your server). Maybe this channel is the UUID of the user, so you could publish the message like this:

    pubnub.publish({
        channel : event.uuid, // use the UUID as the channel name
        message : {'welcome' : "Welcome to channel, " + event.channel}
    },
    

    Further Assistance

    I hope this provides some insights into how you can implement this. If you still have further questions, just contact PubNub Support and provide full details about what you are trying to do and reference this SO post if it is applicable.