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!')
- Configuration
- Issue Authorization URL
- Go to Authorization URL
- Fetch Access Token
- 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 # => # #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)
# =>
# #" , # @expires_in="7200," # @refresh_token="" , # @scope="tweet.write users.read tweet.read offline.access" , # @token_type="bearer">
```
#### 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=>"*****" }
```