Skip to content

Instantly share code, notes, and snippets.

@gelin
Created February 20, 2020 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gelin/e710ae8e7cb2da252c34d01edfb9375d to your computer and use it in GitHub Desktop.
Save gelin/e710ae8e7cb2da252c34d01edfb9375d to your computer and use it in GitHub Desktop.
Invite users to Slack
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import csv
import requests
import time
# Create and register your app in Slack.
# You need the Legacy Token here: https://api.slack.com/custom-integrations/legacy-tokens
token = 'xxxx-1234567890-1234567890-1234567890-1234567890abcdef1234567890abcdef'
first_name_column = 'Имя'
last_name_column = 'Фамилия'
email_column = 'Gmail'
# https://github.com/ErikKalkoken/slackApiDoc/blob/master/users.admin.invite.md
url_invite = 'https://slack.com/api/users.admin.invite'
def main(csv_file):
print('The users.admin.invite call is rate limited, is going to be processed slowly...')
print('Reading', csv_file)
for row in read_csv(csv_file):
invite_user(
first_name=row.get(first_name_column),
last_name=row.get(last_name_column),
email=row.get(email_column)
)
time.sleep(61) # to satisfy Tier 1 Web API rate limiting: https://api.slack.com/docs/rate-limits#tiers
print('Done')
def read_csv(csv_file):
with open(csv_file, newline='') as file:
reader = csv.DictReader(file)
for row in reader:
yield row
def invite_user(first_name, last_name, email):
print('Inviting', first_name, last_name, email, '...', end=' ', flush=True)
if blank(email):
print('no email')
return
params = {
'token': token,
'email': email.strip()
}
if not_blank(first_name):
params['first_name'] = first_name.strip()
if not_blank(last_name):
params['last_name'] = last_name.strip()
try:
repeats = 10
error = 'ratelimited'
response = None
while error == 'ratelimited' and repeats > 0:
response = requests.post(url_invite, data=params)
result = response.json()
if result.get('ok'):
break
error = result.get('error')
repeats -= 1
print('...', end=' ', flush=True)
time.sleep(30)
print(response.text)
except Exception as e:
print(e)
# https://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python
def blank(s):
return not (s and s.strip())
def not_blank(s):
return bool(s and s.strip())
def print_usage():
print("""Usage:
invite_to_slack.py invitees.csv
The CSV file must contain named columns: first_name, last_name, email""")
if __name__ == '__main__':
if len(sys.argv) < 2:
print_usage()
sys.exit(1)
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment