-
Notifications
You must be signed in to change notification settings - Fork 0
/
repost_mongo.rb
106 lines (83 loc) · 2.48 KB
/
repost_mongo.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
require 'rubygems'
require 'twitter'
require File.expand_path(File.join(File.dirname(__FILE__), 'configuration.rb'))
require File.expand_path(File.join(File.dirname(__FILE__), 'blacklist.rb'))
require 'mongo'
include Mongo
class Repost
def initialize
@db = initialize_mongo
@config = Configuration.read_config
@blacklist = Blacklist.new
end
def initialize_mongo
db = Connection.new.db('twitter_tweets')
end
def open_id_collection
ids = @db.create_collection('ids', :capped => true, :size => 1024, :max => 1)
end
def open_tweet_collection
tweets = @db.collection('tweets')
end
def read_last_id
ids_collection = open_id_collection
id = ids_collection.find_one
last_id = nil
if id != nil
last_id = id['id']
end
last_id
end
def write_last_id(id)
ids_collection = open_id_collection
ids_collection.insert('id' => id)
end
def save_tweet(tweet)
tweet_collection = open_tweet_collection
tweet_collection << { :text => tweet.text, :user => tweet.user.screen_name, :id => tweet.id}
end
def get_replies(id, account)
if id == nil
replies = account.replies
else
options = {:since_id => id}
replies = account.replies(options)
end
end
def get_replies_to_retweet(replies, number_to_tweet)
if number_to_tweet == -1
retweets = replies
else
retweets = replies.last(number_to_tweet)
end
retweets
end
def format_text(tweet_text, user_screen_name)
text = @blacklist.strip_username(tweet_text, @config['username'])
text = @blacklist.strip_unwanted_phrases(text)
text << ' (@' + user_screen_name + ')'
end
def twitter_account
client = Twitter::HTTPAuth.new(@config['username'], @config['password'])
account = Twitter::Base.new(client)
end
def repost_tweets
id = read_last_id
account = twitter_account
replies = get_replies(id, account)
retweets = get_replies_to_retweet(replies, @config['number_to_tweet'])
retweets.reverse! # Twitter returns replies from newest to oldest, but want to retweet the oldest first
retweets.each do |tweet|
if @blacklist.eligible_to_retweet(tweet.text, tweet.user.screen_name)
text = format_text(tweet.text, tweet.user.screen_name)
save_tweet(tweet)
account.update(text)
end
write_last_id(tweet.id)
end
end
end
if __FILE__ == $0
repost = Repost.new
repost.repost_tweets
end