Created
December 5, 2019 14:54
-
-
Save jbaker10/558968c52660a0885db91a6cdf5d41b8 to your computer and use it in GitHub Desktop.
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 os | |
import csv | |
import json | |
import requests | |
from requests.auth import HTTPBasicAuth | |
user_emails = [] | |
with open("/Users/jeremy.baker/Desktop/Members_03jtnz0s2flbciv_04122019_184656.csv", "r") as f: | |
csv_reader = csv.reader(f, delimiter=',') | |
for row in csv_reader: | |
user_emails.append(row[0]) | |
print(user_emails) | |
session = requests.Session() | |
session.headers.update( | |
{ | |
"Content-Type": "application/json", | |
"Accept": "application/json", | |
"Authorization": "Bearer xoxp-123456789", | |
} | |
) | |
endpoint_users = "https://api.slack.com/scim/v1/Users" | |
endpoint_usergroups = "https://slack.com/api/usergroups.{}" | |
users = [] | |
current_slack_users = {} | |
# slack starts their index at 1 | |
start_index = 1 | |
total_users = 0 | |
count = 100 | |
## we are first calling the users endpoint solely to get the totalUsers key | |
resp = session.get(endpoint_users) | |
if not resp.status_code == 200: | |
print("Unable to retrieve users from Slack. Received status code: {}".format(resp.status_code)) | |
exit(1) | |
try: | |
resp = resp.json() | |
except Exception as e: | |
print("Unable to convert Slack response to a JSON object") | |
exit(1) | |
total_users = resp.get("totalResults", 0) | |
while start_index <= total_users: | |
resp = session.get("{}?startIndex={}&count={}".format(endpoint_users, start_index, count)) | |
try: | |
resp = resp.json() | |
except Exception as e: | |
print("Unable to convert Slack response to a JSON object") | |
exit(1) | |
users += resp.get("Resources", []) | |
start_index += count | |
for user in users: | |
# emails is a list so we need to iterate for the primary | |
for email in user.get("emails", []): | |
if email.get("primary", False): | |
current_slack_users[email.get("value", "")] = user | |
break | |
cake_slack_users = [] | |
for user in user_emails: | |
cake_slack_users.append(current_slack_users.get(user, {}).get("id", "")) | |
data = {"usergroup": "S0G360K08", "users": cake_slack_users} | |
resp = session.post( | |
"{endpoint}".format(endpoint=endpoint_usergroups.format("users.update")), json=data | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment