Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
8
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@0tofu

rubyでtwitter/json-streamを使用し、Streaming APIからmongoDBに保存

TwitterのStreaming APIを使用するにあたって、取得したツイートすべてをmongoDBに保存するにはtwitter/json-streamを使うのが簡単そうだったので…

main.rb
# encoding: utf-8
#! ruby -Ku

require "rubygems"
require "bundler"
require "twitter/json_stream"
require "json"
require "mongo"
Bundler.require

#.envファイルより環境変数load
Dotenv.load

#mongodb接続用定義
db = Mongo::Connection.from_uri(ENV["MONGODB_URL"]).db(ENV["MONGODB_DB"])
#コレクション定義
@items = db.collection(ENV["MONGODB_COLLECTION"])

#EventMachine
EM.run do
  #Twitter Streaming APIのsampleStremの定義
  samplestream = Twitter::JSONStream.connect(
    :host => "stream.twitter.com",          #接続ホスト
    :path => "/1.1/statuses/sample.json",   #接続ホスト以降のURL
    :ssl => true,                           #SSL通信
    :oauth => {                             #oauth認証情報
      :consumer_key => ENV["CONSUMER_KEY"],
      :consumer_secret => ENV["CONSUMER_SECRET"],
      :access_key => ENV["ACCESS_KEY"],
      :access_secret => ENV["ACCESS_SECRET"]
    }
  )

  #sampleStreamより取得したアイテムをmongodbへ挿入
  samplestream.each_item do |item|
    tweet = JSON.parse(item)  #ツイートの内容をjson形式に変換
    if tweet["lang"] == "ja"  #日本語ツイートのみ取得対象とする
      @items.insert(tweet)    #json形式に変換したツイートをmongodbへ挿入
    end
  end
end

Gemfileに使用するgemを記載

Gemfile
ruby "2.1.0"

source "https://rubygems.org"

gem "twitter-stream"
gem "json"
gem "mongo"
gem "bson"
gem "bson_ext"
gem "dotenv"

.envファイルにはmongoDB接続及びTwitterの認証キーをセットする

#mongoDB
MONGODB_URL = "mongodb://<uid>:<password>@localhost/db_name"
MONGODB_DB = "db_name"
MONGODB_COLLECTION = "collection_name"

#Twitter
CONSUMER_KEY = "xxxxxxxx"
CONSUMER_SECRET = "xxxxxxxx"
ACCESS_KEY = "xxxxxxxx"
ACCESS_SECRET = "xxxxxxxx"

実行する時は以下のコマンド
bundle install
bundle exec ruby main.rb

8
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
8
Help us understand the problem. What is going on with this article?