Spam prevention
PubNub Anti-Spam function stops users from spamming on your application. This is done by limiting the rate at which messages can be published.
Anti Spam Block rate limits the publish rate from any IP address. The limit is configurable. The block keeps track of the times of published messages, and allows a message to get published only if the IP address doesn't cross the maximum number of messages allowed.
Setting up the PubNub Function
Create a new function. Go to your Admin Portal and create a new module, and then create a new Before Publish function. Set up the function to trigger on a specific channel (such as
spam-blocker-channel
), a set of channels (such aschat.*
), or on all channels using wildcards (*
).Copy the function code below. Make changes as necessary to the dictionary, and configure the function to either replace the swear words, or block the entire message from being published on the channel.
// Requires the console module const console = require('console'); const store = require('kvstore'); export default (request) => { // Window, aggregation period const aggregationWindow = 120; // Seconds // Duration const duration = 60; // Seconds // No of messages const noOfMessages = 5; // Since this is an after-publish event handler, we can't modify the // message let messageAllowed = false; // Check if an auth value exists in the incoming message // Messages without metadata will be discarded by returning null if (typeof request.params.auth === 'undefined') { request.status = 400; return request.abort('Message Dropped'); } const currentTime = Math.round(Date.now() / 1000); return store.get('anti_spam').then((value) => { let antiSpamAuth = value && value.auth || {}; const aggregationStart = value && value.aggregation_start || 0; if (currentTime - aggregationStart > aggregationWindow) { antiSpamAuth = {}; } // get auth value var authValue = request.params.auth; if (!authValue) { request.status = 400; return request.abort('Message Dropped'); } var authMessages = antiSpamAuth[authValue] || []; var oldestMessageTime = authMessages[0]; if ((currentTime - oldestMessageTime) > duration || authMessages.length < noOfMessages) { messageAllowed = true; } if (!messageAllowed) { request.status = 400; return request.abort('Message Dropped'); } if (authMessages.length === noOfMessages) { authMessages.shift(); } authMessages.push(currentTime); antiSpamAuth[authValue] = authMessages; store.set('anti_spam', { auth: antiSpamAuth, aggregation_start: currentTime }); return request.ok(); }) .catch((e) => { console.error(e); }); }
Click Start module on the right to start the function, and test it using the Test Payload field and Publish button on the left.
Testing the Function
Input: Publish a message text on the input channel: spam-blocker-channel
{
"text": "Hi"
}
Output: If the message rate is exceeded a 400 error will be returned.
{
"message": "Message Dropped",
"error": true,
"status": 400
}