From c0e318cd5cb4f7a2362f5606cd9f6f10fa2f2a4e Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Sat, 30 Jul 2022 00:51:14 +0900 Subject: notification: add Discord notification --- config.rb.example | 3 +++ notification.rb | 44 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/config.rb.example b/config.rb.example index 02bb38e..7b2cf43 100644 --- a/config.rb.example +++ b/config.rb.example @@ -12,6 +12,9 @@ NyaConfig.configure( slack: { webhook: "https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX" }, + discord: { + webhook: "https://discord.com/api/webhooks/XXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + }, }, modules: { ruby: { diff --git a/notification.rb b/notification.rb index 56d25a8..412adaf 100644 --- a/notification.rb +++ b/notification.rb @@ -5,10 +5,11 @@ require "net/http" require "json" class Notification - def initialize(email: nil, slack: nil) + def initialize(email: nil, slack: nil, discord: nil) @list = [] @list << Email.new(email) if email @list << Slack.new(slack) if slack + @list << Discord.new(discord) if discord end def publish(*args) @@ -107,4 +108,45 @@ class Notification raise "failed to post to Slack: #{body}" if body != "ok" end end + + class Discord + def initialize(webhook:) + @webhook = webhook + end + + def publish(project, jobid, results, elapsed) + failed = results.count { |id, result| !result } + + link = NyaConfig.webroot + "/" + project + "/" + jobid + ary = [] + if failed != 0 + ary << "failed builds:" + results.select { |id, r| !r }.map { |id, r| id }.sort.each { |i| + alink = NyaConfig.webroot + "/" + project + "/" + jobid + "/" + i + ai = i.gsub(/[_~*|`]/, "\\\\\\0") + ary << "- [#{ai}](#{alink})" + } + end + + payload = JSON.generate(embeds: [{ + color: failed == 0 ? 1673044 : 14431557, + title: "nyaci #{failed == 0 ? "passed" : "failed"} - #{project}/#{jobid}", + url: link, + description: ary.join("\n"), + footer: { + text: "#{project} • Finished in #{elapsed} seconds", + }, + timestamp: Time.now.iso8601, + }]) + + 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 Discord: #{body}" if body != "ok" + end + end end -- cgit v1.2.3