journalduhacker/script/post_to_twitter
joshua stein b4444c58c9 twitter stupidly "shortens" find.com into http://t.co/u44JiITiuc, cope
try to pluck out simple urls in basic tlds and treat their length as
a t.co url if it's longer than the url being shortened

of course this will not catch all urls, but i'm not going to load a
whole suffix list or library just to deal with this stupid shit
2015-04-17 09:16:08 -05:00

73 lines
1.7 KiB
Ruby
Executable file

#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= "production"
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
require APP_PATH
Rails.application.require_environment!
MIN_STORY_SCORE = 2
Story.where("is_expired = ? AND #{Story.score_sql} > ? AND " <<
"twitter_id IS NULL AND created_at >= ?", false, MIN_STORY_SCORE,
Time.now - 1.days).order(:id).each_with_index do |s,x|
if s.tags.map(&:tag).include?("meta")
next
end
if x > 0
sleep 2
end
tags = ""
s.sorted_taggings.each do |tagging|
tags += ' #' + tagging.tag.tag
end
tco_status = "\n" +
(s.url.present?? ("X" * Twitter::TCO_LEN) + "\n" : "") +
("X" * Twitter::TCO_LEN) +
tags
status = "\n" +
(s.url.present?? s.url + "\n" : "") +
s.short_id_url +
tags
left_len = Twitter::MAX_TWEET_LEN - tco_status.length
title = s.title
if title.match(/^([dm] |@)/i)
# prevent these tweets from activating twitter shortcuts
# https://dev.twitter.com/docs/faq#tweeting
title = "- #{title}"
end
# if there are any urls in the title, they should be sized (at least) to a
# twitter t.co url
left_len -= (title.scan(/[^ ]\.(com|org|net|edu)/i).map{|u| [ 0,
Twitter::TCO_LEN ].max }.inject(:+)).to_i
if title.bytesize > left_len
status = title[0, left_len - 3] + "..." + status
else
status = title + status
end
res = Twitter.oauth_request("/1.1/statuses/update.json", :post,
{ "status" => status })
begin
if res["id_str"].match(/\d+/)
s.update_column("twitter_id", res["id_str"])
else
raise
end
rescue => e
puts "failed posting story #{s.id} (#{status.inspect}): #{e.inspect}\n" +
"#{res.inspect}"
exit
end
end