Sending Slack messages from Rails

This tutorial explains how to send Slack messages from a Rails application.

Creating a Slack App

Before writing any code, we need to follow the Slack tutorial for creating an app and obtaining a token. In the tutorial there is a section called ‘Create a pre-configured app’ that allows us to pick a workspace and create an app. After reviewing the configuration we can click ‘create’.

After creating the app, we’re taken to the app settings page. In the ‘Basic Information’ section there is a button to install the app in our workspace.

Lastly, we can navigate to the ‘Install App’ section to grab the OAuth Token.

Sending a message from Rails

To handle this, we’re going to use the slack-ruby-client gem. The first step is to add this to the Gemfile and run bundler:

1
gem 'slack-ruby-client'

Next, we’ll add a Slack.configure block to a new initializers file, which we’ll call config/initializers/slack.rb. Inside, we’ll use an ENV var, which is set to the OAuth token obtained earlier:

1
2
3
Slack.configure do |config|
  config.token = ENV['SLACK_BOT_USER_OAUTH_TOKEN']
end

Sending a message is simple, it’s just two lines of code:

1
2
client = Slack::Web::Client.new
client.chat_postMessage(channel: '#general', text: "Hello world!", as_user: true)