Monday, 17 September 2012

How to send direct message to your followers via twitter using rails

How to send direct message to your followers 
via twitter using rails

Step-1 : authenticate twitter with rails
             require 'twitter'

             def twitter
client =
                   :consumer_key =>  'consumer key',
                   :consumer_secret => 'consumer secret key'
request_token = client.request_token(:oauth_callback =>'callback url' )
session[:request_token] = request_token.token
                 session[:request_token_secret] = request_token.secret
redirect_to request_token.authorize_url
            // redirect url (callback url)

            def twitter_invite_friend

Step-2 : configure your twitter account 

             def twitter_direct_message_to_friends
                 Twitter.configure do |config|
                    config.consumer_key = 'consumer key'
                   config.consumer_secret = 'consumer secret key'
                @client =
                     :oauth_token => 'oauth token',
                     :oauth_token_secret => 'oauth secret token'

Step-3 : fetch twitter friends
             // try in console
             // you will get following result

               => [:new, :method_missing, :respond_to?, :adapter, :adapter=, :connection_options, :connection_options=, :consumer_key, :consumer_key=, :consumer_secret, :consumer_secret=, :endpoint, :endpoint=, :gateway, :gateway=, :oauth_token, :oauth_token=, :oauth_token_secret, :oauth_token_secret=, :proxy, :proxy=, ..... ]

             all_followers = @client.follower_ids // we get all followers

             friend_list = @client.follower_ids.ids // we get all followers ids
             // we are sending direct message so we need only ids so that we use second

Step-4: Send direct message to 1 friend
            Twitter.direct_message_create('screen_name', "message") // send direct message

Step-5: Send direct message to all friend

            friend_list.each do |id|
  Twitter.configure do |config|
                 config.consumer_key =  'consumer key'
             config.consumer_secret = 'consumer secret key'
                 config.oauth_token =  'oauth token',
                 config.oauth_token_secret = 'oauth secret token'
             Twitter.direct_message_create('twitter friend id', "message")  // send direct message

1 comment:

  1. Hello dipak,When I am redirecting the user to twitter action in step1... I am getting this error."401 Unauthorized" Can you please help me in this.....