Mentioning users
Mentions enable users to get notified when their @username
is mentioned in a chat room. You can build logic on the client to directly parse messages and trigger these notifications to user channels. Or, if you prefer to keep your user channels secure, you can use Functions to parse messages and publish these notifications.
PubNub's User Mentions Function parses all messages that travel through the chat channels. If @username
is detected, the same message is forwarded to the @username
channel. The original message still reaches the intended target. Every user should have their own @username
channel, locked down with Access Manager such that only they can access it.
Set up the PubNub Function
To add the PubNub Function, do the following:
-
Create a new function. Go to your Admin Portal and create a new module, and then create a new After Publish function. The function should be set up to trigger on a specific set of channels (such as
chat.*
) or on all channels using wildcards (*
). -
Copy the function code. Copy the code that checks the contents of each message for
@username
mentions and publishes those messages to the@username
channel. You can add custom logic to the function to find the appropriate user channels to forward messages.
show all 26 linesexport default (request) => {
var console = require('console');
var pubnub = require('pubnub');
try {
var message = request.message;
var pattern = /\B@[a-z0-9_-]+/gi;
var usernames = message.match(pattern);
// for every username found, forward the message to a channel
// with the same name (ex: "@username")
usernames.forEach(function(username) {
pubnub.publish({
channel: username,
message: message -
Start the function. Click Start module to start the function, and test it using the Publish button and Test Payload field on the left.
For more information on creating functions, refer to Create a Function.
Test the Function
Input: A message is published on the input channel.
"A message that mentions a @username"
Output: Note that the message is identical, but the new message has been duplicated and sent to a channel called @username
.
"A message that mentions a @username"