Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

Why do not you register as a user and use Qiita more conveniently?
  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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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