This repository has been archived by the owner on Mar 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
twitrend.py
executable file
·78 lines (65 loc) · 2.06 KB
/
twitrend.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
#!/usr/bin/env python
# encoding: utf-8
"""
twitrend.py
Requires OAuth values in a text file, in the following order:
Consumer key
Consumer secret
Access key
Access secret
Specify filename on line 36
"""
import sys
import logging
import tweepy
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='twitrend.log',
filemode='a')
def open_file(to_read):
""" Open a text file for reading, and strip the carriage returns
"""
try:
with open(to_read, 'r') as opened:
# strip the newlines, and return the result as a list
return [got_lines.rstrip('\n') for got_lines in opened.readlines()]
except IOError:
print "Couldn't read OAuth values from %s\nCan't continue." % to_read
logging.critical(
"Couldn't read OAuth values from %s. Can't continue", to_read
)
raise
def main():
""" main function
"""
oauth_values = open_file('acc_keys.txt')
auth = tweepy.OAuthHandler(oauth_values[0], oauth_values[1])
auth.set_access_token(oauth_values[2], oauth_values[3])
try:
api = tweepy.API(auth, secure = True)
# now we can do whatever we like!
# Ireland's WOEID:
woeid = 23424803
retrieved = api.trends_location(woeid)
except tweepy.TweepError, err:
print "Couldn't retrieve trends. Error was:"
logging.critical("Couldn't retrieve trends. Error was: %s", err)
raise
# the following is required because the trends_location method returns a
# single-member list containing a JSON-formatted dict, *not* a JSON object
print '\n'.join([trend["name"] for trend in retrieved[0]["trends"]])
if __name__ == "__main__":
try:
main()
except (KeyboardInterrupt, SystemExit):
# actually raise these, for a clean exit
raise
except Exception, error:
# all other exceptions: display the error
print error
else:
pass
finally:
# exit cleanly once we've done everything else
sys.exit(0)