twitter_tweet_bot

Tweet Bot with Twitter's V2 API.
(by OAuth 2.0 with PCKE)

Getting Started

# Gemfile
gem 'twitter_tweet_bot'

Then run bundle install.

Usage

require 'twitter_tweet_bot'

TwitterTweetBot.post_tweet(<ACEESS_TOKEN>, 'Yeah!')
  1. Configuration
  2. Issue Authorization URL
  3. Go to Authorization URL
  4. Fetch Access Token
  5. Post Tweet
Details #### Step1. Configuration ```rb require 'twitter_tweet_bot' TwitterTweetBot.configure do |config| # Twitter's Bot Name (any) config.name = 'iambot' # Twitter's Client ID config.client_id = '*****' # Twitter's Client Secret config.client_secret = '*****' # Redirect URL After Authorization config.redirect_uri = 'https://example.com/twitter/callback' # Twitter's App Scopes with OAuth 2.0 config.scopes = %w[tweet.read tweet.write users.read offline.access] end ``` #### Step2. Issue an authorization url ```rb authorization = TwitterTweetBot.authorize # => # # ``` #### Step3. Redirect (or Go) to `authorization.url` And smash `"Authorize app"`. If authorized, redirected to your `config.redirect_uri`.
Check **CODE** in Twitter's response. ``` e.g. https://example.com/twitter/callback?state=***&code=***** ``` #### Step4. Fetch an access token ```rb token = TwitterTweetBot.fetch_token('', authorization.code_verifier) # => # # ``` #### Step5. Post a tweet ```rb TwitterTweetBot.post_tweet(token.access_token, 'Yeah!') # => # # ``` ##### With [some params](https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets) ```rb TwitterTweetBot.post_tweet(token.access_token, 'Yeah! Yeah!') do |params| params.reply = { in_reply_to_tweet_id: '*******************' } end ``` #### Ex. Refresh an access token (required `'offline.access'` in scopes) ```rb TwitterTweetBot.refresh_token(token.refresh_token) ```

Caching

TwitterTweetBot can cache follow variables automatically in any store (like Rails.cache).

  • code_verifier
  • state
  • access_token
  • refresh_token

If needed, require 'twitter_tweet_bot/cache'.

require 'twitter_tweet_bot/cache'

TwitterTweetBot.post_tweet('Yeah!')
Details #### Step1. Configuration ```rb require 'twitter_tweet_bot/cache' TwitterTweetBot.configure do |config| # ... # Any Cache Store (required `#write(key, value)` and `#read(key)` implementation). config.cache_provider = ActiveSupport::Cache.lookup_store(:file_store, '../tmp/cache') end ``` #### Step2. Issue an authorization url ```rb # `code_verifier` and `state` will be cached. TwitterTweetBot.authorize ``` #### Step3. Fetch an access token ```rb # `access_token` and `refresh_token` will be cached. TwitterTweetBot.fetch_token('') ``` Don't need to pass `code_verifier`.
(resolved from cache) #### Step4. Post a tweet ```rb TwitterTweetBot.post_tweet('Yeah!') ``` Don't need to pass `access_token`.
(resolved from cache) #### Ex. Check a cache ```rb TwitterTweetBot.client.cache.read # => # { :code_verifier=>"*****", :state=>"***", :access_token=>"*****", :refresh_token=>"*****" } ```