Send Slack Messages from your Ruby on Rails Server

Paulo Carvalho
2 min readOct 9, 2020

Quickly start sending Slack messages from your Ruby on Rails backend without the need for any third party libraries!

Photo by Scott Webb on Unsplash

Introduction

Slack provides several ways to integrate with the platform. Among these integration options are the Slack Workflows. In this article, we will go over setting up one of these workflows and use it to provide a Ruby on Rails backend a way to post messages to Slack.

Methods

Setup the Workflow in Slack

  1. From the Slack Desktop client click on your workspace name, select tools and then “Workflow Builder”.
  2. Click “Create” on the top right corner.
  3. Type a name for your workflow such as: “My First Workflow”. This name will appear as the title of messages created by the workflow.
  4. In the “Choose a way to start this workflow” window select “Webhook advanced” and feel proud that you are an advanced user!
  5. In the “Webhook” window create a variable of type text called message.
  6. At this point, a workflow has been created. Add a step to the created workflow to “Send a message”. Select the channel your integration should be sending messages to and use our variable message in the notification body.
  7. Publish the workflow and copy the provided webhook URL.

More information on creating workflow can be found here.

Setup Integration in Ruby on Rails

  1. Add the webhook URL from the previous section to your environment variables (for testing you can use directly in code) as SLACK_WEBHOOK_URL.
  2. Create a job called send_slack_notification_job.rb in your jobs folder with the code below:
class SendSlackNotificationJob < ApplicationJob
def perform(message)
return unless ENV['SLACK_GENERAL_HOOK'].present?

HTTParty.post(
ENV['SLACK_GENERAL_HOOK'],
body: {
message: message
}.to_json,
headers: { 'Content-Type' => 'application/json' }
)
end
end

3. Send messages by calling SendSlackNotificationJob.perform_later("My first Slack message!") from anywhere in your code!

Notes:

  • You don’t need to use the HTTParty gem to make the POST request to the webhook.
  • The integration was created inside a job so that it can occur asynchronously from the main code execution. For instance, if you want to send a Slack message whenever a new user signs up to your platform using the after_create callback, you don’t want to slow down the user creation API having to wait for the Slack webhook to succeed.

Conclusion

A simple integration between Slack and a Ruby on Rails backend was shown. With this integration, it is possible to post messages to Slack from your backend.

Paulo Carvalho

Want to chat about startups, consulting or engineering? Just send me an email on paulo@avantsoft.com.br.