Slack workspace aiforall · Salesforce org afdcnew

Slackforce: Salesforce and Slack together

How Salesforce posts case alerts and a daily digest into Slack, how the Case Triage agent could be reached from Slack, and who does each setup step.

Where things stand

Live Alerts

  • A new High priority Case posts an alert to Slack on its own
  • Proven: a test Case fired the trigger and the alert arrived
  • The test Case was deleted afterwards

Live Daily digest

  • Scheduled for 8:00 every day, in the time zone of the user who scheduled it
  • A manual send was seen in Slack: High 5, Medium 4, Low 5
  • The first scheduled run is the next 8:00

Unconfirmed Agent in Slack

  • The Salesforce and Slack integration may not be available on a free Slack plan
  • Not checked. The Chrome instructions include a step that finds out

What Slackforce is for

Slackforce pushes information to people where they already work. A rule in Salesforce fires, Apex builds a short message, and Slack shows it. There is no AI at run time and the same event always produces the same kind of message. Use it for awareness, not for conversation.

Meant for

  • Telling a team about urgent items as they happen
  • A daily summary the team does not have to ask for
  • Small teams that live in Slack
  • One-way notifications, simple to operate and audit

Not meant for

  • Conversation or questions. Use Agentforce.
  • Approvals, buttons or threads. A webhook is one-way, so that needs a full Slack app.
  • Reading what people write in Slack
  • Very high event volumes, because Salesforce limits callouts

Use cases

Use caseWhoHow it worksStatus
Instant alert on a new High priority CaseSupport teamTrigger after insert sends one message per batch through a future methodBuilt
Proven end to end
Daily digest of open Cases by priorityTeam leadScheduled Apex at 8:00 counts open Cases and posts the totalsBuilt
Scheduled. A manual send was seen in Slack
Alert when a Case is escalatedSupport teamExtend the trigger to fire on a status changeNext
Link to the Case in each messageSupport teamAdd the record URL to the message textNext
Different channels by priority or productSupport teamStore several webhooks, pick one per ruleNext
SLA breach warningTeam leadNeeds entitlement or milestone dataNext
Digest per owner or queueAgentsGroup the digest query by ownerNext
Use the Case Triage agent from SlackSupport staffNeeds the Salesforce and Slack integration, which may not be available on a free Slack planOption
Unconfirmed
Approve or reassign from a Slack buttonSupport staffNeeds a custom Slack app, not a webhookOut of scope
Post customer personal dataAnyoneMessages carry case number and subject onlyOut of scope

Architecture: Salesforce to Slack

Live, tested end to end

Two things start a message: a new Case with High priority, and a daily schedule. Both build a short text and pass it to one class, SlackCaseNotifier. That class reads the webhook URL from a protected custom label. If the label still says REPLACE_ME, it stops. Otherwise it posts the text as JSON to the Slack webhook, which puts it in the channel chosen when the webhook was created.

SALESFORCE SLACK New CasePriority = High Daily schedulecron 0 0 8 * * ? CaseSlackAlertTriggerafter insert SlackCaseDigestJobSchedulable SlackCaseNotifier buildAlert / buildDigest label unset? stop send() builds JSON body @future(callout=true) one message per insert batch Label Slack_Webhook_Urlprotected, holds the secret URL Remote sitehooks.slack.comallows the callout Incoming webhook app: Salesforce Case Alerts #aiforall-central or the channel you pick plain text message POST alert digest
The only secret is the webhook URL, held in a custom label that any admin can read. It is read when a message is sent and never appears in code. The callout runs asynchronously, so saving a Case does not wait for Slack.
force-app/main/default/classes/SlackCaseNotifier.cls66 lines
/**
 * Posts Case summaries to Slack through an incoming webhook.
 * The webhook URL lives in the protected custom label Slack_Webhook_Url.
 * While the label still says REPLACE_ME, nothing is sent.
 */
public with sharing class SlackCaseNotifier {
    @TestVisible
    private static String webhookOverride;

    private static String webhookUrl() {
        String url = webhookOverride != null ? webhookOverride : Label.Slack_Webhook_Url;
        return (String.isBlank(url) || url == 'REPLACE_ME') ? null : url;
    }

    public static String buildDigest() {
        List<AggregateResult> rows = [
            SELECT Priority p, COUNT(Id) n FROM Case WHERE IsClosed = FALSE GROUP BY Priority
        ];
        Map<String, Integer> counts = new Map<String, Integer>{ 'High' => 0, 'Medium' => 0, 'Low' => 0 };
        for (AggregateResult r : rows) {
            counts.put((String) r.get('p'), (Integer) r.get('n'));
        }
        return ':clipboard: *Daily case digest*\n' +
            ':red_circle: High: ' + counts.get('High') + '\n' +
            ':large_orange_circle: Medium: ' + counts.get('Medium') + '\n' +
            ':large_green_circle: Low: ' + counts.get('Low');
    }

    public static String buildAlert(List<Case> cases) {
        List<String> lines = new List<String>();
        for (Case c : cases) {
            lines.add('• ' + c.CaseNumber + ' - ' + c.Subject);
        }
        return ':rotating_light: *New High priority case(s)*\n' + String.join(lines, '\n');
    }

    public static void send(String text) {
        String url = webhookUrl();
        if (url == null) {
            return;
        }
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(JSON.serialize(new Map<String, String>{ 'text' => text }));
        new Http().send(req);
    }

    @future(callout=true)
    public static void sendAsync(String text) {
        send(text);
    }

    public static void alertHighPriority(List<Case> cases) {
        List<Case> high = new List<Case>();
        for (Case c : cases) {
            if (c.Priority == 'High') {
                high.add(c);
            }
        }
        if (!high.isEmpty() && webhookUrl() != null && !System.isFuture() && !System.isBatch()) {
            sendAsync(buildAlert(high));
        }
    }
}
force-app/main/default/classes/SlackCaseDigestJob.cls9 lines
/**
 * Schedulable job that posts the daily case digest to Slack.
 * Schedule: System.schedule('Slack case digest', '0 0 8 * * ?', new SlackCaseDigestJob());
 */
public with sharing class SlackCaseDigestJob implements Schedulable, Database.AllowsCallouts {
    public void execute(SchedulableContext sc) {
        SlackCaseNotifier.sendAsync(SlackCaseNotifier.buildDigest());
    }
}
force-app/main/default/triggers/CaseSlackAlertTrigger.trigger3 lines
trigger CaseSlackAlertTrigger on Case (after insert) {
    SlackCaseNotifier.alertHighPriority(Trigger.new);
}
force-app/main/default/labels/CustomLabels.labels-meta.xml10 lines
<?xml version="1.0" encoding="UTF-8"?>
<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
    <labels>
        <fullName>Slack_Webhook_Url</fullName>
        <language>en_US</language>
        <protected>true</protected>
        <shortDescription>Slack incoming webhook URL</shortDescription>
        <value>REPLACE_ME</value>
    </labels>
</CustomLabels>
force-app/main/default/remoteSiteSettings/Slack_Hooks.remoteSite-meta.xml6 lines
<?xml version="1.0" encoding="UTF-8"?>
<RemoteSiteSetting xmlns="http://soap.sforce.com/2006/04/metadata">
    <disableProtocolSecurity>false</disableProtocolSecurity>
    <isActive>true</isActive>
    <url>https://hooks.slack.com</url>
</RemoteSiteSetting>
force-app/main/default/classes/SlackCaseNotifierTest.cls58 lines
@IsTest
private class SlackCaseNotifierTest {
    private class Mock implements HttpCalloutMock {
        public Integer calls = 0;
        public HttpResponse respond(HttpRequest req) {
            calls++;
            HttpResponse res = new HttpResponse();
            res.setStatusCode(200);
            return res;
        }
    }

    @IsTest
    static void digestCountsOpenCasesByPriority() {
        insert new List<Case>{
            new Case(Subject = 'a', Status = 'New', Priority = 'High'),
            new Case(Subject = 'b', Status = 'New', Priority = 'Low')
        };
        String d = SlackCaseNotifier.buildDigest();
        Assert.isTrue(d.contains('High: 1'));
        Assert.isTrue(d.contains('Low: 1'));
    }

    @IsTest
    static void doesNothingWithoutWebhook() {
        Mock m = new Mock();
        Test.setMock(HttpCalloutMock.class, m);
        Test.startTest();
        insert new Case(Subject = 'c', Status = 'New', Priority = 'High');
        Test.stopTest();
        Assert.areEqual(0, m.calls);
    }

    @IsTest
    static void highPriorityInsertPostsOnce() {
        SlackCaseNotifier.webhookOverride = 'https://hooks.slack.com/services/T/B/X';
        Mock m = new Mock();
        Test.setMock(HttpCalloutMock.class, m);
        Test.startTest();
        insert new List<Case>{
            new Case(Subject = 'd', Status = 'New', Priority = 'High'),
            new Case(Subject = 'e', Status = 'New', Priority = 'Low')
        };
        Test.stopTest();
        Assert.areEqual(1, m.calls);
    }

    @IsTest
    static void digestJobPosts() {
        SlackCaseNotifier.webhookOverride = 'https://hooks.slack.com/services/T/B/X';
        Mock m = new Mock();
        Test.setMock(HttpCalloutMock.class, m);
        Test.startTest();
        new SlackCaseDigestJob().execute(null);
        Test.stopTest();
        Assert.areEqual(1, m.calls);
    }
}

What was tested

CheckResult
Apex unit tests4 pass: digest counts, no send without a webhook, one post per High priority insert batch, digest job posts
Test messageSlack answered 200 and the message appeared in the channel
Digest and alert through the real classBoth appeared in the channel with the right counts and Case numbers
Trigger on a new CaseA High priority test Case queued the send job, it completed, and the alert appeared in Slack. The test Case was then deleted
Webhook label overwrittenA project deploy reset the label to its placeholder once, so the first trigger test sent nothing. In the working project the label file is now excluded in .forceignore. The published repo does not do this, so add that line yourself after you set the webhook (README step 8)

Architecture: the agent from Slack

Unconfirmed, depends on the org and plan

The Salesforce and Slack native integration lets people in Slack talk to a Salesforce agent. If it is available here, a person in Slack would message the agent, Salesforce would run Case_Triage_Assistant and its Apex actions, and the answer would come back into Slack. Solid boxes already exist. Dashed boxes depend on the integration being available and switched on.

Person in Slackasks about cases Slack and Salesforceintegration Case TriageAssistant Apex actionslist · set priority Case records reply returns to the Slack conversation
The agent side is built and tested. What is missing is the connection from Slack, which the Chrome instructions check for. The agent edits Cases, so decide who in Slack may use it before enabling it.
If the integration is not available. The alerts above still work with only a webhook. For a two-way Slack bot on a free plan the alternative is a custom Slack app that calls the Salesforce API. That is a larger build and is not started.

Setup: who does what

The Chrome instructions in docs/slackforce-chrome-instructions.md split the work so that secrets and approvals stay with you.

YOU CHROME CODE 1 Create app,enable webhook 2 Say yes, click Allowchoose the channel 3 Copy the URL, pasteinto the label yourself 4 Save thelabel 5 Test message,schedule digest
Step 3 is yours on purpose. A webhook URL works like a password, so it goes from the Slack page to the Salesforce field without passing through Claude.

Test and operate

# 1. after the label is saved: send a test message from Salesforce
echo "SlackCaseNotifier.send('Test from Salesforce');" > /tmp/slack_test.apex
sf apex run -o afdcnew -f /tmp/slack_test.apex

# 2. check the alert path: create a High priority Case, expect one Slack message
# 3. schedule the digest (8:00 in the time zone of the user who schedules it)
System.schedule('Slack case digest', '0 0 8 * * ?', new SlackCaseDigestJob());

# stop the digest: find the job, then abort it
SELECT Id, CronJobDetail.Name FROM CronTrigger WHERE CronJobDetail.Name = 'Slack case digest'
System.abortJob('<CronTrigger Id>');

# deploy again, with only the Slack tests
sf project deploy start -o afdcnew -m CustomLabel:Slack_Webhook_Url -m RemoteSiteSetting:Slack_Hooks \
  -m ApexClass:SlackCaseNotifier -m ApexClass:SlackCaseDigestJob -m ApexClass:SlackCaseNotifierTest \
  -m ApexTrigger:CaseSlackAlertTrigger -l RunSpecifiedTests -t SlackCaseNotifierTest

Security, limits and behaviour

TopicWhat to know
Webhook secretAnyone with the URL can post to that channel. It lives in a custom label, which any admin, and any Apex code in the org, can read. For production move it to a Named Credential, and rotate it in Slack if it leaks.
Trigger scopeThe trigger runs on every Case insert in the org. It sends nothing unless the label is set and at least one new Case is High priority.
One message per batchA bulk load of 200 High priority Cases sends one message listing them, not 200 messages.
AsynchronousSending runs in a future method, so a Slack outage never blocks saving a Case. A failed post is not retried.
Message contentCase number and subject only, as plain text. Subjects go to Slack, so avoid sensitive text in subjects, or remove the subject from the alert.
Digest timingThe schedule uses the time zone of the user who scheduled the job. The digest counts open Cases by priority at run time.
Deploys can reset the labelThe label value lives in the org, but the file in source says REPLACE_ME. A full project deploy overwrites the saved webhook. Add the label file to .forceignore after you create it.
Free Slack planIncoming webhooks are available. The native Agentforce in Slack integration may not be. This has not been checked.
Agent in SlackCase Triage Assistant can change a Case's priority. Limit who can reach it, and keep its confirmation step.

Open items

  1. Confirm the first scheduled 8:00 digest arrives on its own.
  2. Rotate the webhook if its URL was ever shared, then paste the new one into the label.
  3. Run Part 2 of the Chrome instructions to find out whether the Slack integration is available on this plan.
  4. Decide who in Slack may use the Case Triage agent, if it is enabled.
  5. For production, replace the label with a Named Credential.