MKK
MKK

Reputation: 2753

How can I send tweets to my Twitter account?

Every time the user post a comments, I want it to send the same comment to my Twitter automatically.

First of all, I have it already done with Twitter developer settings.

So I made a test action in my App to make it send a tweet to my Twitter account. However, it says this error

NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/top_controller.rb:173:in `test_action'

How can I solve this? These are my codes

gems related that are already bundled (I'm on rails 3.2.11)

gem 'omniauth-twitter'
gem 'twitter'
gem 'figaro'

config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
    Twitter.configure do |config|
        config.consumer_key = ENV["TWITTER_KEY"]
        config.consumer_secret = ENV["TWITTER_SECRET"]
    end
end

config/application.yml

TWITTER_KEY: 6TeBX6HkeHzMXesgc
TWITTER_SECRET: JyfOndg8xHcM81KEpgmBT7h2vFJJujMP14YTdt6ruvLbsQk

test_action

def test_action  
    @twitter = Twitter::Client.new(oauth_token: request.env["omniauth.auth"][:credentials][:token], oauth_token_secret: request.env["omniauth.auth"][:credentials][:secret])
    @twitter.update("Your message")
    flash[:notice] = "Successfully tweeted on your account."
    redirect_to root_path
    return 
end

Upvotes: 1

Views: 841

Answers (1)

abcm1989
abcm1989

Reputation: 81

I think your issue may be with your controller configuration of Twitter:

instead of:

@twitter = Twitter::Client.new(oauth_token: request.env["omniauth.auth"][:credentials][:token], oauth_token_secret: request.env["omniauth.auth"][:credentials][:secret])

try this:

@twitter = Twitter::REST::Client.new do |config|
  config.consumer_key = ENV['CONSUMER_KEY']
  config.consumer_secret = ENV['CONSUMER_SECRET']
  config.access_token = request.env["omniauth.auth"][:credentials][:token]
  config.access_token_secret = request.env["omniauth.auth"][:credentials][:secret]
end

You also might want to confirm that your API keys have read and write permissions, which you can check on your Twitter developer account here.

Upvotes: 2

Related Questions