如何将推文发送到我的Twitter帐户?

时间:2014-08-30 11:45:42

标签: ruby-on-rails ruby-on-rails-3 twitter twitter-oauth

每次用户发表评论时,我都希望它自动向Twitter发送相同的评论。

首先,我已经完成了Twitter开发人员设置。

所以我在我的应用程序中做了一个测试操作,让它向我的Twitter帐户发送推文。 但是,它说这个错误

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

我该如何解决这个问题?这些是我的代码

已捆绑的相关宝石(我在轨道3.2.11上)

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

配置/初始化/ 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

配置/ 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

1 个答案:

答案 0 :(得分:2)

我认为您的问题可能出在Twitter的控制器配置上:

而不是:

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

试试这个:

@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

您还可能需要确认您的API密钥具有读写权限,您可以在Twitter开发者帐户here上查看。