Slack Ruby Client

Gem Version
Build Status

A Ruby client for the Slack Web and RealTime Messaging APIs.

Installation

Add to Gemfile.

gem 'slack-ruby-client'

Run bundle install.

Usage

Create a New Bot Integration

This is something done in Slack, under integrations. Create a new bot, and note its API token.

Use the API Token

Slack.configure do |config|
  config.token = ENV['SLACK_API_TOKEN']
end

Web Client

The Slack Web API allows you to build applications that interact with Slack. For example, send messages with chat_PostMessage.

client = Slack::Web::Client.new

client.auth_test

general_channel = client.channels_list['channels'].detect { |c| c['name'] == 't3' }

client.chat_postMessage(channel: general_channel['id'], text: 'Hello World', as_user: true)

See a fully working example in examples/hi_web.

Refer to the Slack Web API Method Reference for the list of all available functions.

RealTime Client

The Real Time Messaging API is a WebSocket-based API that allows you to receive events from Slack in real time and send messages as user.

client = Slack::RealTime::Client.new

client.on :hello do
  puts 'Successfully connected.'
end

client.on :message do |data|
  case data['text']
  when 'bot hi' then
    client.message channel: data['channel'], text: "Hi <@#{data['user']}>!"
  when /^bot/ then
    client.message channel: data['channel'], text: "Sorry <@#{data['user']}>, what?"
  end
end

client.start!

You can also send typing indicators.

client.typing channel: data['channel']

See a fullly working example in examples/hi_real_time.

Combinging RealTime and Web Clients

Since the web client is used to obtain the RealTime client’s WebSocket URL, you can continue using the web client in combination with the RealTime client.

client = Slack::RealTime::Client.new

client.on :message do |data|
  case data['text']
  when 'bot hi' then
    client.web_client.chat_postMessage channel: data['channel'], text: "Hi <@#{data['user']}>!"
  when /^bot/ then
    client.web_client.chat_postMessage channel: data['channel'], text: "Sorry <@#{data['user']}>, what?"
  end
end

client.start!

See a fullly working example in examples/hi_real_time_and_web.

History

This gem is based on slack-ruby-gem, but it more clearly separates the Web and RTM APIs, is more thoroughly tested and is in active development.

Contributing

See CONTRIBUTING.

Copyright and License

Copyright © 2015, Daniel Doubrovkine, Artsy and Contributors.

This project is licensed under the MIT License.