pronoob
pronoob

Reputation: 831

Determine Channel Type via Slack Events API

While working with the Slack Events API and receiving event notifications, I found it was difficult to determine whether the message was sent in a:

There is no field in the request body that identifies the type of channel the message was sent in. Therefore if you want different behaviour for your application depending on the channel type, (e.g. tagging the user who sent the message in a multi-person channel), there is no obvious way to do it.

Regardless of the channel type, the request always follows the same format:

{
  :token=>"some_auth_token",
  :team_id=>"T1234ABCD",
  :api_app_id=>"A1234ABCD",
  :event=> { 
    :type=>"message",
    :user=>"U1234ABCD",
    :text=>"Who loves Orange Soda?",
    :ts=>"1486219313.000034",
    :channel=>"D1234ABCD",
    :event_ts=>"1486219313.000034"
  },
  :type=>"event_callback",
  :authed_users=>["U1234ABCD"]
}

Upvotes: 0

Views: 207

Answers (1)

pronoob
pronoob

Reputation: 831

What I did notice (though could not find in the Slack documentation), is that the channel identifier starts with a corresponding character depending on the channel type that is used:

  • Direct Message
    • starts with D, e.g. :channel=>"D1234ABCD"
  • Public Channel
    • starts with C, e.g. :channel=>"C1234ABCD"
  • Private Group/Channel
    • starts with G, e.g. :channel=>"G1234ABCD"

Therefore you can determine channel type by checking the first character of the Channel ID.

For example, in Ruby, I use the following method:

def channel?(channel_id)
  return true if channel_id.start_with?("C", "G")
  false
end

Also, I managed to get a response from Slack confirming that this is expected behaviour, so it should be safe to assume channel type in this way.

Upvotes: 1

Related Questions