Slack v0.4.0 Slack

Slack is a genserver-ish interface for working with the Slack real time messaging API through a Websocket connection.

To use this module you’ll need a valid Slack API token. You can find your personal token on the Slack Web API page, or you can add a new bot integration.

Example

defmodule Bot do
  use Slack

  def handle_message(message = {type: "message"}, slack, state) do
    if message.text == "Hi" do
      send_message("Hi has been said #{state} times", message.channel, slack)
      state = state + 1
    end

    {:ok, state}
  end
end

Bot.start_link("API_TOKEN", 1)

handle_* methods are always passed slack and state arguments. The slack argument holds the state of Slack and is kept up to date automatically.

In this example we’re just matching against the message type and checking if the text content is “Hi” and if so, we reply with how many times “Hi” has been said.

The message type is pattern matched against because the Slack RTM API defines many different types of messages that we can receive. Because of this it’s wise to write a catch-all handle_message/3 in your bots to prevent crashing.

Callbacks

  • handle_connect(slack, state) - called when connected to Slack.
  • handle_message(message, slack, state) - called when a message is received.
  • handle_close(reason, slack, state) - called when websocket is closed.
  • handle_info(message, slack, state) - called when any other message is received in the process mailbox.

Slack argument

The Slack argument that’s passed to each callback is what contains all of the state related to Slack including a list of channels, users, groups, bots, and even the socket.

Here’s a list of what’s stored:

  • me - The current bot/users information stored as a map of properties.
  • team - The current team’s information stored as a map of properties.
  • bots - Stored as a map with id’s as keys.
  • channels - Stored as a map with id’s as keys.
  • groups - Stored as a map with id’s as keys.
  • users - Stored as a map with id’s as keys.
  • socket - The connection to Slack.
  • client - The client that makes calls to Slack.

For all but socket and client, you can see what types of data to expect each of the types to contain from the Slack API types page.

Summary

Functions

Notifies Slack that the current user is typing in channel

Sends text to channel for the given slack connection

Notifies slack that the current slack user is typing in channel

Sends raw JSON to a given socket

Functions

indicate_typing(channel, slack)

Notifies Slack that the current user is typing in channel.

send_message(text, channel, slack)

Sends text to channel for the given slack connection.

send_ping(data \\ [], slack)

Notifies slack that the current slack user is typing in channel.

send_raw(json, map)

Sends raw JSON to a given socket.