2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ruby から slack へ message を送信する

Last updated at Posted at 2022-09-24

目的

  • ruby から slack channel や個人へ message を送信する
    • 送信者は bot 扱いとなる

概要

  • 使用 gem
  • token の取得
  • channel id, user id の取得
  • ruby code sample
    • token 設定
    • dm
    • message
    • block

使用 gem

gem 'slack-ruby-client'

bot auth token の取得

  • [ 使用する slack app の設定画面 ] を開く
  • [ OAuth & Permissions ] を開く
  • [ Bot User OAuth Token ] を控える

スクリーンショット 2022-09-25 21.11.16.png

App へ chat write 権限の付与

  • [ OAuth & Permissions ] を開く
  • [ Bot Token Scopes ] の [ Add an OAuth Scope ] を選択
  • [ chat:write ] を追加する
  • [ Reinstall to Workspace ] を実行
    • 初回の場合は, message が異なる

スクリーンショット 2022-09-25 21.21.34.png

channel, user id を取得する

  • slack を browser で開き, url path より取得する
# channel id
https://app.slack.com/client/[TEAM_ID]/[CHANNEL_ID]/

# user id : user profile を開き, url 末尾が user_id となる
https://app.slack.com/client/[TEAM_ID]/[CHANNEL_ID]/rimeto_profile/[USER_ID]

ruby code sample

require 'slack-ruby-client'


def setup_slack
    token="xoxb-11111111111-222222222222-DummyDummyDummy3333"

    Slack.configure do |config|
        config.token = token
    end
end


def send_message_to_user
    # user へ DM を送信する
    user_id = 'USER_ID'
    msg     = 'test msg'

    client = Slack::Web::Client.new
    response = client.chat_postMessage(
        channel: user_id,
        text:    msg
    )
end


def send_message_to_channel
    # channel へ message を送信する
    channel_id = 'CHANNEL_ID'
    msg        = 'test msg'

    client = Slack::Web::Client.new
    response = client.chat_postMessage(
        channel: channel_id,
        text:    msg
    )
end

setup_slack
send_message_to_user
send_message_to_channel

block message

block とは

block sample 画像

スクリーンショット 2022-09-24 16.25.08.png

sample code

  • 投稿する際は, message と同様に block を付与して送信する.
  • 投稿した block の更新も可能.
    • 更新には message_ts が必要となる
    • message_ts は, block 上の button などから発行される request に含まれる.
def post_block
    client = Slack::Web::Client.new
    block = generate_block

    response = client.chat_PostMessage(
        channel: channel_id,
        blocks:  block
    )
end

def update_block
    client = Slack::Web::Client.new
    block = generate_block

    response = client.chat_update({
        ts:      message_ts,
        channel: channel_id,
        blocks:  block
    })
end

以上

参考記事

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?