参照
やりたいこと
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)