Apex SDK for Slack (Beta)
Documentation Changelog
Project Structure
App Metadata
Assets
Event Handling
Event Subscriptions
Integration Users
Event Examples
Data Providers
Expressions
Input Validation
Permission Scopes
Considerations and Limitations
Customize your app’s behavior in response to activities in Slack. Here are a few event handling examples to help you get started.
Before you can handle an event, subscribe to the event in your app manifest and register the event handler.
Most of these examples are available in the sample Apex SDK for Slack app.
Tip
This example displays a message in the App Home.
1# ApexSlackApp.slackapp
2# Other app configuration here
3# Register event handlers
4events:
5 app_home_opened:
6 action:
7 definition: apex__action__EventDispatcherAppHomeOpened
8 title: Example event handler for app_home_opened
9 description: The event fires when a user opens the home tab.The app_home view is published using Slack.ViewsPublishRequest and Slack.ViewsPublishResponse.
1# app_home.view
2description: "This is a simple app home"
3schema:
4 properties:
5 bodyText:
6 type: string
7 required: true
8 headerText:
9 type: string
10 defaultValue: "Welcome Home"
11components:
12 - definition: home
13 components:
14 - definition: header
15 properties:
16 text: "{!view.properties.headerText}"
17 - definition: section
18 properties:
19 text:
20 type: "mrkdwn"
21 text: "{!view.properties.bodyText}"
22 - definition: dividerSet the expression values in the event handler using the Slack.ViewReference class.
1public class EventDispatcherAppHomeOpened extends Slack.EventDispatcher {
2 public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
3 return Slack.ActionHandler.ack(new Handler(parameters, context));
4 }
5
6 public class Handler implements Slack.RunnableHandler {
7 Slack.EventParameters parameters;
8 Slack.RequestContext context;
9
10 public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
11 this.parameters = parameters;
12 this.context = context;
13 }
14
15 public void run() {
16 // Name must match the DeveloperName of your SlackApp.
17 Slack.App app = Slack.App.ApexSlackApp.get();
18 Slack.BotClient botClient = app.getBotClientForTeam(context.getTeamId());
19 Slack.AppHomeOpenedEvent appHomeOpened = (Slack.AppHomeOpenedEvent) parameters.getEvent();
20 String userId = appHomeOpened.getUser();
21
22 Slack.ViewReference viewReference = Slack.View.app_home.get();
23 viewReference.setParameter('headerText', 'Welcome to the Apex Slack App Example.');
24 viewReference.setParameter('bodyText', 'To see how this custom home view was created, see the EventDispatcherAppHomeOpened apex class.');
25 Slack.HomeView homeView = new Slack.HomeView.builder().viewReference(viewReference).build();
26
27 Slack.ViewsPublishRequest req = new Slack.ViewsPublishRequest.builder().userId(userId).view(homeView).build();
28
29 Slack.ViewsPublishResponse response = botClient.viewsPublish(req);
30 if (response.getError() != null) {
31 System.debug(response.getResponseMetadata().getMessages());
32 }
33 }
34 }
35}This example responds to a channel (public or private) rename by posting a message.
1# ApexSlackApp.slackapp
2# Other app configuration here
3# Register event handlers
4events:
5 channel_rename:
6 action:
7 definition: apex__action__RenameEventExample
8 title: Example channel rename event
9 description: example event that fires when a user renames a channel.
10 group_rename:
11 action:
12 definition: apex__action__RenameEventExample
13 title: Example channel rename event
14 description: example event that fires when a user renames a channel.Get the event parameters using the Slack.Event class and check if the event is an instance of the Slack.ChannelRenameEvent or Slack.GroupRenameEvent class.
1public class RenameEventExample extends Slack.EventDispatcher {
2 public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
3 return Slack.ActionHandler.ack(new Handler(parameters, context));
4 }
5
6 public class Handler implements Slack.RunnableHandler {
7 Slack.EventParameters parameters;
8 Slack.RequestContext context;
9
10 public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
11 this.parameters = parameters;
12 this.context = context;
13 }
14
15 public void run() {
16 // Name must match the DeveloperName of your SlackApp.
17 Slack.App app = Slack.App.ApexSlackApp.get();
18 Slack.BotClient botClient = app.getBotClientForTeam(this.context.getTeamId());
19 Slack.Event event = this.parameters.getEvent();
20 String channelId = '';
21 String channelName = '';
22
23 if (event instanceof Slack.GroupRenameEvent) {
24 Slack.GroupRenameEvent groupRenameEvent = (Slack.GroupRenameEvent) event;
25 channelId = groupRenameEvent.getChannel().getId();
26 channelName = groupRenameEvent.getChannel().getName();
27 } else if (event instanceof Slack.ChannelRenameEvent) {
28 // Group rename will only work if the app is added as an integration to the private channel.
29 Slack.ChannelRenameEvent channelRenameEvent = (Slack.ChannelRenameEvent) event;
30 channelId = channelRenameEvent.getChannel().getId();
31 channelName = channelRenameEvent.getChannel().getName();
32 }
33
34 Slack.ChatPostMessageResponse response = botClient.chatPostMessage(
35 Slack.ChatPostMessageRequest.builder().channel(channelId).text('The channel was renamed to ' + channelName).build()
36 );
37
38 if (response.getError() != null) {
39 System.debug(response.getResponseMetadata().getMessages());
40 }
41 }
42 }
43}This example responds to a user adding and removing an emoji on an item.
1# ApexSlackApp.slackapp
2# Other app configuration here
3# Register event handlers
4events:
5 reaction_added:
6 action:
7 definition: apex__action__ReactionEventExample
8 title: Example reaction added event
9 description: example reaction added to message.
10 reaction_removed:
11 action:
12 definition: apex__action__ReactionEventExample
13 title: Example reaction removed event
14 description: example reaction removed from message.Get the event parameters using the Slack.Event class and check if the event is an instance of the Slack.ReactionAddedEvent or Slack.ReactionRemovedEvent class.
1public class ReactionEventExample extends Slack.EventDispatcher {
2 public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
3 return Slack.ActionHandler.ack(new Handler(parameters, context));
4 }
5
6 public class Handler implements Slack.RunnableHandler {
7 Slack.EventParameters parameters;
8 Slack.RequestContext context;
9
10 public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
11 this.parameters = parameters;
12 this.context = context;
13 }
14
15 public void run() {
16 // Name must match the DeveloperName of your SlackApp.
17 Slack.App app = Slack.App.ApexSlackApp.get();
18 Slack.BotClient botClient = app.getBotClientForTeam(this.context.getTeamId());
19 Slack.Event event = this.parameters.getEvent();
20 String channelId = '';
21 String channelName = '';
22 String text = getBaseText(event);
23
24 if (event instanceof Slack.ReactionAddedEvent) {
25 Slack.ReactionAddedEvent reactionAddedEvent = (Slack.ReactionAddedEvent) event;
26 channelId = reactionAddedEvent.getItem().getChannel();
27 text += reactionAddedEvent.getReaction();
28 } else if (event instanceof Slack.ReactionRemovedEvent) {
29 Slack.ReactionRemovedEvent reactionRemovedEvent = (Slack.ReactionRemovedEvent) event;
30 channelId = reactionRemovedEvent.getItem().getChannel();
31 text += reactionRemovedEvent.getReaction();
32 }
33
34 Slack.ChatPostMessageResponse response = botClient.chatPostMessage(
35 Slack.ChatPostMessageRequest.builder().channel(channelId).text(text).build()
36 );
37
38 if (response.getError() != null) {
39 System.debug(response.getResponseMetadata().getMessages());
40 }
41 }
42
43 private String getBaseText(Slack.Event event) {
44 if (event instanceof Slack.ReactionAddedEvent) {
45 return 'Reaction added is: ';
46 } else if (event instanceof Slack.ReactionRemovedEvent) {
47 return 'Reaction removed is: ';
48 } else {
49 return '';
50 }
51 }
52 }
53}This example creates a channel based on a user’s message post containing the string “create channel [channel name]” where [channel name] is the name of the channel that will be joined by dashes. For example, “create channel demo channel” creates a channel called #demo-channel. You can also automatically add the user who issued the message to the new channel.
1# ApexSlackApp.slackapp
2# Other app configuration here
3# Register event handlers
4events:
5 message:
6 action:
7 definition: apex__action__MessageEventExample
8 title: Message sent
9 description: A message was sent to meCreate the specified channel using the Slack.ConversationsCreateResponse and Slack.ConversationsCreateRequest.
Next, invite the user who issued the command to the new channel using Slack.ConversationsInviteResponse and Slack.ConversationsInviteRequest.
1public class MessageEventExample extends Slack.EventDispatcher {
2 public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
3 return Slack.ActionHandler.ack(new Handler(parameters, context));
4 }
5
6 public class Handler implements Slack.RunnableHandler {
7 Slack.EventParameters parameters;
8 Slack.RequestContext context;
9 String CREATE_CHANNEL_TOKEN = 'create channel';
10
11 public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
12 this.parameters = parameters;
13 this.context = context;
14 }
15
16 public void run() {
17 // Name must match the DeveloperName of your SlackApp.
18 Slack.App app = Slack.App.ApexSlackApp.get();
19 Slack.BotClient botClient = app.getBotClientForTeam(this.context.getTeamId());
20 Slack.Event event = this.parameters.getEvent();
21
22 if (event instanceof Slack.MessageEvent){
23 handleMessageEvent(app, botClient, event);
24 }
25
26 }
27
28 private void handleMessageEvent(Slack.App app, Slack.BotClient botClient, Slack.Event event){
29 Slack.MessageEvent messageEvent = (Slack.MessageEvent)event;
30 String channelId = messageEvent.getChannel();
31 String message = messageEvent.getText();
32
33 // User sent the message
34 if (messageEvent.getBotId() == null){
35 System.debug(message);
36
37 if (message.toLowerCase().startsWith(CREATE_CHANNEL_TOKEN)){
38
39 if (message.trim().length() == CREATE_CHANNEL_TOKEN.length()){
40 sendChatMessage(app, botClient, channelId, 'You need to specify a channel name');
41 } else {
42 String channelToCreate = message.substring(CREATE_CHANNEL_TOKEN.length() + 1);
43
44 // Remove any spaces
45 channelToCreate = channelToCreate.replaceAll(' ', '-');
46
47 // Create the channel
48 Slack.ConversationsCreateResponse convCreateResponse = botClient.conversationsCreate(
49 Slack.ConversationsCreateRequest.builder().name(channelToCreate).isprivate(false).build()
50 );
51
52 if (convCreateResponse.getError() == null) {
53 // Get channel Id & user who just issued this command
54 String newChannelId = convCreateResponse.getChannel().getId();
55 List<String> users = new List<String>();
56 users.add(messageEvent.getUser());
57
58 // Add them to the newly created channel
59 Slack.ConversationsInviteResponse convInviteResponse = botClient.conversationsInvite(
60 Slack.ConversationsInviteRequest.builder().channel(newChannelId).users(users).build()
61 );
62 if (convInviteResponse.getError() == null){
63 sendChatMessage(app, botClient, channelId, ':tada: Channel #' + channelToCreate + ' was created and you were added to it, enjoy! :tada:');
64 } else {
65 sendChatMessage(app, botClient, channelId, 'Successfully created the channel, but trying to add you I sadly I got an error: ' + convInviteResponse.getError());
66 }
67 } else {
68 // Handle error
69 sendChatMessage(app, botClient, channelId, 'Sadly I got an error: ' + convCreateResponse.getError());
70 }
71 }
72 } else {
73 sendChatMessage(app, botClient, channelId, 'Ask me to "Create Channel <Name>"');
74 }
75 }
76 }
77
78
79 private void sendChatMessage(Slack.App app, Slack.BotClient botClient, String channelId, String message){
80
81 Slack.ChatPostMessageResponse response = botClient.chatPostMessage(
82 Slack.ChatPostMessageRequest.builder().channel(channelId).text(message).build()
83 );
84
85 if (response.getError() != null) {
86 System.debug(response.getResponseMetadata().getMessages());
87 }
88 }
89 }
90}Beta Feature