Created
June 18, 2023 19:15
-
-
Save sagarjunnarkar/383b02094fa3e6f05e0c829fa0f0986a to your computer and use it in GitHub Desktop.
python script to add user as a collaborator and then make user repo admin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
# Set your GitHub personal access token with admin privileges | |
access_token = "<github token with previledge to add collaborator and set admin for repo>" | |
# Set the organization or user name | |
organization = "<orgnaization>" | |
# Set the team name | |
team = "<team name>" | |
# Set the username of the user to be set as admin | |
username = "<username>" | |
# Make a GET request to get the team ID | |
headers = {"Authorization": f"Bearer {access_token}"} | |
url = f"https://api.github.com/orgs/{organization}/teams/{team}" | |
response = requests.get(url, headers=headers) | |
team_data = response.json() | |
team_id = team_data["id"] | |
# Make a GET request to get the repositories for the team | |
url = f"https://api.github.com/teams/{team_id}/repos" | |
response = requests.get(url, headers=headers) | |
repos_data = response.json() | |
# Loop through the repositories and add the user as a collaborator | |
for repo in repos_data: | |
repo_name = repo["name"] | |
url = f"https://api.github.com/repos/{organization}/{repo_name}/collaborators/{username}" | |
response = requests.put(url, headers=headers) | |
if response.status_code == 201: | |
print(f"Added {username} as a collaborator in {repo_name}") | |
elif response.status_code == 204: | |
print(f"{username} is already a collaborator in {repo_name}") | |
else: | |
print(f"Failed to add {username} as a collaborator in {repo_name} {response.reason} {response.status_code}") | |
break | |
# Set the user as an admin | |
url = f"https://api.github.com/repos/{organization}/{repo_name}/collaborators/{username}/permission" | |
data = { | |
"permission": "admin" | |
} | |
response = requests.put(url, headers=headers, json=data) | |
if response.status_code == 200: | |
print(f"Set {username} as an admin in {repo_name}") | |
else: | |
print(f"Failed to set {username} as an admin in {repo_name} {response.reason} {response.status_code}") | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment