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 case | Who | How it works | Status |
|---|---|---|---|
| Instant alert on a new High priority Case | Support team | Trigger after insert sends one message per batch through a future method | Built Proven end to end |
| Daily digest of open Cases by priority | Team lead | Scheduled Apex at 8:00 counts open Cases and posts the totals | Built Scheduled. A manual send was seen in Slack |
| Alert when a Case is escalated | Support team | Extend the trigger to fire on a status change | Next |
| Link to the Case in each message | Support team | Add the record URL to the message text | Next |
| Different channels by priority or product | Support team | Store several webhooks, pick one per rule | Next |
| SLA breach warning | Team lead | Needs entitlement or milestone data | Next |
| Digest per owner or queue | Agents | Group the digest query by owner | Next |
| Use the Case Triage agent from Slack | Support staff | Needs the Salesforce and Slack integration, which may not be available on a free Slack plan | Option Unconfirmed |
| Approve or reassign from a Slack button | Support staff | Needs a custom Slack app, not a webhook | Out of scope |
| Post customer personal data | Anyone | Messages carry case number and subject only | Out of scope |
Architecture: Salesforce to Slack
Live, tested end to endTwo 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.
force-app/main/default/classes/SlackCaseNotifier.cls
/**
* 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.cls
/**
* 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.trigger
trigger CaseSlackAlertTrigger on Case (after insert) {
SlackCaseNotifier.alertHighPriority(Trigger.new);
}force-app/main/default/labels/CustomLabels.labels-meta.xml
<?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.xml
<?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.cls
@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
| Check | Result |
|---|---|
| Apex unit tests | 4 pass: digest counts, no send without a webhook, one post per High priority insert batch, digest job posts |
| Test message | Slack answered 200 and the message appeared in the channel |
| Digest and alert through the real class | Both appeared in the channel with the right counts and Case numbers |
| Trigger on a new Case | A High priority test Case queued the send job, it completed, and the alert appeared in Slack. The test Case was then deleted |
| Webhook label overwritten | A 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 planThe 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.
Setup: who does what
The Chrome instructions in docs/slackforce-chrome-instructions.md split the work so that secrets and approvals stay with you.
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
| Topic | What to know |
|---|---|
| Webhook secret | Anyone 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 scope | The 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 batch | A bulk load of 200 High priority Cases sends one message listing them, not 200 messages. |
| Asynchronous | Sending runs in a future method, so a Slack outage never blocks saving a Case. A failed post is not retried. |
| Message content | Case 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 timing | The 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 label | The 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 plan | Incoming webhooks are available. The native Agentforce in Slack integration may not be. This has not been checked. |
| Agent in Slack | Case Triage Assistant can change a Case's priority. Limit who can reach it, and keep its confirmation step. |
Open items
- Confirm the first scheduled 8:00 digest arrives on its own.
- Rotate the webhook if its URL was ever shared, then paste the new one into the label.
- Run Part 2 of the Chrome instructions to find out whether the Slack integration is available on this plan.
- Decide who in Slack may use the Case Triage agent, if it is enabled.
- For production, replace the label with a Named Credential.