Moderate Chatter Private Messages with Apex Triggers

The ChatterMessage object now supports triggers, which enable you to automate private message moderation in an organization or community. For example, use triggers to ensure that messages conform to your company’s messaging policies and don’t contain blacklisted words.
Available in: Enterprise, Performance, Unlimited, and Developer Editions

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

AND

“Manage Chatter Messages”

To create a trigger for private messages from Setup, click Customize | Chatter | Triggers | 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.

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.

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 (Community) in which the message was sent.

This field is visible only if communities are enabled and Private Messages are enabled in at least one community.

Example

This example shows a before insert trigger on ChatterMessage that’s used to review each new message.
trigger PrivateMessageModerationTrigger on ChatterMessage (before insert) {
    ChatterMessage[] messages = Trigger.new;
    
    for (ChatterMessage currentMessage : messages) {
        // Review current message  
    }
}

If a message violates your policy, for example when the message body contains blacklisted 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 code snippet shows how to add an error to the message Body field.

if (moderator.isMessageUnacceptable(currentMessage)) {
    currentMessage.Body.addError('This message violates the acceptable use policy.');
}