File size: 11,795 Bytes
1c72248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import requests
import json
from datetime import datetime
from dotenv import load_dotenv

# Load environment variables from .env file
env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), ".env")
load_dotenv(dotenv_path=env_path)

# API credentials
PATREON_TOKEN = os.getenv("PATREON_ACCESS_TOKEN")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
GITHUB_USERNAME = os.getenv("GITHUB_USERNAME")
GITHUB_ORG = os.getenv("GITHUB_ORG")  # Organization name (optional)

# Output file
README_PATH = "SUPPORTERS.md"

def fetch_patreon_supporters():
    """Fetch current Patreon supporters"""
    print("Fetching Patreon supporters...")
    
    headers = {
        "Authorization": f"Bearer {PATREON_TOKEN}",
        "Content-Type": "application/json"
    }
    
    url = "https://www.patreon.com/api/oauth2/v2/campaigns"
    
    try:
        # First get the campaign ID
        campaign_response = requests.get(url, headers=headers)
        campaign_response.raise_for_status()
        campaign_data = campaign_response.json()
        
        if not campaign_data.get('data'):
            print("No campaigns found for this Patreon account")
            return []
        
        campaign_id = campaign_data['data'][0]['id']
        
        # Now get the supporters for this campaign
        members_url = f"https://www.patreon.com/api/oauth2/v2/campaigns/{campaign_id}/members"
        params = {
            "include": "user",
            "fields[member]": "full_name,is_follower,patron_status",  # Removed profile_url
            "fields[user]": "image_url"
        }
        
        supporters = []
        while members_url:
            members_response = requests.get(members_url, headers=headers, params=params)
            members_response.raise_for_status()
            members_data = members_response.json()
            
            # Process the response to extract active patrons
            for member in members_data.get('data', []):
                attributes = member.get('attributes', {})
                
                # Only include active patrons
                if attributes.get('patron_status') == 'active_patron':
                    name = attributes.get('full_name', 'Anonymous Supporter')
                    
                    # Get user data which contains the profile image
                    user_id = member.get('relationships', {}).get('user', {}).get('data', {}).get('id')
                    profile_image = None
                    profile_url = None  # Removed profile_url since it's not supported
                    
                    if user_id:
                        for included in members_data.get('included', []):
                            if included.get('id') == user_id and included.get('type') == 'user':
                                profile_image = included.get('attributes', {}).get('image_url')
                                break
                    
                    supporters.append({
                        'name': name,
                        'profile_image': profile_image,
                        'profile_url': profile_url,  # This will be None
                        'platform': 'Patreon',
                        'amount': 0  # Placeholder, as Patreon API doesn't provide this in the current response
                    })
            
            # Handle pagination
            members_url = members_data.get('links', {}).get('next')
        
        print(f"Found {len(supporters)} active Patreon supporters")
        return supporters
    
    except requests.exceptions.RequestException as e:
        print(f"Error fetching Patreon data: {e}")
        print(f"Response content: {e.response.content if hasattr(e, 'response') else 'No response content'}")
        return []
    
def fetch_github_sponsors():
    """Fetch current GitHub sponsors for a user or organization"""
    print("Fetching GitHub sponsors...")
    
    headers = {
        "Authorization": f"Bearer {GITHUB_TOKEN}",
        "Accept": "application/vnd.github.v3+json"
    }
    
    # Determine if we're fetching for a user or an organization
    entity_type = "organization" if GITHUB_ORG else "user"
    entity_name = GITHUB_ORG if GITHUB_ORG else GITHUB_USERNAME
    
    if not entity_name:
        print("Error: Neither GITHUB_USERNAME nor GITHUB_ORG is set")
        return []
    
    # Different GraphQL query structure based on entity type
    if entity_type == "user":
        query = """
        query {
          user(login: "%s") {
            sponsorshipsAsMaintainer(first: 100) {
              nodes {
                sponsorEntity {
                  ... on User {
                    login
                    name
                    avatarUrl
                    url
                  }
                  ... on Organization {
                    login
                    name
                    avatarUrl
                    url
                  }
                }
                tier {
                  monthlyPriceInDollars
                }
                isOneTimePayment
                isActive
              }
            }
          }
        }
        """ % entity_name
    else:  # organization
        query = """
        query {
          organization(login: "%s") {
            sponsorshipsAsMaintainer(first: 100) {
              nodes {
                sponsorEntity {
                  ... on User {
                    login
                    name
                    avatarUrl
                    url
                  }
                  ... on Organization {
                    login
                    name
                    avatarUrl
                    url
                  }
                }
                tier {
                  monthlyPriceInDollars
                }
                isOneTimePayment
                isActive
              }
            }
          }
        }
        """ % entity_name
    
    try:
        response = requests.post(
            "https://api.github.com/graphql",
            headers=headers,
            json={"query": query}
        )
        response.raise_for_status()
        data = response.json()
        
        # Process the response - the path to the data differs based on entity type
        if entity_type == "user":
            sponsors_data = data.get('data', {}).get('user', {}).get('sponsorshipsAsMaintainer', {}).get('nodes', [])
        else:
            sponsors_data = data.get('data', {}).get('organization', {}).get('sponsorshipsAsMaintainer', {}).get('nodes', [])
        
        sponsors = []
        for sponsor in sponsors_data:
            # Only include active sponsors
            if sponsor.get('isActive'):
                entity = sponsor.get('sponsorEntity', {})
                name = entity.get('name') or entity.get('login', 'Anonymous Sponsor')
                profile_image = entity.get('avatarUrl')
                profile_url = entity.get('url')
                amount = sponsor.get('tier', {}).get('monthlyPriceInDollars', 0)
                
                sponsors.append({
                    'name': name,
                    'profile_image': profile_image,
                    'profile_url': profile_url,
                    'platform': 'GitHub Sponsors',
                    'amount': amount
                })
        
        print(f"Found {len(sponsors)} active GitHub sponsors for {entity_type} '{entity_name}'")
        return sponsors
    
    except requests.exceptions.RequestException as e:
        print(f"Error fetching GitHub sponsors data: {e}")
        return []

def generate_readme(supporters):
    """Generate a README.md file with supporter information"""
    print(f"Generating {README_PATH}...")
    
    # Sort supporters by amount (descending) and then by name
    supporters.sort(key=lambda x: (-x['amount'], x['name'].lower()))
    
    # Determine the proper footer links based on what's configured
    github_entity = GITHUB_ORG if GITHUB_ORG else GITHUB_USERNAME
    github_entity_type = "orgs" if GITHUB_ORG else "sponsors"
    github_sponsor_url = f"https://github.com/{github_entity_type}/{github_entity}"
    
    with open(README_PATH, "w", encoding="utf-8") as f:
        f.write("## Support My Work\n\n")
        f.write("If you enjoy my work, or use it for commercial purposes, please consider sponsoring me so I can continue to maintain it. Every bit helps! \n\n")
        # Create appropriate call-to-action based on what's configured
        cta_parts = []
        if github_entity:
            cta_parts.append(f"[Become a sponsor on GitHub]({github_sponsor_url})")
        if PATREON_TOKEN:
            cta_parts.append("[support me on Patreon](https://www.patreon.com/ostris)")
        
        if cta_parts:
            if GITHUB_ORG:
                f.write(f"{' or '.join(cta_parts)}.\n\n")
        f.write("Thank you to all my current supporters!\n\n")
        
        f.write(f"_Last updated: {datetime.now().strftime('%Y-%m-%d')}_\n\n")
        
        # Write GitHub Sponsors section
        github_sponsors = [s for s in supporters if s['platform'] == 'GitHub Sponsors']
        if github_sponsors:
            f.write("### GitHub Sponsors\n\n")
            for sponsor in github_sponsors:
                if sponsor['profile_image']:
                    f.write(f"<a href=\"{sponsor['profile_url']}\" title=\"{sponsor['name']}\"><img src=\"{sponsor['profile_image']}\" width=\"50\" height=\"50\" alt=\"{sponsor['name']}\" style=\"border-radius:50%;display:inline-block;\"></a> ")
                else:
                    f.write(f"[{sponsor['name']}]({sponsor['profile_url']}) ")
            f.write("\n\n")
        
        # Write Patreon section
        patreon_supporters = [s for s in supporters if s['platform'] == 'Patreon']
        if patreon_supporters:
            f.write("### Patreon Supporters\n\n")
            for supporter in patreon_supporters:
                if supporter['profile_image']:
                    f.write(f"<a href=\"{supporter['profile_url']}\" title=\"{supporter['name']}\"><img src=\"{supporter['profile_image']}\" width=\"50\" height=\"50\" alt=\"{supporter['name']}\" style=\"border-radius:50%;display:inline-block;\"></a> ")
                else:
                    f.write(f"[{supporter['name']}]({supporter['profile_url']}) ")
            f.write("\n\n")
        
        f.write("\n---\n\n")
        
    
    print(f"Successfully generated {README_PATH} with {len(supporters)} supporters!")

def main():
    """Main function"""
    print("Starting supporter data collection...")
    
    # Check if required environment variables are set
    missing_vars = []
    if not GITHUB_TOKEN:
        missing_vars.append("GITHUB_TOKEN")
    
    # Either username or org is required for GitHub
    if not GITHUB_USERNAME and not GITHUB_ORG:
        missing_vars.append("GITHUB_USERNAME or GITHUB_ORG")
    
    # Patreon token is optional but warn if missing
    patreon_enabled = bool(PATREON_TOKEN)
    
    if missing_vars:
        print(f"Error: Missing required environment variables: {', '.join(missing_vars)}")
        print("Please add them to your .env file")
        return
    
    if not patreon_enabled:
        print("Warning: PATREON_ACCESS_TOKEN not set. Will only fetch GitHub sponsors.")
    
    # Fetch data from both platforms
    patreon_supporters = fetch_patreon_supporters() if PATREON_TOKEN else []
    github_sponsors = fetch_github_sponsors()
    
    # Combine supporters from both platforms
    all_supporters = patreon_supporters + github_sponsors
    
    if not all_supporters:
        print("No supporters found on either platform")
        return
    
    # Generate README
    generate_readme(all_supporters)

if __name__ == "__main__":
    main()