使用 Ruby Gem 为 Twitter 获取标签的搜索结果

Using Ruby Gem for Twitter to get search results of a Hashtag

我正在尝试使用此 Twitter gem 连接 Twitter 和 return 具有特定主题标签的所有推文的列表。截至目前,我已经能够连接到 API 和 return 数据,所以我知道连接正常。我已经通读了文档,只是不明白如何实现我所看到的。我对连接和使用 APIs 真的很陌生,如果能提供一些说明,我将不胜感激。这是我到目前为止的代码。

宝石文件

#####################
### My Added Gems ###
#####################

# Define Ruby Version
ruby "2.5.0"

# Social Connections
gem 'twitter'

# ENV Variables
gem 'dotenv-rails'

views/pages/home.html.erb

<h1>Tweets</h1>
<% @tweets.each do |tweet| %>
  <%= tweet.full_text %>
  <br>
<% end %>

controllers/pages_controller.rb

class PagesController < ApplicationController
  require 'twitter'

  def home
    client = Twitter::REST::Client.new do |config|
      config.consumer_key        = ENV.fetch("YOUR_CONSUMER_KEY")
      config.consumer_secret     = ENV.fetch("YOUR_CONSUMER_SECRET")
      config.access_token        = ENV.fetch("YOUR_ACCESS_TOKEN")
      config.access_token_secret = ENV.fetch("YOUR_ACCESS_SECRET")
    end

    @tweets = client.user_timeline('trendingfaith', count: 20)

  end
end

这会打印出用户@TrendingFaith 的推文列表。

我试图让它打印出所有带有#TrendingFaith 标签的推文:

pages_controller.rb

class PagesController < ApplicationController
  require 'twitter'

  def home
    tweets = Twitter::REST::Search.new do |config|
      config.consumer_key        = ENV.fetch("YOUR_CONSUMER_KEY")
      config.consumer_secret     = ENV.fetch("YOUR_CONSUMER_SECRET")
      config.access_token        = ENV.fetch("YOUR_ACCESS_TOKEN")
      config.access_token_secret = ENV.fetch("YOUR_ACCESS_SECRET")
    end
    @tweets = tweets.search(q, options = {:hash => 'trendingfaith'}) ⇒ Twitter::SearchResults

  end
end

出现以下错误:syntax error, unexpected tIDENTIFIER, expecting keyword_end

我试着通读 this doc on the Twitter Gem and the Twitter API docs。就是这个时候看不懂,不知道怎么实现。任何指导将不胜感激。

更新:收到答复后的工作代码

根据@SimonF运行zen 的回答,我缺少的代码是 client.search('#SpecificTag') 用于搜索特定主题标签的语法。

这是我的代码现在的样子:

controllers/pages_controllers.rb

class PagesController < ApplicationController
  require 'twitter'

  def home
    tweets = Twitter::REST::Client.new do |config|
      config.consumer_key        = ENV.fetch("YOUR_CONSUMER_KEY")
      config.consumer_secret     = ENV.fetch("YOUR_CONSUMER_SECRET")
      config.access_token        = ENV.fetch("YOUR_ACCESS_TOKEN")
      config.access_token_secret = ENV.fetch("YOUR_ACCESS_SECRET")
    end
    @tweets = tweets.search('#TrendingFaith')
  end
end

我 运行 byebug 对此进行了搜索,并且能够看到通过此搜索从 Twitter 返回的数据。 (见下面的哈希数据)因此能够像这样更新我的观点:

views/pages/home.html.erb

<h1>TrendingFaith.org - Coming Soon</h1>
<% @tweets.each do |tweet| %>
  User @<%= tweet.user.screen_name %> said: "<%= tweet.text %>" on <%= tweet.created_at.strftime('%-m/%d/%Y') %>
  <br>
<% end %>

这能够提取 Twitter 用户的姓名、推文的文本以及他们发推文的时间。这正是我要找的。

return发给我的 Twitter 散列,放在这里供可能想知道的其他人使用。另外,您可以在页面底部 see it here in their documentation

{
  :created_at=>"Sun Mar 04 18:20:42 +0000 2018", 
  :id=>970363418858332160, 
  :id_str=>"970363418858332160", 
  :text=>"A place where you can find things trending in the Christian faith. Questions and stories. #TrendingFaith", 
  :truncated=>false, 
  :entities=>
    {
      :hashtags=>[{
        :text=>"TrendingFaith", 
        :indices=>[90, 104]
      }], 
      :symbols=>[], 
      :user_mentions=>[], 
      :urls=>[]
    }, 
  :metadata=>
    {
      :iso_language_code=>"en", 
      :result_type=>"recent"
    }, 
  :source=>"<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>", 
  :in_reply_to_status_id=>nil, 
  :in_reply_to_status_id_str=>nil, 
  :in_reply_to_user_id=>nil, 
  :in_reply_to_user_id_str=>nil, 
  :in_reply_to_screen_name=>nil, 
  :user=>
    {
      :id=>970155879180873733, 
      :id_str=>"970155879180873733", 
      :name=>"Trending Faith", 
      :screen_name=>"TrendingFaith", 
      :location=>"", 
      :description=>"", 
      :url=>#Twitter URL Shortener (Had to remove for Whosebug),  
      :entities=>
        {
          :url=>
            {
              :urls=>[
                {
                  :url=>#Twitter URL Shortener (Had to remove for Whosebug), 
                  :expanded_url=>"http://trendingfaith.org", 
                  :display_url=>"trendingfaith.org", 
                  :indices=>[0, 23]
                }
              ]
            }, 
          :description=>
            {
              :urls=>[]
            }
        }, 
      :protected=>false, 
      :followers_count=>0, 
      :friends_count=>3, 
      :listed_count=>0, 
      :created_at=>"Sun Mar 04 04:36:00 +0000 2018", 
      :favourites_count=>0, 
      :utc_offset=>nil, 
      :time_zone=>nil, 
      :geo_enabled=>false, 
      :verified=>false, 
      :statuses_count=>1, 
      :lang=>"en", 
      :contributors_enabled=>false, 
      :is_translator=>false, 
      :is_translation_enabled=>false, 
      :profile_background_color=>"F5F8FA", 
      :profile_background_image_url=>nil, 
      :profile_background_image_url_https=>nil, 
      :profile_background_tile=>false, 
      :profile_image_url=>"http://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png", 
      :profile_image_url_https=>"https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png", 
      :profile_link_color=>"1DA1F2", 
      :profile_sidebar_border_color=>"C0DEED", 
      :profile_sidebar_fill_color=>"DDEEF6", 
      :profile_text_color=>"333333", 
      :profile_use_background_image=>true, 
      :has_extended_profile=>false, 
      :default_profile=>true, 
      :default_profile_image=>true, 
      :following=>false, 
      :follow_request_sent=>false, 
      :notifications=>false, 
      :translator_type=>"none"
    }, 
  :geo=>nil, 
  :coordinates=>nil, 
  :place=>nil, 
  :contributors=>nil, 
  :is_quote_status=>false, 
  :retweet_count=>0, 
  :favorite_count=>0, 
  :favorited=>false, 
  :retweeted=>false, 
  :lang=>"en"
}

新问题

现在弄清楚为什么只有一条推文返回,因为有数百条带有我正在搜索的主题标签,但只有一条适合我。我通过搜索主题标签“#HelloWorld”进行了检查,结果返回了很多。所以,它不仅仅是搜索我的推文。我猜所有其他带有我正在寻找的标签的人可能都是私人推文,除非通过 Twitter 才能拉取?或者这是我的代码的另一个问题?如果这与我原来的问题无关,我可以创建一个新问题并提问。

最终更新:对上一个问题的回答

之所以只有我的推文被拉取主题标签 'TrendingFaith' 但拉取主题标签时我收到了更多推文 'HelloWorld' 是因为只有我的推文是在过去一周内发布的'#TrendingFaith'。标准 Twitter API 搜索仅提取过去 7 天的推文。您必须拥有高级或企业级帐户才能搜索 30 天或完整存档的帖子。他们的 Premium 级别目前(截至 2018 年 3 月 4 日)处于测试阶段,正在接受请求进入他们的候补名单。

Link to Twitter Page

使用twitter gem

gem install twitter

或将其包含在您的 Gemfile 中

创建 Twitter 应用程序,获取授权码

初始化API

require 'twitter'

client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "YOUR_CONSUMER_KEY"
  config.consumer_secret     = "YOUR_CONSUMER_SECRET"
  config.access_token        = "YOUR_ACCESS_TOKEN"
  config.access_token_secret = "YOUR_ACCESS_SECRET"
end

提出请求"Tweets for user"

// get from user
tweets = client.user_timeline('rubyinside', count: 20)
tweets.each { |tweet| puts tweet.full_text }

提出请求"Search by hashtag"

client.search('#searchHash').take(3).each do |tweet|
  puts tweet.inspect
end

检查此以建立您的查询:https://www.hitchhq.com/twitter/activities/592c37f4da4746638900618ehttps://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets