-
Notifications
You must be signed in to change notification settings - Fork 1
/
TwitterService.py
executable file
·393 lines (326 loc) · 12.8 KB
/
TwitterService.py
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# TwitterService.py
# v3 : oAuth
#
import tweepy, urllib2, simplejson, re, time, threading, subprocess, OpenSoundControl, yaml, pprint
from sys import stdout
from tweepy.error import TweepError
class TwitterService:
def __init__(self):
try:
f = open('settings.yaml')
self.settings = yaml.load(f)
except Exception, e:
error_print( '!!! e: %s' % e )
error_print( repr(e) )
exit(1)
try:
self.auth = tweepy.OAuthHandler(self.settings['consumer_key'], self.settings['consumer_secret'])
self.auth.set_access_token(self.settings['access_key'], self.settings['access_secret'])
self.api = tweepy.API(self.auth)
except TweepError, e:
error_print( '!!! e: %s' % e )
error_print( repr(e) )
exit(1)
except Exception, e:
error_print( '!!! e: %s' % e )
error_print( repr(e) )
exit(1)
self.username = self.settings['username']
self.last_reply_id = self.settings['last_reply_id']
self.last_tweet_id = self.settings['last_tweet_id']
self.last_geo_id = self.settings['last_geo_id']
self.last_hashtag_id = self.settings['last_hashtag_id']
self.status_ids_already_handled = []
self.tweets = []
self.following = []
self.timeout = 6
self.search_hashtags = self.settings['hashtags']
self.geoparams = self.settings['geosearch']
self.interface = OpenSoundControl.Client(self.settings['user_interface']['osc_recv_port'])
self.display = OpenSoundControl.Client(self.settings['tweet_display']['osc_recv_port'])
def start(self):
debug_print("\nlistening...\n")
while True:
#debug_print(".",; stdout.flush())
# GET NEW FOLLOWS
self.update_following()
# GET NEW TWEETS FROM FOLLOWED USERS
self.update_tweets()
# GET NEW NEARBY TWEETS
r = self.geo_search()
if r:
self.handle_new_geo_tweets(r)
# GET NEW HASHTAG TWEETS
for hashtag in self.search_hashtags:
r = self.hashtag_search(hashtag)
if r:
self.handle_new_hashtag_tweets(hashtag,r)
self.interface.send('/status','OK')
self.settings_changed = False
if (self.settings['last_reply_id'] < self.last_reply_id):
self.settings['last_reply_id'] = self.last_reply_id
self.settings_changed = True
if (self.settings['last_tweet_id'] < self.last_tweet_id):
self.settings['last_tweet_id'] = self.last_tweet_id
self.settings_changed = True
if (self.settings['last_geo_id'] < self.last_geo_id):
self.settings['last_geo_id'] = self.last_geo_id
self.settings_changed = True
if (self.settings['last_hashtag_id'] < self.last_hashtag_id):
self.settings['last_hashtag_id'] = self.last_hashtag_id
self.settings_changed = True
if (self.settings_changed):
if (self.save_settings()):
self.settings_changed = False
time.sleep(self.timeout)
def update(self, message):
try:
status = self.api.PostUpdate(message)
except TweepError, e:
error_print( '!!! e: %s' % e )
error_print( repr(e) )
status = False
if (status):
debug_print(status.text)
def get_replies(self):
debug_print("getting replies since id %d" % self.last_reply_id)
replies = None
try:
replies = self.api.GetReplies(None, self.last_reply_id)
except IOError, e:
# if hasattr(e, 'reason'):
# print '!!! Can\'t reach server.', e.reason
# elif hasattr(e, 'code'):
# print '!!! Server couldn\'t fulfil request:', e.code
error_print ('!!! Server couldn\'t fulfil request: %s' % e.code)
return replies
def geo_search(self):
try:
info_print('~~~ looking for tweets within %(radius)s of %(lat)s, %(lng)s' % self.geoparams)
results = self.api.search(lang='en', geocode="%(lat)s,%(lng)s,%(radius)s" % self.geoparams)
self.trace_search_results(results)
return results
except TweepError, e:
if hasattr(e, 'reason'):
error_print( '!!! Can\'t reach server. %s' % e.reason )
elif hasattr(e, 'code'):
error_print ('!!! Server couldn\'t fulfil request: %s' % e.code)
return False
def hashtag_search(self, terms):
try:
info_print("### searching for tweets with hashtag "+terms+" since id %d" % self.last_hashtag_id)
results = self.api.search(terms, lang='en', since_id=self.last_hashtag_id)
self.trace_search_results(results)
return results
except TweepError, e:
if hasattr(e, 'reason'):
error_print( '!!! Can\'t reach server. %s' % e.reason )
elif hasattr(e, 'code'):
error_print ('!!! Server couldn\'t fulfil request: %s' % e.code)
return False
def trace_search_results(self, results):
for r in results:
debug_print("%d " % r.id + r.text)
def is_following(self, user):
# check local cache first
if user in self.following:
return True
else:
# no match in cache so check online
result = None
try:
result = self.api.exists_friendship(self.username, user)
except TweepError, e:
if hasattr(e, 'reason'):
error_print( '!!! Can\'t reach server. %s' % e.reason )
elif hasattr(e, 'code'):
error_print ('!!! Server couldn\'t fulfil request: %s' % e.code)
else:
# everything is fine
if result: # update cache -- it's out of date
self.following.append(user)
return result
def follow(self, user):
success = None
if self.is_following(user):
return True
else:
try:
success = self.api.create_friendship(user)
except TweepError, e:
if hasattr(e, 'reason'):
error_print( '!!! Can\'t reach server. %s' % e.reason )
elif hasattr(e, 'code'):
error_print ('!!! Server couldn\'t fulfil request: %s' % e.code)
else:
if success:
self.following.append(user)
info_print('+++ Now following @%s' % user)
return success
def get_new_tweets(self):
try:
#debug_print("*** looking for new tweets from users since id %d" % self.last_tweet_id)
return self.api.friends_timeline(since_id=self.last_tweet_id)
except TweepError, e:
if hasattr(e, 'reason'):
error_print( '!!! Can\'t reach server. %s' % e.reason )
elif hasattr(e, 'code'):
error_print ('!!! Server couldn\'t fulfil request: %s' % e.code)
else:
print '!!! e: %s' % e
print repr(e)
return False
def update_tweets(self):
info_print(">>> looking for new tweets from followed users since id %d" % self.last_tweet_id)
# save id's of tweets already seen, and don't show them again
temp_tweet_id = 0
tweets = self.get_new_tweets()
newtweets = []
if tweets:
self.handle_new_followed_tweets(tweets)
for t in tweets:
#debug_print("inside update_tweets, checking t.id=" + t.id)
temp_tweet_id = max(temp_tweet_id, t.id)
newtweets.append([t.id,t.user.name,t.text])
#print "last_tweet_id: %d " % self.last_tweet_id + "temp_tweet_id: %d" % temp_tweet_id
self.last_tweet_id = max(self.last_tweet_id,temp_tweet_id)
self.tweets = newtweets #.extend(self.tweets)
def get_tweets(self):
return self.tweets
def show_tweets(self):
map(print_tweet,self.tweets)
def print_tweet(self,tweet):
print "%d %s %s" % (tweet[0], tweet[1], tweet[2])
def get_following(self):
return self.following;
def update_following(self):
info_print('@@@ looking for new people to follow')
replies = False
try:
replies = self.api.mentions(since_id=self.last_reply_id)
except TweepError, e:
error_print( '!!! e: %s' % e )
error_print( repr(e) )
except Exception, e:
print ( '!!! e: %s' % e )
print ( repr(e) )
if (replies):
pattern = '@' + self.username + r"\sfollow\s@(\w{1,20})$"
p = re.compile(pattern, re.IGNORECASE)
new_users = []
temp_reply_id = 0
for r in replies:
#debug_print("Checking reply: " + r.text)
temp_reply_id = max(temp_reply_id,r.id)
m = p.match(r.text)
if (m):
#debug_print("Found a follow command: " + r.text)
u = m.group(1)
try:
# check it's actually a Twitter user
if self.api.get_user(u):
if not self.is_following(u):
#debug_print("About to follow: " + u)
new_users.append(u)
else:
debug_print("--- Already following @%s" % u)
except TweepError, e:
debug_print("!!! No user found: %s" % u)
if new_users:
debug_print("%d new users added to follow" % len(new_users))
try:
map(self.follow, new_users)
except urllib2.HTTPError as e:
error_print("Error updating follow list")
error_print(e)
return
self.last_reply_id = max(self.last_reply_id, temp_reply_id)
def handle_new_followed_tweets(self, statuses):
count = 0
for s in statuses:
#debug_print("inside handle_new_followed_tweets, s.id = %d" % s.id)
id = s.id
if id not in self.status_ids_already_handled:
self.status_ids_already_handled.append(id)
if (count == 0):
info_print("")
user = s.user.screen_name.encode('ascii', 'ignore')
text = s.text.encode('ascii', 'ignore')
info_print(">>> @%s\n %s\n" % (user, text))
self.interface.send('/tweet',[user, len(text), text])
self.display.send('/tweet',[user, len(text), text])
count = count + 1
time.sleep(2.25)
def handle_new_hashtag_tweets(self, hashtag, results):
debug_print("handling hashtag tweets")
temp_hashtag_id = 0
count = 0
for r in results:
id = r.id
if id not in self.status_ids_already_handled:
self.status_ids_already_handled.append(id)
if (count == 0):
info_print("")
user = r.from_user.encode('ascii', 'ignore')
text = r.text.encode('ascii', 'ignore')
info_print("### @%s\n %s\n" % (user, text))
self.interface.send('/tweet',[user, len(text), text])
self.display.send('/tweet',[user, len(text), text])
temp_hashtag_id = max(temp_hashtag_id, id)
self.last_hashtag_id = max(self.last_hashtag_id,temp_hashtag_id)
count = count + 1
time.sleep(3)
def handle_new_geo_tweets(self, results):
debug_print("handling nearby tweets")
temp_geo_id = 0
count = 0
for r in results:
id = r.id
if id not in self.status_ids_already_handled:
self.status_ids_already_handled.append(id)
if (count == 0):
info_print("")
user = r.from_user.encode('ascii', 'ignore')
text = r.text.encode('ascii', 'ignore')
info_print("~~~ @%s\n %s\n" % (user, text))
self.interface.send('/tweet',[user, len(text), text])
self.display.send('/tweet',[user, len(text), text])
temp_geo_id = max(temp_geo_id, id)
self.last_geo_id = max(self.last_geo_id,temp_geo_id)
count = count + 1
time.sleep(1.5)
def save_settings(self):
debug_print("Saving settings...")
try:
stream = file('settings.yaml','w')
yaml.dump(self.settings, stream)
return True
except Exception, e:
error_print( '!!! e: %s' % e )
error_print( repr(e) )
return False
def error_print(msg):
if PRINT_ERROR:
print msg.encode('ascii', 'ignore')
def debug_print(msg):
if PRINT_DEBUG:
print msg.encode('ascii', 'ignore')
def info_print(msg):
if PRINT_INFO:
print msg.encode('ascii', 'ignore')
if __name__ == "__main__":
print ""
print " __ __ __ ___ _ _ _ "
print " / // /___ ________/ / / _ \____(_)_ __(_)___ ( )"
print " / _ // _ `/ __/ _ / / // / __/ /| |/ / // _ \|/ "
print " /_//_/ \_,_/_/ \_,_/ /____/_/ /_/ |___/_//_//_/ "
print ""
print " ___ ___ ___ ___ __ __ ___ __ __ "
print " | | | |__ |__ | / ` / \ |\ | | |__) / \ | "
print " | |/\| |___ |___ | \__, \__/ | \| | | \ \__/ |___ "
print ""
PRINT_ERROR = True
PRINT_DEBUG = False
PRINT_INFO = True
ts = TwitterService()
ts.start()