Skip to content

Instantly share code, notes, and snippets.

@VishalTaj
Created April 11, 2019 13:55
Show Gist options
  • Save VishalTaj/9dae11aa75706cf26f8ba4a45ebcb879 to your computer and use it in GitHub Desktop.
Save VishalTaj/9dae11aa75706cf26f8ba4a45ebcb879 to your computer and use it in GitHub Desktop.
Slack Notification in ruby
require 'net/http'
class Slack
attr_accessor :message, :channel, :status
BASE_URL = 'your base url goes here'
HEX_COLORS = {
success: '#7CD197',
error: '#BB0000',
warning: '#9F6000',
info: '#428bca'
}
def initialize(message, channel, status)
self.message = message
self.channel = channel
self.status = status
end
def self.notify(message: nil, channel: 'notification', status: :success)
@slack = self.new(message, channel, status)
uri = URI(@slack.send("#{channel}_url"))
https = Net::HTTP.new uri.host, uri.port
https.use_ssl = true
https.post2 uri.path, @slack.send(:payload), 'Content-Type' => 'application/json'
end
private
def payload
{
attachments: [
{
author_name: author,
color: HEX_COLORS[status],
title: @message,
ts: Time.now.to_i
}
]
}.to_json
end
def author
ENV['GIT_AUTHOR_NAME'] || `git config user.name`.chomp
end
# channels url
def notification_url
"#{BASE_URL}channel_key goes here"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment