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.
show all 77 lines// 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 -
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
}