LoginSignup
95
85

More than 5 years have passed since last update.

RailsアプリからSlackに通知

Posted at

Railsで作ってるWebアプリのエラーや、ご意見フォームからの投稿をSlackにとりあえず流したいとき用。

以下のgemを利用する。
aki017/slack-ruby-gem

Gemfile
gem 'slack-api'

bundle installしたら、config/intializers下に設定ファイルを置く。

config/intializers/slack_api.rb
require 'slack'

Slack.configure do |config|
  config.token = "<Slack Authentication Token>"
end

トークンは、以下のページで取得。
Slack Web API | Slack


あとは、実際にSlackに送信する部分を記述するのみ。

例えばemail, messageというプロパティを持つ、Opinionというモデルのインスタンスの情報を送るとすると、適当だがこんな感じだろうか。

app/controllers/opinions_controller.rb
class OpinionsController < ApplicationController
  def create
    @opinion = Opinion.new(params[:opinion])

    if @opinion.save
      notify_to_slack
      ...
    else
      ...
    end
  end

  private

  def notify_to_slack
    text = <<-EOC
-----------------------------
[#{Rails.env}] 新しいご意見が来ました。

▼メールアドレス
#{opinion.email}
▼内容
#{opinion.message}
    EOC

    Slack.chat_postMessage text: text, username: "Opinion Notifier", channel: "#opinion"
  end
end

Slack.chat_postMessageには引数として、text(メッセージ), username(表示名), channel(channel名)が渡せる。textchannelは必須。

これで通知がSlackに来る。

Screen Shot 2015-05-19 at 3.29.15 PM.png

簡単な通知ならこれで良さ気。

95
85
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
95
85