From dd3b95e76c79c96c2749dc7948605fb1c21e7ad0 Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Sun, 2 Jul 2017 15:01:14 +0900 Subject: notification: add slack notification Use the "Incoming Webhooks" service of Slack. --- config.rb.example | 3 +++ notification.rb | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/config.rb.example b/config.rb.example index 174c6ed..1c24ae3 100644 --- a/config.rb.example +++ b/config.rb.example @@ -9,6 +9,9 @@ NyaConfig.configure( from: "nyaci@ci.rhe.jp", to: "k@rhe.jp", }, + slack: { + webhook: "https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX" + }, }, modules: { ruby: { diff --git a/notification.rb b/notification.rb index f8dd526..169fbf5 100644 --- a/notification.rb +++ b/notification.rb @@ -1,11 +1,14 @@ require "net/smtp" require "uri" require "time" +require "net/http" +require "json" class Notification - def initialize(email: nil) + def initialize(email: nil, slack: nil) @list = [] @list << Email.new(email) if email + @list << Slack.new(slack) if slack end def publish(*args) @@ -68,4 +71,39 @@ class Notification finish(subject, body, jobid) end end + + class Slack + def initialize(webhook:) + @webhook = webhook + end + + def publish(project, jobid, results) + failed = results.count { |id, result| !result } + + link = NyaConfig.webroot + "/" + project + "/" + jobid + result = failed == 0 ? "passed" : "failed" + ary = ["nyaci build <#{link}|#{project}/#{jobid}> #{result}."] + if failed != 0 + ary << "failed builds:" + results.select { |id, r| !r }.map { |id, r| id }.sort.each { |i| + link = NyaConfig.webroot + "/" + project + "/" + jobid + "/" + i + ary << "- <#{link}|#{i}>" + } + end + + payload = JSON.generate(attachments: [{ + color: failed == 0 ? "good" : "danger", + text: ary.join("\n"), + }]) + + uri = URI.parse(@webhook) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = uri.scheme == "https" + body = http.start { + res = http.post(uri.path, payload, "Content-Type" => "application/json") + res.body + } + raise "failed to post to Slack: #{body}" if body != "ok" + end + end end -- cgit v1.2.3