LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

【初心者向け】【Mac】Rubyを使ってTwitter情報を使って遊ぼう!(全二回)

Last updated at Posted at 2016-07-17

Rubyのコードを書いて実行する

手順1:twitterのGemをインストールする

twitterの情報を取得する際に必要な外部ライブラリをgemコマンドを使ってインストールします。
以下のコマンドをターミナル上で実行します。

sudo gem install twitter

以下のような出力が出たら成功です。

スクリーンショット 2016-07-17 14.32.56.png

手順2:Rubyのコードを書く

今はまだrubyでtwitter情報を取得する準備が出来ただけなので今からコードを書いていきます。
まず以下のコマンドをターミナル上で実行し、デスクトップに「Ruby」というフォルダを作成します。
(作成後に自動的にフォルダが起動します)


mkdir ~/Desktop/Ruby
cd ~/Desktop/Ruby
open ./

作成したフォルダ内に「twitter.rb」というファイルを作成します。
作成したファイルに対して以下の内容を追記します。
コピペはせずに「写経」をしてください

twitter.rb

require 'Twitter'

client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "作成したtwitterアプリのconsumer_keyを入力してください"
  config.consumer_secret     = "作成したtwitterアプリのconsumer_secretを入力してください"
  config.access_token        = "作成したtwitterアプリのaccess_tokenを入力してください"
  config.access_token_secret = "作成したtwitterアプリのaccess_token_secretを入力してください"
end

my_user = client.user

p follow = "フォロー数:#{my_user.friends_count}"
p follower =  "フォロワー数:#{my_user.followers_count}"
p tweet =   "ツイート数:#{my_user.tweets_count}"

client.update(follow + follower + tweet)


手順3:Rubyのコードを実行する

入力後はターミナル上で以下のコマンドを実行してください。

ruby twitter.rb

ターミナル上で以下のような出力が表示されたら成功です。

スクリーンショット 2016-07-17 14.40.33.png

そして自分のtwitterへも同じ内容が投稿されています。
自分のtwitterを開き、以下のような投稿がされていれば成功です。

スクリーンショット 2016-07-17 14.42.08.png

おまけ

Rubyのコードで他にもtwitterの機能を使うことが出来ます。
時間に余裕がある人はぜひ遊んで見てください。

自分のタイムラインを表示する

client.home_timeline.each do |tweet|
  puts tweet.full_text
end

自分が特定ユーザー(この場合は「hatebu」)のツイートを最新5つを取得

client.user_timeline("hatebu", { count: 5 } ).each do |timeline|
  tweet = client.status(timeline.id)
  puts tweet.created_at
  puts tweet.text
end

「特定キーワード(この場合は「石原さとみ」)」を含むツイートを検索、最新15ツイートをお気に入りして、そのユーザーをフォローする。

client.search("石原さとみ").take(15).each do |tweet|
   client.favorite(tweet.id)
   client.follow(tweet.user.id)
end

前へ

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up