0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

twitterAPIで自動ツイートをしたい

Last updated at Posted at 2022-07-09

APIキーを取得

やり方
callback url は http://127.0.0.1:3000/oauth/callback

gem

公式のdeveloper platformsample codeがあったのでそれに則っていく

gem install typhoeus

httpクライアントとして使用

gem install oauth

APIキーの認証に使う

gem install dotenv

今回自分はDockerを使用したので、環境変数を渡すのに便利な'dotenv'も使用しました

コーディング

ファイルの作成

touch tweet.rb

ほぼコピペでいいのですが、sample codeのままだと毎回実行するたびにアクセストークンの発行をしてしまうので、ruby標準ライブラリのpstoreを使って保存していきます

# require 'dotenv'
require 'pstore'
require 'oauth'
require 'json'
require 'typhoeus'
require 'oauth/request_proxy/typhoeus_request'
 
# キーは環境変数から
consumer_key = ENV['CONSUMER_KEY']
consumer_secret = ENV['CONSUMER_SECRET']

create_tweet_url = "https://api.twitter.com/2/tweets"

db = PStore.new("/tmp/access_token")

# これがツイートの内容
@json_payload = {"text": "Hello world!"}
 
consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
 :site => 'https://api.twitter.com',
 :authorize_path => '/oauth/authenticate',
 :debug_output => false)
 
def get_request_token(consumer)
 
 request_token = consumer.get_request_token()
 
 return request_token
end
 
def get_user_authorization(request_token)
 puts "Follow this URL to have a user authorize your app: #{request_token.authorize_url()}"
 puts "Enter PIN: "
 pin = gets.strip
 
 return pin
end
 
def obtain_access_token(consumer, request_token, pin)
 token = request_token.token
 token_secret = request_token.secret
 hash = { :oauth_token => token, :oauth_token_secret => token_secret }
 request_token = OAuth::RequestToken.from_hash(consumer, hash)
 # Get access token
 access_token = request_token.get_access_token({:oauth_verifier => pin})
 return access_token
end
 
 
def create_tweet(url, oauth_params)
 options = {
 :method => :post,
 headers: {
 "User-Agent": "v2CreateTweetRuby",
 "content-type": "application/json"
 },
 body: JSON.dump(@json_payload)
 }
 request = Typhoeus::Request.new(url, options)
 oauth_helper = OAuth::Client::Helper.new(request, oauth_params.merge(:request_uri => url))
 request.options[:headers].merge!({"Authorization" => oauth_helper.header}) # Signs the request
 response = request.run
 
 return response
end
 
 
 
def run_oauth(consumer)
 request_token = get_request_token(consumer)
 pin = get_user_authorization(request_token)
 access_token = obtain_access_token(consumer, request_token, pin)
end


db.transaction do 
  unless access_token = db["token"]
    access_token = run_oauth(consumer)
    db["token"] = access_token
  end
  oauth_params = {:consumer => consumer, :token => access_token}
  response = create_tweet(create_tweet_url, oauth_params)
  puts response.code, JSON.pretty_generate(JSON.parse(response.body))
end

ツイートのパラメータについては
Post, retrieve, and engage with Tweets

実行

ターミナルから

ruby tweet.rb

初実行時のみ、URLの表示とPINを入力しろと出る。
URLにアクセスし、認証すると出てくる7けたの数字を入力してEnter
二回目以降は、pin入力なしで実行できる。
ただし、同じ内容のツイートは連投できないので、ツイート内容は変更しなければならない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?