Skip to content

Instantly share code, notes, and snippets.

@chrisk
Created December 10, 2009 22:29
Show Gist options
  • Save chrisk/253757 to your computer and use it in GitHub Desktop.
Save chrisk/253757 to your computer and use it in GitHub Desktop.
Post tweets to Campfire
#!/usr/bin/ruby
require 'rubygems'
require 'twitter'
require 'httparty'
require 'json'
require 'action_view'
include ActionView::Helpers
class Campfire
include HTTParty
base_uri 'https://example.campfirenow.com'
basic_auth 'your_token_here', 'x'
headers 'Content-Type' => 'application/json'
def self.rooms
Campfire.get('/rooms.json')["rooms"]
end
def self.room(room_id)
Room.new(room_id)
end
end
class Room
attr_reader :room_id
def initialize(room_id)
@room_id = room_id
end
def message(message)
send_message message
end
def paste(paste)
send_message paste, 'PasteMessage'
end
private
def send_message(message, type = 'Textmessage')
post 'speak', :body => {:message => {:body => message, :type => type}}.to_json
end
def post(action, options = {})
Campfire.post room_url_for(action), options
end
def room_url_for(action)
"/room/#{room_id}/#{action}.json"
end
end
twitter_auth = { :username => 'username',
:password => 'secret' }
def get_last_tweet_id(options = {})
options[:type] ||= "timeline"
path = File.expand_path(File.dirname(__FILE__) + "/last_tweet_#{options[:type]}_id")
`touch #{path}`
last_tweet_id = `cat #{path}`
last_tweet_id.blank? ? nil : last_tweet_id
end
def update_last_tweet_id(last_tweet_id, options = {})
options[:type] ||= "timeline"
path = File.expand_path(File.dirname(__FILE__) + "/last_tweet_#{options[:type]}_id")
`echo #{last_tweet_id} > #{path}`
end
def options_for_twitter_timeline(last_tweet_id)
last_tweet_id.nil? ? {:count => 1} : {:since_id => last_tweet_id.to_i}
end
begin
twitter_httpauth = Twitter::HTTPAuth.new(twitter_auth[:username], twitter_auth[:password])
twitter = Twitter::Base.new(twitter_httpauth)
room_id = Campfire.rooms.detect { |room| room["name"] == "Room Name" }["id"]
if room = Campfire.room(room_id)
tweets = twitter.user_timeline(options_for_twitter_timeline(get_last_tweet_id))
raise "Too many tweets! #{tweets.inspect}" if tweets.size > 3
tweets.reverse!
tweets.each do |tweet|
links = [] # auto_link is an easy way to extract all links, thanks Rails
auto_link(tweet.text, :link => :urls) { |l| links << l }
room.message "http://twictur.es/i/#{tweet.id}.gif"
room.message(links.to_sentence) if links.any?
end
update_last_tweet_id(tweets.last.id) if tweets.any?
else
warn "Failed to join room"
end
rescue Twitter::TwitterError, Twitter::Unavailable, Errno::ECONNRESET
# Just try again next time this runs
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment