Skip to content

Instantly share code, notes, and snippets.

@birarda
Created March 12, 2013 01:36
Show Gist options
  • Select an option

  • Save birarda/5139554 to your computer and use it in GitHub Desktop.

Select an option

Save birarda/5139554 to your computer and use it in GitHub Desktop.
Basecamp to-dos to HipChat
require "net/https"
require "uri"
require "json"
$filename = "timestamp.txt"
$time_format = "%Y-%m-%dT%H:%M:%S%z"
def event_request(timestamp, page = 1)
# setup a GET request to the basecamp API
bc_url = "https://basecamp.com/#{ENV['BASECAMP_ID']}/api/v1/events.json?since=#{timestamp}"
bc_url += "&page=#{page}" if page > 1
bc_uri = URI.parse(bc_url)
bc_http = Net::HTTP.new(bc_uri.host, bc_uri.port)
bc_http.use_ssl = true
# BC API requires us to pass a custom user agent
headers = {
'User-Agent' => "HighFidelity ([email protected])"
}
# fire off the request to the BC API and parse out the JSON response
bc_req = Net::HTTP::Get.new bc_uri.request_uri, headers
bc_req.basic_auth ENV['BASECAMP_USER'], ENV['BASECAMP_PASSWORD']
bc_res = bc_http.request(bc_req)
json = JSON.parse(bc_res.body)
# write the time of this request to the file at filename
File.open($filename, 'w') do |file|
file.write Time.now.strftime $time_format
end
# setup requests to the hipchat API
hc_uri = URI.parse("https://api.hipchat.com/v1/rooms/message?auth_token=#{ENV['BC_HIPCHAT_TOKEN']}")
hc_http = Net::HTTP.new(hc_uri.host, hc_uri.port)
hc_http.use_ssl = true
hc_req = Net::HTTP::Post.new(hc_uri.request_uri)
# default params for each message
message_params = {
:room_id => ENV['BC_HIPCHAT_ROOM_ID'],
:from => "Basecamp",
:color => "purple"
}
# check each event
json.each do |event|
if (summary = event["summary"]).match('to-do')
# this is a to-do event
# find where we want to put the anchor
pre_link_text = "</span> "
span_close = summary.index(pre_link_text)
link_text = summary[(span_close + pre_link_text.size)..summary.size]
# construct the message for HipChat
message = "#{event["creator"]["name"]} #{summary.gsub(link_text, "<a href=#{event['html_url']}>#{link_text}</a>")}"
message.gsub!("<span>", '')
message.gsub!("</span>", '')
# send this message to hipchat
message_params[:message] = message
hc_req.set_form_data(message_params)
hc_res = hc_http.request(hc_req)
end
end
if json.length == 50
# there are more than 50 events, we need to grab the next page
event_request(timestamp, page + 1)
end
end
# pull the timestamp of last check from file at filename
timestamp = nil
begin
File.open($filename, 'r') do |file|
timestamp = file.read
end
rescue
# if we didn't have the file, just default to one minute ago
timestamp = (Time.now - (60 * 10)).strftime $time_format
end
event_request(timestamp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment