Skip to content

Instantly share code, notes, and snippets.

@johanlunds
Last active January 11, 2018 18:50
Show Gist options
  • Save johanlunds/4ace813480abb8585a3fe9df0bad33d5 to your computer and use it in GitHub Desktop.
Save johanlunds/4ace813480abb8585a3fe9df0bad33d5 to your computer and use it in GitHub Desktop.
List users of a Slack team that are not bots and not restricted users.
# Read how to generate "test token" (only to be used during development) here:
#
# https://slackapi.github.io/python-slackclient/auth.html#handling-tokens
#
# Install slackclient:
#
# https://github.com/slackapi/python-slackclient
#
# pip install slackclient
#
# If you need Python and/or pip:
#
# brew install python
#
# Follow the instructions ("brew info python") how to use Homebrew Python over the one that
# comes with macOS.
#
# Run this script like:
#
# SLACK_API_TOKEN=.... python slack_list_employees.py
import os, sys
import pprint, json
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)
# NOTE: does not handle pagination right now.
#
# See API docs: https://api.slack.com/methods/users.list
result = sc.api_call(
"users.list",
limit=100
)
employees = [user for user in result['members'] if not user['is_bot']
and not user['deleted']
and not user.get('is_restricted')
and not user.get('is_ultra_restricted')
and not user['name'] == 'slackbot']
print "Found", len(employees), "employees."
print
def dump(value):
print json.dumps(value, indent=True, sort_keys=True, ensure_ascii=False)
def get_key_values(object, keys):
keys = (keys or 'name').split(',') # with default
filtered = {}
for key in keys:
subkeys = key.split('.')
key = subkeys[0]
if len(subkeys) == 1:
filtered[key] = object.get(key)
elif len(subkeys) == 2:
filtered[key] = filtered.get(key, {})
filtered[key][subkeys[1]] = object[key].get(subkeys[1])
else:
raise ValueError("Only 2 levels is supported, like profile.email")
if len(keys) == 1:
return filtered[filtered.keys()[0]]
else:
return filtered
try:
action = sys.argv[1]
except IndexError:
action = None
if action == '--help':
print "Run like one these examples:"
print
print "python " + sys.argv[0] + " --example"
print "python " + sys.argv[0] + " --keys"
print "python " + sys.argv[0] + " --help"
print "python " + sys.argv[0] + " # will print name of all employees"
print "python " + sys.argv[0] + " real_name"
print "python " + sys.argv[0] + " real_name,profile.email"
elif action == '--example':
print "Here is an example of a Slack user:"
print
dump(employees[0])
elif action == '--keys':
print "Here are possible keys you can ask for:"
print
keys = employees[0].keys()
dump(keys)
else:
keys = action
filtered = [get_key_values(user, keys) for user in employees]
dump(filtered)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment