4 # Thomas Thurman, thomas@thurman.uk
5 # Public domain. Bug reports etc welcome.
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.
18 ################ begin config section
20 # URL of the petition.
21 PETITION_URL = 'https://petition.parliament.uk/petitions/131215'
23 # URL of the petition's JSON feed on the petitions site.
24 PETITION_DATA_URL = "https://petition.parliament.uk/petitions/131215.json"
26 # Name of a local file containing your Twitter credentials.
27 # It should contain a JSON object like this one:
29 # "consumer_key" : "xxx",
30 # "consumer_secret" : "xxx",
31 # "access_token" : "xxx",
32 # "access_token_secret" : "xxx"
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"
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"
43 ################ end config section
47 Format the integer "x" with commas, so
48 1234567 -> "1,234,567"
49 There are probably better ways of doing this.
51 if type(x) not in [type(0), type(0L)]:
52 raise TypeError("Parameter must be an integer.")
54 return '-' + intWithCommas(-x)
58 x, r = divmod(x, 1000)
59 result = ",%03d%s" % (r, result)
60 return "%d%s" % (x, result)
64 Creates a tweepy object based on the configuration "cfg".
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)
72 Tweets the string "message".
74 cfg = json.load(open(TWITTER_CONFIG_FILE, "r"));
76 status = api.update_status(status=message)
80 # Pick up the current number of signatures.
82 jsondata = urllib.urlopen("https://petition.parliament.uk/petitions/131215.json").read()
83 data = json.loads(jsondata)
84 count = data['data']['attributes']['signature_count']
88 number = intWithCommas(count)
89 message = "Currently the EU second referendum petition has "+number+" signatures."
91 # Add the previous number, if we have it.
94 previous = json.load(open(PREVIOUS_CONFIG_FILE, 'r'))
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.)"
103 previous['count'] = count
106 json.dump(previous, open(PREVIOUS_CONFIG_FILE, 'w'))
108 # Can't write it. Never mind.
111 # Add a link to the petition site.
113 message += '\n\n' + PETITION_URL
119 if __name__=='__main__':