These instructions set up a way to publish tweets to Twitter's OAuth2 API from a Ruby on Rails app.
-
Set up a twitter account via the Twitter account setup instructions here: https://github.com/jkotchoff/twitter_oauth2#twitter-account-setup
-
Add the twitter_oauth2 gem and something to issue HTTP requests (like Typhoeus) to your Gemfile:
gem 'twitter_oauth2'
gem 'typhoeus'
- Introduce a rails migration to persist your oauth2 token in a single database record in a table (and update it when it needs refreshing)
class CreateTwitterTokens < ActiveRecord::Migration[7.0]
def change
create_table :twitter_tokens do |t|
t.string :marshaled_client, null: false
t.string :marshaled_token, null: false
t.timestamps
end
end
end
-
Retrieve and persist your token (refer one-off.rb in this gist)
-
Use the token to write tweets to the twitter API, refreshing and persisting the token when it expires (refer app/models/twitter.rb in this gist)
Hey @nezirz, you’ll want to run the one off code in a console. On line 22, you’ll see a url which will be printed to output which you can open in your browser manually. You’ll want that browser to be already authenticated into your twitter developer account.
That url will prompt you for permission and then redirect your local browser to the callback url (ie. the stocklight url) which probably won’t resolve properly however it will contain a ‘code’ query string parameter which you can then take off that redirected url and use in the rest of the one-off script.