Search code examples
javabotsslackslack-api

Bot identification with slash command in direct message channel


I have custom slack bot called 'rbot'. Also I created a custom slash command '/r-out'. whenever this command is being executed from any channel, my java service is being called with parameters included 'channel_id' and 'channel_name', which I use to identify from which channel this command is being executed.

Now, I want to restrict this command for 'rbot' only. For which, I need to validate if command is being executed as in a direct message channel with 'rbot' or not. How can I achieve this?


Solution

  • To verify that a slash command was sent in a direct message channel with your app you just need to check that the channel_id in the slash request refers to a valid direct message channel of your app.

    In more detail:

    When a user executes your slash command in a direct message channel with your app your app will receive a slash request like this: (PHP array)

    array (
      'token' => 'XXX',
      'team_id' => 'T12345678',
      'team_domain' => 'mydomain',
      'channel_id' => 'D12345678',
      'channel_name' => 'directmessage',
      'user_id' => 'U12345678',
      'user_name' => 'erik.kalkoken',
      'command' => '/evestatus',
      'text' => '',
      'response_url' => 'https://hooks.slack.com/commands/Txxx',
      'trigger_id' => '123',
    )
    

    The channel_id will start with "D" indicating that this comes from a direct message channel.

    Next pull the list of direct message channels for your app with im.list. Make sure to use your app token, so you get the direct message channels for your app.

    If the channel_id is in that list, then the slash command was used in a direct message channel with your app.