-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patronupdater.py
executable file
·151 lines (125 loc) · 4.64 KB
/
patronupdater.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
#!/usr/bin/env python3
import patreon
import sys
import os
import configparser
import json
import argparse
# DO NOT ENABLE IN PRODUCTION !!!!
import pprint
import collections
RewardInfo = collections.namedtuple('RewardInfo', 'rewarded anons')
def process_pledges(data, rewardToScanFor):
"""Takes a 'page' of pledges returned by the Patreon API and filters out patrons that are eligible for the specified reward."""
processed = []
valid_pledges = [
pledge
for pledge in data['data']
if pledge['type'] == 'pledge'
if pledge['attributes']['declined_since'] == None
]
rewarded_pledges = [
pledge
for pledge in valid_pledges
if pledge['relationships']['reward']['data'] != None
if pledge['relationships']['reward']['data']['id'] == rewardToScanFor
]
anon_pledges = [
pledge
for pledge in valid_pledges
if pledge['relationships']['reward']['data'] == None
]
patrons = {
patron['id']: patron['attributes']
for patron in data['included']
if patron['type'] == 'user'
}
processed = [
patrons[pledge['relationships']['patron']['data']['id']]
for pledge in rewarded_pledges
]
return RewardInfo(rewarded = processed, anons=len(anon_pledges))
class PledgeAttributes(object):
amount_cents = 'amount_cents'
total_historical_amount_cents = 'total_historical_amount_cents'
declined_since = 'declined_since'
created_at = 'created_at'
pledge_cap_cents = 'pledge_cap_cents'
patron_pays_fees = 'patron_pays_fees'
unread_count = 'unread_count'
my_pledge_attributes = [
PledgeAttributes.amount_cents,
PledgeAttributes.declined_since,
PledgeAttributes.total_historical_amount_cents,
]
def getCurrentRewardedPatrons(accessToken, rewardToScanFor):
"""Gets all the patrons eligible for a specified reward."""
patreonAPI = patreon.API(accessToken)
campaign = patreonAPI.fetch_campaign()
campaignId = campaign['data'][0]['id']
pageSize = 20
anons = 0
all_rewarded = []
pledges = patreonAPI.fetch_page_of_pledges(campaignId, pageSize, None, None, { 'pledge': my_pledge_attributes })
cursor = patreonAPI.extract_cursor(pledges)
processed = process_pledges(pledges, rewardToScanFor)
all_rewarded += processed.rewarded
anons += processed.anons
while 'next' in pledges['links']:
pledges = patreonAPI.fetch_page_of_pledges(campaignId, pageSize, cursor, None, { 'pledge': my_pledge_attributes })
cursor = patreonAPI.extract_cursor(pledges)
processed = process_pledges(pledges, rewardToScanFor)
all_rewarded += processed.rewarded
anons += processed.anons
# sort by full name
all_rewarded.sort(key=lambda y: y['full_name'].lower())
return RewardInfo(rewarded = all_rewarded, anons=anons)
def main(configPath, workPath):
configPath = configPath + '/tokens.cfg'
textPath = workPath + '/patrons.txt'
jsonPath = workPath + '/patrons.json'
# read the config
config = configparser.RawConfigParser()
config.read(configPath)
# refresh the auth tokens
auth = patreon.OAuth(config['Keys']['clientid'], config['Keys']['clientsecret'])
tokens = auth.refresh_token(config['Keys']['refreshtoken'], "fake")
config['Keys']['accesstoken'] = tokens['access_token']
config['Keys']['refreshtoken'] = tokens['refresh_token']
# write the refreshed auth tokens
with open(configPath, 'w') as configFile:
config.write(configFile)
processed = getCurrentRewardedPatrons(tokens['access_token'], config['Config']['reward'])
# simple list with one name per line
legacylist = [
patron['full_name']
for patron in processed.rewarded
]
if processed.anons > 0:
if processed.anons > 1:
legacylist.append('And %d others who wish to remain anonymous.' % processed.anons)
else:
legacylist.append('And one other who wishes to remain anonymous.' % processed.anons)
legacylistText = '\n'.join(legacylist)
# JSON list with names, avatar images and URLs for clickable links to Patreon profiles
modernlist = [
{
'name': patron['full_name'],
'image_url': patron['thumb_url'] if patron['thumb_url'].startswith("http") else 'https:' + patron['thumb_url'],
'patreon_url': patron['url']
}
for patron in processed.rewarded
]
modernlistJson = json.dumps(modernlist, separators=(',',':'))
with open(textPath, mode='w', encoding='utf-8') as textFile:
textFile.write(legacylistText)
with open(jsonPath, mode='w', encoding='utf-8') as jsonFile:
jsonFile.write(modernlistJson)
return 0
scriptPath = os.path.dirname(os.path.realpath(__file__));
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config", type=str, help="folder with the configuration", default=scriptPath)
parser.add_argument("-w", "--work", type=str, help="folder for the resulting files", default=scriptPath)
args = parser.parse_args()
retval = main(args.config, args.work)
sys.exit(retval)