Help us understand the problem. What is going on with this article?

RailsアプリからSlackに通知

More than 3 years have passed since last update.

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした