How to Programatically Invite People to Slack Chatrooms

There are scripts that one can use (like Slakin) that let you create user registration forms for Slack. I was poking around in the Slakin code and the Slack API and I extracted the part that actually invites the users. You can use this code to create your own custom invite tools for Slack.

Here is an example of how to invite a user to Slack with Python 3:

  1. import requests
  2. from datetime import datetime
  3.  
  4. o = 'myslacksubdomain' # Organization
  5. t = '*********' # API token
  6. e = [email protected]' # Email
  7. c = 'C04H3KVI5' # Channel IDs. I think this can be a comma-separated string of channels
  8. # e.g., invite(o, t, e, c)
  9.  
  10. base_url = 'https://{}.slack.com/api'.format(o)
  11.  
  12. def invite(org, token, email, channel):
  13. """Invite a user to your Slack org."""
  14. ts = int(datetime.now().timestamp())
  15. url = '{}/users.admin.invite?t={}'.format(base_url, org, ts)
  16. payload = {
  17. 'email': email,
  18. 'token': token,
  19. 'channels': channel,
  20. 'set_active': True
  21. }
  22. headers = {
  23. 'cache-control': "no-cache"
  24. }
  25.  
  26. print('About to send payload: {}'.format(payload))
  27. print('to: {}'.format(url))
  28.  
  29. res = requests.request('POST', url, headers=headers, params=payload)
  30.  
  31. # See what gets sent back
  32. print('Got: {}'.format(res.status_code))
  33. print(res.text)

If you have questions, leave a comment below.