Tuesday, 15 November 2011

Rails 3 and Twitter API

Rails 3 provides a very simple way to connect your application with TWITTER.
Here are the steps which you might need to post a tweet in your twitter account from your application :

1) First of all go to https://dev.twitter.com/apps and register your application. Make sure that you have configured "OAuth settings" and "Your access token" section in your Twitter application.
[Note : 'Access level' must have the 'read and write' privileges ]

2) Inside your gemfile add the Twitter gem:
gem 'twitter'

3) Next to install the gem simply open the console and do:
$ bundle install
or
$ bundle

4) Put the following code inside the view file ( eg, user_page.html.erb ) :

<%= form_for (@tweet = Tweet.new, :url => user_tweet_path) do |tweet_form| %>
<%= tweet_form.text_area :tweet_content, :id => "tweet" %>
<%= tweet_form.submit "Tweet" %>
<% end %>

5)  Now go to the respective controller and just add an action to handle the form submission :


def user_tweet
    require "rubygems"
    require "twitter"
 
    # Certain methods require authentication. To get your Twitter OAuth credentials,
    # register an app at http://dev.twitter.com/apps
    Twitter.configure do |config|
      config.consumer_key = ' << your consumer key >>'
      config.consumer_secret =  ' << your consumer secret >>'
      config.oauth_token = ' << your access token >> '
      config.oauth_token_secret = '<< your access token secret >>'
    end
 
    # Initialize your Twitter client
    client = Twitter::Client.new
 
    # Post a status update
    client.update("I just posted a status update via the Twitter Ruby Gem !")
    redirect_to request.referer, :notice => 'Tweet successfully posted'
end

6) TADA!!! your application is now connected to the twitter and you can post tweets directly from your application without going to twitter.com

Here are some more examples of functions to integrate with twitter API. Use the following codes inside any action to get the respective results :


require "rubygems"
require "twitter"

# Get a user's location
puts Twitter.user("sferik").location

# Get a user's most recent status update
puts Twitter.user_timeline("sferik").first.text

# Get a status update by id
puts Twitter.status(27558893223).text

# Initialize a Twitter search
search = Twitter::Search.new

# Find the 3 most recent marriage proposals to @justinbieber
search.containing("marry me").to("justinbieber").result_type("recent").per_page(3).each do |r|
  puts "#{r.from_user}: #{r.text}"
end

# Enough about Justin Bieber
search.clear

# Let's find a Japanese-language status update tagged #ruby
puts search.hashtag("ruby").language("ja").no_retweets.per_page(1).fetch.first.text

# And another
puts search.fetch_next_page.first.text

# Certain methods require authentication. To get your Twitter OAuth credentials,
# register an app at http://dev.twitter.com/apps
Twitter.configure do |config|
  config.consumer_key = YOUR_CONSUMER_KEY
  config.consumer_secret = YOUR_CONSUMER_SECRET
  config.oauth_token = YOUR_OAUTH_TOKEN
  config.oauth_token_secret = YOUR_OAUTH_TOKEN_SECRET
end

# Initialize your Twitter client
client = Twitter::Client.new

# Post a status update
client.update("I just posted a status update via the Twitter Ruby Gem!")

# Read the most recent status update in your home timeline
puts client.home_timeline.first.text

# Who's your most popular friend?
puts client.friends.sort{|a, b| a.followers_count <=> b.followers_count}.reverse.first.name

# Who's your most popular follower?
puts client.followers.sort{|a, b| a.followers_count <=> b.followers_count}.reverse.first.name

# Get your rate limit status
puts client.rate_limit_status.remaining_hits.to_s + " Twitter API request(s) remaining this hour"


19 comments:

  1. What is it: @tweet = Tweet.new ?
    I get error: => undefined method `new' for Twitter:Module
    when write so in my Ruby on Rails application...

    Can you help me?

    ReplyDelete
    Replies
    1. Writing @tweet = Tweet.new is same as writing in some_controller.rb
      def some_action
      ...
      ...
      @tweet = Tweet.new
      end
      And then writing it in the form view as form_for(@tweet,...)
      Add,
      require 'twitter'
      in the controller/other classes, if you are getting this error. If error persists, double check that you executed bundle install to install the twitter gem.

      Delete
    2. Thanks for answer.

      Delete
  2. correction to comment from 3 October 2012 15:02 ::

    I'm sorry, a have another error:
    uninitialized constant ActionView::CompiledTemplates::Tweet

    ReplyDelete
    Replies
    1. Can you just give me the surrounding lines of codes, that is giving you this error?

      Delete
  3. please hellp me as soon as possible
    error im getting "undefined method `new' for Twitter:Module"
    require "rubygems"
    require "twitter"

    class TwitterController < ApplicationController
    def user_page
    @twitter = Twitter.new
    end

    def user_twitter
    @twitter = Twitter.new(params[:twitter])

    if @twitter.save then
    # Certain methods require authentication. To get your Twitter OAuth credentials,
    # register an app at http://dev.twitter.com/apps
    Twitter.configure do |config|
    config.consumer_key = 'key'
    config.consumer_secret = 'skey'
    config.oauth_token = 'token'
    config.oauth_token_secret = 'token secret'

    end

    # Initialize your Twitter client
    client = Twitter::Client.new

    # Post a status update
    client.update(@twitter.twitter_content)
    end
    render action: 'user_page', :notice => 'Twitter successfully posted'

    end

    end

    ReplyDelete
    Replies
    1. Hi Sai,

      I think there is some problem with the methods you defined.
      Try replacing Twitter.new with Tweet.new.
      That is,
      def user_page
      @twitter = Tweet.new
      end

      and same for method user_twitter.

      Try that, and get back to me if this is not helping you to get rid of the error.

      Thanks,
      Souvik

      Delete
    2. hey i change total code again

      Showing /home/wafuser/deployment/twitter/games/app/views/tweet/user_page.html.erb where line #2 raised:

      now im getting error:undefined method `tweet_content' for #



      in controller
      require "rubygems"
      require "twitter"

      class TweetController < ApplicationController
      def user_page
      @tweet = Tweet.new
      end

      def user_tweet
      @tweet = Tweet.new(params[:tweet])

      if @tweet.save then
      # Certain methods require authentication. To get your Twitter OAuth credentials,
      # register an app at http://dev.twitter.com/apps
      Twitter.configure do |config|
      config.consumer_key = 'key'
      config.consumer_secret = 'skey'
      config.oauth_token = 'token'
      config.oauth_token_secret = 'stoken'

      end

      # Initialize your Twitter client
      client = Twitter::Client.new

      # Post a status update
      client.update(@tweet.tweet_content)
      end
      render action: 'user_page', :notice => 'Twitter successfully posted'

      end

      end
      in model
      class Tweet < ActiveRecord::Base
      # attr_accessible :title, :body
      attr_accessible :tweet_content
      end
      in user_page.html.erb
      <%= form_for(@tweet, :url => '/user_tweet') do |tweet_form| %>
      <%= tweet_form.text_area :tweet_content %>
      <%= tweet_form.submit "Tweet" %>
      <% end %>

      Delete
    3. please help me as soon as possible because 2morrow last date for ower project submittion
      final i got corrected will i had created
      rails g model tweet tweet_content:string

      now when i created tweet text it coming error like:
      Timestamp out of bounds
      app/controllers/tweet_controller.rb:25:in `user_tweet'

      Delete
  4. how does your routes and database look like, i am assuming you have to create one. but idk how to set it up.

    thanks

    ReplyDelete
  5. Hey everyone, let me clarify on this gem.
    Although it's a nice simple way of tweeting to your own application, you should avoid using this where users need to authenticate via twitter.
    Database structure is upon necessity of developers. For example,say, if you want to keep track of what tweets are being sent from your rails application, create a new field called user_tweet in database and populate it accordingly.

    Main usage notes:

    Put settings for twitter inside an initializer file like config/initializers/twitter_settings.rb:

    # app settings obtained from twitter
    Twitter.configure do |config|
    config.consumer_key = 'key'
    config.consumer_secret = 'skey'
    config.oauth_token = 'token'
    config.oauth_token_secret = 'token secret'
    end

    Open up your rails console:
    1.9.3p194 :001 > client = Twitter::Client.new
    1.9.3p194 :002 > client.update("Hello from Twitter Ruby Gem !")

    And, that's it. It will post a new tweet for the account for which the app tokens are provided.

    Similarly you can use other methods mentioned above.

    I will be posting authentication via twitter soon.

    Thanks,
    Souvik

    ReplyDelete
  6. This gem is not recommended if there are multiple users and they all want to post status updates to their respective accounts. It will really be a pain to manage. But for simple purposes this gem will rock!

    Keep an eye on this blog for a better solution.

    ReplyDelete
  7. after searching lot of blogs my search ends here finally. Thanks works great for me !!
    now i am in the searching of twitter authentication. its too painful for me, tried several gems but getting and getting several errors. Guide me here @Souvik Dey

    ReplyDelete
    Replies
    1. I would love to help. It will be good if you give me a scenario. You want people to sign up via twitter or something like that?

      Delete
    2. yeah.. if the user login with twitter/facebook then the user details should be store in local database, and redirect to actual site home page.
      It would be really helpful for me and the people like me if you make a new post on that.

      Delete
    3. it will take me some time to do a post on that. if you are looking for the solution in a hurry, you can share your email id and i'll pass you some links on how to do it for the time being.

      Delete
  8. Can you please update this post? Seems the code you provided no longer works on Rails 4. Thanks!

    ReplyDelete
  9. Thanks for sharing such a nice information. Cryptex Technologies is well-known for Rails development company. If you have any email us at: info@cryptextechnologies.com

    ReplyDelete