class Msgtrail::Twitter

Constants

CONTENT_TYPE_HEADER
EXPECTED_TOKEN_TYPE
POST_AUTHENTICATION
PRE_AUTHENTICATION
TWITTER_API_OAUTH_ENDPOINT
TWITTER_API_STATUS_ENDPOINT
TWITTER_AUTH_BODY
TWITTER_STATUS_ENDPOINT

Public Class Methods

authenticate() click to toggle source
# File lib/msgtrail/twitter.rb, line 25
def self.authenticate
  api_key = ENV['TWITTER_CONSUMER_API_KEY']
  secret = ENV['TWITTER_CONSUMER_SECRET_KEY']
  credentials = Base64.strict_encode64("#{api_key}:#{secret}")
  begin
    result = HTTP.auth(PRE_AUTHENTICATION % credentials)
                 .headers(CONTENT_TYPE_HEADER)
                 .post(TWITTER_API_OAUTH_ENDPOINT, body: TWITTER_AUTH_BODY)
  rescue
    puts("Failed to authenticate with Twitter API (#{$!})")
    exit(2)
  end
  begin
    json = MultiJson.load(result.to_s, symbolize_keys: true)
  rescue
    puts("Invalid JSON from '#{TWITTER_API_OAUTH_ENDPOINT}' (#{$!})")
    exit(2)
  end
  EXPECTED_TOKEN_TYPE == json[:token_type] ? json[:access_token] : nil
end
fetch(tweet_id) click to toggle source
# File lib/msgtrail/twitter.rb, line 17
def self.fetch(tweet_id)
  if access_token = authenticate
    full_tweet_text(access_token, tweet_id)
  else
    puts("Failed to authenticate with Twitter API")
  end
end
full_tweet_text(access_token, tweet_id) click to toggle source

There seem to be two ways to get to any tweet by its ID:

  1. twitter.com/i/web/status/{id}

  2. twitter.com/statuses/#{id}

Using former method which seems to work best on desktop and mobile.

# File lib/msgtrail/twitter.rb, line 50
def self.full_tweet_text(access_token, tweet_id)
  url = TWITTER_API_STATUS_ENDPOINT % tweet_id
  begin
    result = HTTP.auth(POST_AUTHENTICATION % access_token)
                 .get(url)
  rescue
    puts("Failed to get tweet from '#{url}' (#{$!})")
    exit(2)
  end
  begin
    json = MultiJson.load(result.to_s, symbolize_keys: true)
  rescue
    puts("Invalid JSON from '#{url}' (#{$!})")
    exit(2)
  end
  {
    body: json[:full_text],
    source: TWITTER_STATUS_ENDPOINT % tweet_id,
    type: Article::TYPE_TWEET
  }
end
tweet_bodies(tweet_ids) click to toggle source
# File lib/msgtrail/twitter.rb, line 13
def self.tweet_bodies(tweet_ids)
  tweet_ids.map { |tweet_id| fetch(tweet_id) }
end