LoginSignup
11
8

More than 5 years have passed since last update.

Slack | Incoming WebHooks を利用して, Ruby から Slack にメッセージを送る #ruby #slack

Posted at

Slack | Incoming WebHooks を利用して, Ruby から Slack にメッセージを送る #ruby #slack

:musical_score: 概要

Incoming WebHooks を利用して, Ruby から Slack にメッセージを送ります

:raised_hand: 前提

環境変数の管理に dotenv gem を利用します。詳細は下記記事参照。
dotenv gem で環境変数をスマートに管理

手順

:musical_note: Slack の Configure Integrations で Incoming WebHooks を追加

slack_incoming1.png

:musical_note: Webhook URL をコピーしておく

:musical_note: Channel , Icon, Customize Name を任意の内容に設定する

attr value
Channel test
Icon 私のプロフィールアイコンを使用
Customize Name (^-^)

slack_incoming2.png

:musical_note: .env ファイルを設定

URL=コピーしておいた WebHooks の URL

:musical_note: ソースコード

sample.rb
require 'net/http'
require 'uri'
require 'json'
require 'dotenv'

class SlackWraper
  def self.post(text)
    data = { "text" => text }
    request_url = ENV['URL']
    uri = URI.parse(request_url)
    Net::HTTP.post_form(uri, {"payload" => data.to_json})  
  end
end

Dotenv.load
SlackWraper.post("=Message=")

:musical_note: 実行

$ ruby sample.rb

:musical_note: 実行結果を確認

slack_incoming3.png

11
8
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
11
8