LoginSignup
9
12

More than 5 years have passed since last update.

twitterのapiを使ってrailsからtweet

Posted at

作りたいモノ

railsのアプリ上でtwitterログインした後にそのtwitterアカウントでrailsからtweet

twitterのomnioathでtwitterログインを実装

twitterのapiは基本的にはomnioath認証されているアカウントを通してじゃないと行えない。

omniauthはココに乗っているやり方で実装

twitter apiのkey取得

Get started: Build an app on Twitter
Twitter’s API platform includes numerous endpoints to help you build an app and solution on Twitter. Our basic endpoints are available for free. As your app or solution needs grow, you’ll also find enterprise APIs that include increased levels of access.

Get started with the basic REST and Streaming APIs
Twitter’s basic REST and Streaming APIs enable free access to numerous endpoints. To get started, you must first create an app.

1. Create an app
To use an endpoint, you must create an app and use our OAuth-based authorization system. Visit apps.twitter.com to create one.

2. Start using the endpoints!
Once you’ve setup your account, accessing the endpoint is super simple. Check out the documentation and API reference for additional details about each endpoint. There are many libraries and utilities in different programming languages that can help you to get started.

Have a question? There’s a good chance our community has an answer for you. Visit our developer forums to review topics, ask questions, and learn from others.

上記のようにまずはappアカウントを作成し、keyを発行しないといけない。気をつけないといけないのがpermissionでデフォルトはread onlyなので書き込みも許可する。

twitter gemをinstall

twitterのapiを利用するためのgemがあるのでそれをinstall。

controller作成

ここからはこの記事を参考にした。twitter gemにメソッドがあるのでそれを使っていく。そのメソッドを使う前にbefore_actionでkeyの情報を渡している。

post_controller.rb
class ArticlesController < ApplicationController
  before_action :twitter_client, only: [:create]

  def create
    @post = Post.new(content:params[:content],title:params[:title],user_id:params[:user_id])
    if @post.save
      @client.update("テスト")
      redirect_to root_path
    end
  end
  private
  def twitter_client
    @client = Twitter::REST::Client.new do |config|
      config.consumer_key = "自分のConsumer Keyを選択"
      config.consumer_secret = "自分のConsumer Secretを選択"
      config.access_token = "自分のAccess tokenを選択"
      config.access_token_secret ="自分のAccess token secretを選択"
    end
  end
end

Could not authenticate you.がでたら

なんか何回かkeyをregenerateしないとエラーが出る。Could not authenticate you.とでたらregenerateしてみよう。

9
12
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
9
12