Newer Version Available

This content describes an older version of this product. View Latest

Moderate Chatter Private Messages with Triggers

Write a trigger for ChatterMessage to automate the moderation of private messages in an org or Experience Cloud site. Use triggers to ensure that messages conform to your company’s messaging policies and don’t contain blocklisted words.
Available in: Salesforce Classic
Available in: Enterprise, Performance, Unlimited, and Developer Editions

User Permissions Needed
To save Apex triggers for ChatterMessage: Author Apex

AND

Manage Chatter Messages and Direct Messages

Write an Apex before insert trigger to review the private message body and information about the sender. You can add validation messages to the record or the Body field, which causes the message to fail and an error to be returned to the user.

Although you can create an after insert trigger, ChatterMessage is not updatable, and consequently any after insert trigger that modifies ChatterMessage will fail at run time with an appropriate error message.

To create a trigger for private messages from Setup, enter ChatterMessage Triggers in the Quick Find box, then select ChatterMessage Triggers. Alternatively, you can create a trigger from the Developer Console by clicking File | New | Apex Trigger and selecting ChatterMessage from the sObject drop-down list.

This table lists the fields that are exposed on ChatterMessage.

Table 1. Available Fields in ChatterMessage
Field Apex Data Type Description
Id ID Unique identifier for the Chatter message
Body String Body of the Chatter message as posted by the sender
SenderId ID User ID of the sender
SentDate DateTime Date and time that the message was sent
SendingNetworkId ID Network (site) in which the message was sent.

This field is visible only if digital experiences is enabled and Private Messages is enabled in at least one site.

This example shows a before insert trigger on ChatterMessage that is used to review each new message. This trigger calls a class method, moderator.review(), to review each new message before it is inserted.

If a message violates your policy, for example when the message body contains blocklisted words, you can prevent the message from being sent by calling the Apex addError method. You can call addError to add a custom error message on a field or on the entire message. The following snippet shows a portion of the reviewContent method that adds an error to the message Body field.

The following is the full MessageModerator class, which contains methods for reviewing the sender and the content of messages. Part of the code in this class has been deleted for brevity.