LoginSignup
4
4

More than 5 years have passed since last update.

railsアプリとslackの連携&通知をする

Last updated at Posted at 2016-03-04

railsで作ったブログやSNSで投稿があった時にslackに通知をする

自分のブログです。
railsアプリとslackの連携

実装方法

slack-apiというgemを使う

Gemfile

gem 'slack-api'を追加してbundle install

アクセストークンの取得

https://api.slack.com/web
下のボタンから生成する。

設定ファイル

config/initializers/slack_api.rb
require "slack"

Slack.configure do |config|
  config.token = "取得したトークン"
end

を新規作成

使い方

Slack.chat_postMessage(text: '新規投稿があります', username: '名前', channel: "#チャンネル名")

でチャンネルにusernameで指定したユーザー名で投稿される。

通知させる

ブログに新規投稿があったときに通知をさせる。
articles_controllerのcreateメソッドのsaveしたところに追加した。

articles_controller.rb
def create
    @article = Article.new(article_params)

    respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: '作成しました' }
        format.json { render :show, status: :created, location: @article }
        Slack.chat_postMessage(text: '新しい投稿があるよ!『'+ @article.title + '』', username: 'blogbot', channel: "#blogs")
      else
        format.html { render :new }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

参考サイト

railsアプリとslackの連携
Rails slack連携をしてみた

4
4
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
4
4