Skip to content

Instantly share code, notes, and snippets.

@zackster
Last active July 19, 2016 03:03
Show Gist options
  • Save zackster/ac4e1bf2916a0f7d99f772bec46170de to your computer and use it in GitHub Desktop.
Save zackster/ac4e1bf2916a0f7d99f772bec46170de to your computer and use it in GitHub Desktop.
This worker will post messages from an Amazon SQS queue via the StockTwits API. It requires you to have an access_token (obtained via the Stocktwits API) and an SQS queue with messages containing the contents of your StockTwits messages. It respects the StockTwits API rate limitations through an exponential backoff algo.
require 'aws-sdk'
require 'unirest'
require 'pp'
STOCKTWITS_QUEUE_URL = 'PATH TO YOUR QUEUE GOES HERE...' # looks like https://sqs.REGION.amazonaws.com/######/name
STOCKTWITS_API_URL = 'https://api.stocktwits.com/api/2/messages/create.json?access_token=ACCESS_TOKEN_OF_STOCKTWITS_USER_TO_POST'
Aws.config.update({
region: 'REGION',
credentials: Aws::Credentials.new('ACCESS KEY', 'SECRET')
})
SQS_CLIENT = Aws::SQS::Client.new
def check_for_messages
resp = SQS_CLIENT.receive_message({
queue_url: STOCKTWITS_QUEUE_URL,
max_number_of_messages: 1
})
if resp.messages.size > 0
message_body = resp.messages.first.body
receipt_handle = resp.messages.first.receipt_handle
stocktwits_response = Unirest.post STOCKTWITS_API_URL, headers:{ "Accept" => "application/json" }, parameters: {:body => message_body}
unless stocktwits_response.code == 200
PP.pp stocktwits_response
raise 'Rate limited or other error'
end
resp = SQS_CLIENT.delete_message({
queue_url: STOCKTWITS_QUEUE_URL,
receipt_handle: receipt_handle
})
else
puts 'No messages'
end
end
iter = 0
while true
begin
check_for_messages
iter = 0
rescue Exception => e
puts e
iter += 1
end
sleep (1.0/2.0*(2.0**iter - 1.0)).ceil # exponential backoff
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment