Skip to content

Instantly share code, notes, and snippets.

@hiroxto
Created June 6, 2016 12:50
Show Gist options
  • Save hiroxto/df492142149413ec4eb18ad1253b4f34 to your computer and use it in GitHub Desktop.
Save hiroxto/df492142149413ec4eb18ad1253b4f34 to your computer and use it in GitHub Desktop.
ユーザーストリームを監視して自動でフォローバック、リムーブバックする
# ライブラリはtwitterを使うので事前に`gem install twitter`を実行
require "twitter"
class AutoFollowBack
def initialize(config)
@config = config
@rest = Twitter::REST::Client.new(@config)
@stream = Twitter::Streaming::Client.new(@config)
@my_id = rest.user.id.freeze
@events = [:follow, :unfollow].freeze
end
attr_reader :config
attr_reader :rest
attr_reader :stream
attr_reader :my_id
attr_reader :events
# 実行
def run
rest_remove
run_stream
end
# ユーザーをフォローするメソッド
def follow(id)
@rest.follow(id)
puts "Followed #{id}"
end
# ユーザーをアンフォローするメソッド
def unfollow(id)
@rest.unfollow(id)
puts "Unfollowed #{id}"
end
# フォロー、フォロワーを全件取得して一気にリムーブするメソッド
def remove_all
options = {
count: 5000,
user_id: @my_id,
}
following = @rest.friends(options).to_a.map(&:id)
followers = @rest.followers(options).to_a.map(&:id)
following.each do |id|
unfollow(id) unless followers.include?(id)
end
end
# ユーザーストリームに接続してfollow,unfollowイベントを監視するメソッド
def run_stream
puts "Connect to stream"
@stream.user do |obj|
next unless obj.is_a?(Twitter::Streaming::Event)
next unless @events.include?(obj.name)
next unless obj.target.id == @my_id
send(obj.name, obj.source.id)
end
puts "Disconnect stream"
puts "Sleep 3min"
sleep 60 * 3
run_stream
end
end
# ここに自分のキーを書く
config = {
consumer_key: "",
consumer_secret: "",
access_token: "",
access_token_secret: "",
}
app = AutoFollowBack.new(config)
app.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment