Skip to content

Instantly share code, notes, and snippets.

@pozil
Last active November 5, 2020 15:14
Show Gist options
  • Save pozil/545583c2c29c05ab5d7b6ed40704d02d to your computer and use it in GitHub Desktop.
Save pozil/545583c2c29c05ab5d7b6ed40704d02d to your computer and use it in GitHub Desktop.
Slack Post Message Invocable Action
{
"openapi": "3.0.0",
"info": {
"version": "1.0.0",
"title": "MuleSoft/Slack Integration Demo"
},
"paths": {
"/slack/message/{channel}/{message}": {
"post": {
"summary": "Post a message to a Slack channel",
"operationId": "postSlackMessage",
"parameters": [
{
"name": "channel",
"in": "path",
"description": "Slack channel to post to",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "message",
"in": "path",
"description": "Message to be posted",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Operation succeeded"
}
}
}
}
}
}
public with sharing class SlackIntegration {
@future(callout=true)
public static void postMessage(String url, String message) {
Map<String, String> body = new Map<String, String>();
body.put('text', message);
String bodyJSON = JSON.Serialize(body);
HttpResponse response = sendRequest(url, 'POST', bodyJSON);
if (response.getStatusCode() != 200) {
throw new SlackException('Failed to post Slack Message ' + response.getBody());
}
}
private static HttpResponse sendRequest(String url, String method, String body) {
HttpRequest request = new HttpRequest();
request.setEndpoint(url);
request.setMethod(method);
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody(body);
return new Http().send(request);
}
public class SlackException extends Exception {
}
}
public with sharing class SlackPostAction {
@InvocableMethod(label='Post a Slack Message' )
public static List<OutputParameters> postMessage(List<InputParameters> inputs) {
List<OutputParameters> outputs = new List<OutputParameters>();
for (InputParameters input : inputs) {
OutputParameters output = new OutputParameters();
try {
SlackIntegration.postMessage(input.namedCredential, input.message);
output.isSuccess = true;
} catch (SlackIntegration.SlackException e) {
output.isSuccess = false;
output.errorMessage = e.getMessage();
}
outputs.add(output);
}
return outputs;
}
/**
* Wrapper class for input parameters
*/
public class InputParameters {
@InvocableVariable(required=true)
public String namedCredential;
@InvocableVariable(required=true)
public String message;
}
/**
* Wrapper class for output parameters
*/
public class OutputParameters {
@InvocableVariable
public Boolean isSuccess;
@InvocableVariable
public String errorMessage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment