---
schema_version: "1"
id: af9acb8194a014b893580a91c628445e48297a1029a6ad737331158fe40612d0
title: Event Examples
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/salesforce-slack-sdk/apex-slack-sdk/guides/build/events_examples.md
canonical_url: https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/guide/events_examples.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 1e963e2d27555ce048e237aad56f552b2b39f1fffb410e7e95025ef0ebf22527
products:
  - Apex SDK for Slack (Beta)
---
# Event Examples

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](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/guide/events_handling.md).

**tip:** Most of these examples are available in the [sample Apex SDK for Slack app](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/setup-install-app.md).

## app_home_opened

This example displays a message in the App Home.

```yaml
# ApexSlackApp.slackapp
# Other app configuration here
# Register event handlers
events:
  app_home_opened:
    action:
      definition: apex__action__EventDispatcherAppHomeOpened
    title: Example event handler for app_home_opened
    description: The event fires when a user opens the home tab.
```

The `app_home` view is published using [`Slack.ViewsPublishRequest`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_views.md#viewspublishrequest-class) and [`Slack.ViewsPublishResponse`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_views.md#viewspublishresponse-class).

```yaml
# app_home.view
description: "This is a simple app home"
schema:
  properties:
    bodyText:
      type: string
      required: true
    headerText:
      type: string
      defaultValue: "Welcome Home"
components:
  - definition: home
    components:
      - definition: header
        properties:
          text: "{!view.properties.headerText}"
      - definition: section
        properties:
          text:
            type: "mrkdwn"
            text: "{!view.properties.bodyText}"
      - definition: divider
```

Set the expression values in the event handler using the [`Slack.ViewReference`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_dispatchers.md#viewreference-class) class.

```java
public class EventDispatcherAppHomeOpened extends Slack.EventDispatcher {
    public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
        return Slack.ActionHandler.ack(new Handler(parameters, context));
    }

    public class Handler implements Slack.RunnableHandler {
        Slack.EventParameters parameters;
        Slack.RequestContext context;

        public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
            this.parameters = parameters;
            this.context = context;
        }

        public void run() {
            // Name must match the DeveloperName of your SlackApp.
            Slack.App app = Slack.App.ApexSlackApp.get();
            Slack.BotClient botClient = app.getBotClientForTeam(context.getTeamId());
            Slack.AppHomeOpenedEvent appHomeOpened = (Slack.AppHomeOpenedEvent) parameters.getEvent();
            String userId = appHomeOpened.getUser();

            Slack.ViewReference viewReference = Slack.View.app_home.get();
            viewReference.setParameter('headerText', 'Welcome to the Apex Slack App Example.');
            viewReference.setParameter('bodyText', 'To see how this custom home view was created, see the EventDispatcherAppHomeOpened apex class.');
            Slack.HomeView homeView = new Slack.HomeView.builder().viewReference(viewReference).build();

            Slack.ViewsPublishRequest req = new Slack.ViewsPublishRequest.builder().userId(userId).view(homeView).build();

            Slack.ViewsPublishResponse response = botClient.viewsPublish(req);
            if (response.getError() != null) {
                System.debug(response.getResponseMetadata().getMessages());
            }
        }
    }
}
```

## channel_rename and group_rename

This example responds to a channel (public or private) rename by posting a message.

```yaml
# ApexSlackApp.slackapp
# Other app configuration here
# Register event handlers
events:
  channel_rename:
    action:
      definition: apex__action__RenameEventExample
    title: Example channel rename event
    description: example event that fires when a user renames a channel.
  group_rename:
    action:
      definition: apex__action__RenameEventExample
    title: Example channel rename event
    description: example event that fires when a user renames a channel.
```

Get the event parameters using the [`Slack.Event` class](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_events.md#event-class) and check if the event is an instance of the [`Slack.ChannelRenameEvent`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_events.md#channelrenameevent-class) or [`Slack.GroupRenameEvent`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_events.md#grouprenameevent-class) class.

```java
public class RenameEventExample extends Slack.EventDispatcher {
    public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
        return Slack.ActionHandler.ack(new Handler(parameters, context));
    }

    public class Handler implements Slack.RunnableHandler {
        Slack.EventParameters parameters;
        Slack.RequestContext context;

        public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
            this.parameters = parameters;
            this.context = context;
        }

        public void run() {
            // Name must match the DeveloperName of your SlackApp.
            Slack.App app = Slack.App.ApexSlackApp.get();
            Slack.BotClient botClient = app.getBotClientForTeam(this.context.getTeamId());
            Slack.Event event = this.parameters.getEvent();
            String channelId = '';
            String channelName = '';

            if (event instanceof Slack.GroupRenameEvent) {
                Slack.GroupRenameEvent groupRenameEvent = (Slack.GroupRenameEvent) event;
                channelId = groupRenameEvent.getChannel().getId();
                channelName = groupRenameEvent.getChannel().getName();
            } else if (event instanceof Slack.ChannelRenameEvent) {
                // Group rename will only work if the app is added as an integration to the private channel.
                Slack.ChannelRenameEvent channelRenameEvent = (Slack.ChannelRenameEvent) event;
                channelId = channelRenameEvent.getChannel().getId();
                channelName = channelRenameEvent.getChannel().getName();
            }

            Slack.ChatPostMessageResponse response = botClient.chatPostMessage(
                Slack.ChatPostMessageRequest.builder().channel(channelId).text('The channel was renamed to ' + channelName).build()
            );

            if (response.getError() != null) {
                System.debug(response.getResponseMetadata().getMessages());
            }
        }
    }
}
```

## reaction_added and reaction_removed

This example responds to a user adding and removing an emoji on an item.

```yaml
# ApexSlackApp.slackapp
# Other app configuration here
# Register event handlers
events:
      reaction_added:
    action:
        definition: apex__action__ReactionEventExample
    title: Example reaction added event
    description: example reaction added to message.
  reaction_removed:
    action:
        definition: apex__action__ReactionEventExample
    title: Example reaction removed event
    description: example reaction removed from message.
```

Get the event parameters using the [`Slack.Event` class](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_events.md#event-class) and check if the event is an instance of the [`Slack.ReactionAddedEvent`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_events.md#reactionaddedevent-class) or [`Slack.ReactionRemovedEvent`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_events.md#reactionremovedevent-class) class.

```java
public class ReactionEventExample extends Slack.EventDispatcher {
    public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
        return Slack.ActionHandler.ack(new Handler(parameters, context));
    }

    public class Handler implements Slack.RunnableHandler {
        Slack.EventParameters parameters;
        Slack.RequestContext context;

        public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
            this.parameters = parameters;
            this.context = context;
        }

        public void run() {
            // Name must match the DeveloperName of your SlackApp.
            Slack.App app = Slack.App.ApexSlackApp.get();
            Slack.BotClient botClient = app.getBotClientForTeam(this.context.getTeamId());
            Slack.Event event = this.parameters.getEvent();
            String channelId = '';
            String channelName = '';
            String text = getBaseText(event);

            if (event instanceof Slack.ReactionAddedEvent) {
                Slack.ReactionAddedEvent reactionAddedEvent = (Slack.ReactionAddedEvent) event;
                channelId = reactionAddedEvent.getItem().getChannel();
                text += reactionAddedEvent.getReaction();
            } else if (event instanceof Slack.ReactionRemovedEvent) {
                Slack.ReactionRemovedEvent reactionRemovedEvent = (Slack.ReactionRemovedEvent) event;
                channelId = reactionRemovedEvent.getItem().getChannel();
                text += reactionRemovedEvent.getReaction();
            }

            Slack.ChatPostMessageResponse response = botClient.chatPostMessage(
                Slack.ChatPostMessageRequest.builder().channel(channelId).text(text).build()
            );

            if (response.getError() != null) {
                System.debug(response.getResponseMetadata().getMessages());
            }
        }

        private String getBaseText(Slack.Event event) {
            if (event instanceof Slack.ReactionAddedEvent) {
                return 'Reaction added is: ';
            } else if (event instanceof Slack.ReactionRemovedEvent) {
                return 'Reaction removed is: ';
            } else {
                return '';
            }
        }
    }
}

```

## message

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.

```yaml
# ApexSlackApp.slackapp
# Other app configuration here
# Register event handlers
events:
  message:
    action:
      definition: apex__action__MessageEventExample
    title: Message sent
    description: A message was sent to me
```

Create the specified channel using the [`Slack.ConversationsCreateResponse`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_conversations.md#conversationscreateresponse-class) and [`Slack.ConversationsCreateRequest`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_conversations.md#conversationscreaterequest-class).

Next, invite the user who issued the command to the new channel using [`Slack.ConversationsInviteResponse`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_conversations.md#conversationsinviteresponse-class) and [`Slack.ConversationsInviteRequest`](https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/apex_ref/apex_ref_conversations.md#conversationsinviterequest-class).

```java
public class MessageEventExample extends Slack.EventDispatcher {
    public override Slack.ActionHandler invoke(Slack.EventParameters parameters, Slack.RequestContext context) {
        return Slack.ActionHandler.ack(new Handler(parameters, context));
    }

    public class Handler implements Slack.RunnableHandler {
        Slack.EventParameters parameters;
        Slack.RequestContext context;
        String CREATE_CHANNEL_TOKEN = 'create channel';

        public Handler(Slack.EventParameters parameters, Slack.RequestContext context) {
            this.parameters = parameters;
            this.context = context;
        }

        public void run() {
            // Name must match the DeveloperName of your SlackApp.
            Slack.App app = Slack.App.ApexSlackApp.get();
            Slack.BotClient botClient = app.getBotClientForTeam(this.context.getTeamId());
            Slack.Event event = this.parameters.getEvent();

            if (event instanceof Slack.MessageEvent){
                handleMessageEvent(app, botClient, event);
            }

        }

        private void handleMessageEvent(Slack.App app, Slack.BotClient botClient, Slack.Event event){
            Slack.MessageEvent messageEvent = (Slack.MessageEvent)event;
            String channelId = messageEvent.getChannel();
            String message = messageEvent.getText();

            // User sent the message
            if (messageEvent.getBotId() == null){
                System.debug(message);

                if (message.toLowerCase().startsWith(CREATE_CHANNEL_TOKEN)){

                    if (message.trim().length() == CREATE_CHANNEL_TOKEN.length()){
                        sendChatMessage(app, botClient, channelId, 'You need to specify a channel name');
                    } else {
                        String channelToCreate = message.substring(CREATE_CHANNEL_TOKEN.length() + 1);

                        // Remove any spaces
                        channelToCreate = channelToCreate.replaceAll(' ', '-');

                        // Create the channel
                        Slack.ConversationsCreateResponse convCreateResponse = botClient.conversationsCreate(
                            Slack.ConversationsCreateRequest.builder().name(channelToCreate).isprivate(false).build()
                        );

                        if (convCreateResponse.getError() == null) {
                            // Get channel Id & user who just issued this command
                            String newChannelId = convCreateResponse.getChannel().getId();
                            List<String> users = new List<String>();
                            users.add(messageEvent.getUser());

                            // Add them to the newly created channel
                            Slack.ConversationsInviteResponse convInviteResponse = botClient.conversationsInvite(
                                Slack.ConversationsInviteRequest.builder().channel(newChannelId).users(users).build()
                            );
                            if (convInviteResponse.getError() == null){
                                sendChatMessage(app, botClient, channelId, ':tada: Channel #' + channelToCreate + ' was created and you were added to it, enjoy! :tada:');
                            } else {
                                sendChatMessage(app, botClient, channelId, 'Successfully created the channel, but trying to add you I sadly I got an error: ' + convInviteResponse.getError());
                            }
                        } else {
                            // Handle error
                            sendChatMessage(app, botClient, channelId, 'Sadly I got an error: ' + convCreateResponse.getError());
                        }
                    }
                } else {
                    sendChatMessage(app, botClient, channelId, 'Ask me to "Create Channel <Name>"');
                }
            }
        }


        private void sendChatMessage(Slack.App app, Slack.BotClient botClient, String channelId, String message){

            Slack.ChatPostMessageResponse response = botClient.chatPostMessage(
                Slack.ChatPostMessageRequest.builder().channel(channelId).text(message).build()
            );

            if (response.getError() != null) {
                System.debug(response.getResponseMetadata().getMessages());
            }
        }
    }
}
```
