chiark / gitweb /
initial
[petition-twitter.git] / petition-twitter.py
1 #!/usr/bin/python
2
3 # petition-twitter.py
4 # Thomas Thurman, thomas@thurman.uk
5 # Public domain. Bug reports etc welcome.
6 #
7 # Very simple script to tweet the number of signatures
8 # to a petition on the UK government website.
9 # This should be run from a cronjob every five minutes
10 # (or however often you like).
11 # I apologise for the quick and dirty code:
12 # it had to be written in an hour.
13
14 import urllib
15 import json
16 import tweepy
17
18 ################ begin config section
19
20 # URL of the petition.
21 PETITION_URL = 'https://petition.parliament.uk/petitions/131215'
22
23 # URL of the petition's JSON feed on the petitions site.
24 PETITION_DATA_URL = "https://petition.parliament.uk/petitions/131215.json"
25
26 # Name of a local file containing your Twitter credentials.
27 # It should contain a JSON object like this one:
28 # { 
29 #       "consumer_key"        : "xxx",
30 #       "consumer_secret"     : "xxx",
31 #       "access_token"        : "xxx",
32 #       "access_token_secret" : "xxx"
33 # }
34 # If you want to know how to get these values,
35 # I'll write it up somewhere.
36 TWITTER_CONFIG_FILE = "petition-twitter-config.json"
37
38 # Name of a file containing the number of signatures
39 # from last time we ran this script. If it doesn't
40 # exist, the script will create it.
41 PREvIOUS_CONFIG_FILE = "petition-twitter-previous.json"
42
43 ################ end config section
44
45 def intWithCommas(x):
46     """
47     Format the integer "x" with commas, so
48      1234567 -> "1,234,567"
49     There are probably better ways of doing this.
50     """
51     if type(x) not in [type(0), type(0L)]:
52         raise TypeError("Parameter must be an integer.")
53     if x < 0:
54         return '-' + intWithCommas(-x)
55     result = ''
56
57     while x >= 1000:
58             x, r = divmod(x, 1000)
59             result = ",%03d%s" % (r, result)
60     return "%d%s" % (x, result)
61
62 def get_api(cfg):
63     """
64     Creates a tweepy object based on the configuration "cfg".
65     """
66     auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
67     auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
68     return tweepy.API(auth)
69
70 def tweet(message):
71     """
72     Tweets the string "message".
73     """
74     cfg = json.load(open(TWITTER_CONFIG_FILE, "r"));
75     api = get_api(cfg)
76     status = api.update_status(status=message) 
77
78 def main():
79
80     # Pick up the current number of signatures.
81
82     jsondata = urllib.urlopen("https://petition.parliament.uk/petitions/131215.json").read()
83     data = json.loads(jsondata)
84     count = data['data']['attributes']['signature_count']
85
86     # Format the message.
87
88     number = intWithCommas(count)
89     message = "Currently the EU second referendum petition has "+number+" signatures."
90
91     # Add the previous number, if we have it.
92
93     try:
94         previous = json.load(open(PREVIOUS_CONFIG_FILE, 'r'))
95     except:
96         previous = {}
97
98     if previous.has_key('count'):
99         delta = count - previous['count']
100         number = intWithCommas(delta)
101         message += "\n\n(" + number+" more in the last five minutes.)"
102
103     previous['count'] = count
104
105     try:
106         json.dump(previous, open(PREVIOUS_CONFIG_FILE, 'w'))
107     except:
108         # Can't write it. Never mind.
109         pass
110
111     # Add a link to the petition site.
112
113     message += '\n\n' + PETITION_URL
114
115     # And tweet it!
116
117     tweet(message)
118
119 if __name__=='__main__':
120     main()
121