Daniel Doubrovkine bio photo

Daniel Doubrovkine

aka dB., @awscloud, former CTO @artsy, +@vestris, NYC

Email Twitter LinkedIn Github Strava
Creative Commons License

I’ve been recently contributing to slack-pongbot, a node.js Slack bot for setting up ping-pong matches at Artsy.

The endless levels of callback hell and promises have driven me sufficiently crazy to try and rewrite this in Ruby. Let’s get a basic Ruby Slack integration going, using the Slack Real Time Messaging API this time.

Slack-Ruby-Client

A quick note to readers. If you come here from slack-ruby-gem this tutorial no longer uses it. That library was slow to evolve and wasn’t clearly separating the Slack Web API with the Slack RealTime Messaging API. I’ve rewritten much of the implementation in a new gem slack-ruby-client, please use that for all your Slack Ruby needs!

I do want to thank @aki017, the author of the former gem, for getting me started.

Use Slack Real Time Messaging Api

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. The hard part has been done for you in the slack-ruby-client gem.

gem 'slack-ruby-client', '~> 0.1.0'

Create a New Bot Integration

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

Verify Auth

Use the token to verify auth via the Web API.

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

client = Slack::Web::Client.new

client.auth_test

The above code returns a hash with the user information, including url, team and team id, user and user_id.

Start a Bot

The slack-api gem uses eventmachine to listen on events from Slack.

client = Slack::RealTime::Client.new

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

client.on :message do |data|
  # respond to messages
end

client.start!

Respond to Messages

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

Slack automatically parses and translates things like <@userid>. That’s it.

Turning GameBot into an App

I turned GameBot into a runnable app with some bells and whistles at github.com/dblock/slack-gamebot.

Update: Bot Framework and Integration with Rails

If you’re writing a bot, or trying to integrate Slack with Rails, check out The Easiest Way to Write a Slack Bot in Ruby and Writing a Slack Bot running on Rails (with React).