LoginSignup
11
10

More than 5 years have passed since last update.

BacklogのタスクをSlackに通知する その2

Last updated at Posted at 2014-06-02

参照

その1
その3

やりたいこと

slackの投稿を整形する

前回のやり方では、一行メッセージのみが投稿可能だったので、attachmentを使ったものに置き換える。
そのために、slack-notifierを使用する

サンプルコード

slack.rb
require 'slack-notifier'

class SlackClient
  #
  def initialize(team, token, room='#general', name=nil)
    @client = Slack::Notifier.new(team, token)
    @default_room = room
    if name
      @client.username = name
      @default_name = name
    end
    clear_fields
  end
  #
  def clear_fields
    @client.channel = @default_room
    @fields = []
  end
  #
  def message(msg, room = nil)
    @client.channel = room if room
    @client.ping(msg)
    clear_fields
  end
  #
  def append_field(title, value, short = false)
    @fields << {:title => title, :value => value, :short => short}
  end
  #
  def format_message(msg, fields = [], room = nil)
    opts = {
      "fallback"  => msg,
      "color"     => "#8ABE00",
      "fields"    => @fields + fields,
    }
    @client.channel = room if room
    @client.ping(msg, attachments: [opts])
    clear_fields
  end

end

投稿部分のみ。前回のサンプルを参照してください。

sample.rb
#
def slack_send(slack, project, issue)
  action = (issue["created_on"] == issue["updated_on"]) ? "created" : "updated"
  #
  mes = "[" + project["name"] + "]" + issue['summary'] + "(" + issue['url'] + ") " + action
  mes_format = issue['summary']
  #
  slack.clear_fields
  slack.append_field("project", project["name"], true)
  slack.append_field("created by", issue['created_user']['name'], true)
  slack.append_field("priority", issue['priority']['name'], true)
  slack.append_field("url", issue['url'], true)
  room = project2room(project["name"])
  puts room
  if action == "created"
    slack.format_message(mes_format, [], room)
  else
    slack.message(mes, room)
  end
end

(中略)

  slack = SlackClient.new('test', 'xxxxxxxx', '#test', 'backlog')

(中略)

    slack_send(slack, project, issue)

こちらに続きます

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