Slack Bots for Work

In a previous post, I mentioned how I get notified of the restaurant menu via a Ruby script. Recently I’ve moved to a totally different product area and the main communication channel we use is Slack. Naturally enough, I ported the Ruby code I wrote, and it now posts the menu every day to our Slack channel.

This also got me thinking of what other information would be handy to have. I scouted around for ideas and came up with an obvious one: reminder of the bus times to and from the office. So here’s my bus times notification slack bot:

#!/usr/bin/env ruby
#Encoding: UTF-8
require 'nokogiri'
require 'json'
require 'net/http'
require 'open-uri'

def notify_slack(text)
    webhook_url = '' # TODO: Insert yours here
    payload = {
        #:channel => channel,
        #:username => username,
        :text => text
        #:icon_url => image
    }.to_json
    cmd = "curl -X POST --data-urlencode 'payload=#{payload}' #{webhook_url}"
    system(cmd)
end

def make_bus_times()
    today = Date.today
    return {
        "Sheraton" => [
            Time.local(today.year, today.month, today.day, 8, 10, 0),
            Time.local(today.year, today.month, today.day, 8, 35, 0),
            Time.local(today.year, today.month, today.day, 9, 10, 0)
        ],
        "Ericsson" => [
            Time.local(today.year, today.month, today.day, 16, 30, 0),
            Time.local(today.year, today.month, today.day, 17, 25, 0),
            Time.local(today.year, today.month, today.day, 18, 00, 0)
        ]
    }

    return bus_times
end

def check_next_bus()
    bus_times = make_bus_times()
    t = Time.now
    t2 = t + 15 * 60 # 15mins in future
    bus_times.each do |key, array|
        bus_times[key].each { |val|
            if val.between?(t, t2)
                text = "@here Bus leaving from #{key} in next 15mins at #{val.strftime('%H:%M')}"
                notify_slack(text)
            end
        }
    end

end

check_next_bus()

I simply set this to run every 20 minutes, Monday to Friday, during working hours via cron:

*/20 07-19 * * 1,2,3,4,5 bus-times.rb > /dev/null 2>&1

For convenience, I have the webhook set to post to a different channel so people can opt in for bus reminders.