Files
datapipeline/lib/datapipeline/notification/slack.rb
T

37 lines
1.0 KiB
Ruby

require 'http'
require 'json'
class DataPipeline
#
# Slack.new(channel: '#etl').send_message('posting export done')
#
# options
# token: bot token, default ENV['SLACK_TOKEN']
# channel: default '#general'
#
class Slack
API_URL = 'https://slack.com/api/chat.postMessage'.freeze
DEFAULTS = {
token: nil,
channel: '#general'
}.freeze
def initialize options = {}
@options = DEFAULTS.merge(token: ENV['SLACK_TOKEN']).merge(options)
raise ArgumentError, 'Slack: token missing (option token: or ENV SLACK_TOKEN)' unless @options[:token]
end
# returns the parsed slack response, raises when slack reports an error
def send_message(content, verbose: false)
response = HTTP.auth("Bearer #{@options[:token]}")
.post(API_URL, json: { channel: @options[:channel], text: content })
body = JSON.parse(response.body.to_s)
puts JSON.pretty_generate(body) if verbose
raise "Slack#send_message failed: #{body['error']}" unless body['ok']
body
end
end
end