Ruby Slack Notifier

Register at Slack.com
Create a channel for your Team
Configure a Custom Incoming WebHooks Integration
Install the app on your phone (Optional, but it will receive push notifications)

##Replace Your Unique Webhook URL accordingly (In @@uri)!
root@mikrodash:/opt/dashing/rmm_hud# cat jobs/SlackNotifier.rb
require ‘net/http’
require ‘json’
require ‘uri’

class SlackNotifier
@@uri = URI.parse(“PASTE_URI_HERE”)
@@header = {‘Content-Type’ => “text/json”}

def notifySlack(notification)
# Create the HTTP objects
@http = Net::HTTP.new(@@uri.host, @@uri.port)
@http.use_ssl = true
@request = Net::HTTP::Post.new(@@uri.request_uri, @@header)
@request.body = notification.to_json
# Send the request
@http.request(@request)
end
end

##Basic example of Use
root@mikrodash:/opt/dashing/rmm_hud# cat jobs/offlineservercount.rb
require_relative ‘my_db.rb’
require_relative ‘SlackNotifier.rb’

current_offlineservercount = 0
firstRun = true

SCHEDULER.every ’30s’, :first_in => 0 do |job|
db = MyDb.conn
sn = SlackNotifier.new

sql = “SUPER SQL!”
notif = “New Offline Server!!\n”
results = db.query(sql)
if results.count > current_offlineservercount
results.each do|row|
name = row[‘name’]
notif = notif + name + “\n”
end
tmpNotif = {‘text’ => notif}
if !firstRun then sn.notifySlack(tmpNotif) end
end

current_offlineservercount = results.count
firstRun = false
db.close

send_event(‘offlineservercount’, { value: current_offlineservercount } )
end

##Yay!!

Leave a Reply

Your email address will not be published. Required fields are marked *