Automatically Send Slack Invitations

Login to Access Code

Have you ever wanted to programmatically send slack invitations? You can automate your slack integrations, and hit endpoints very quickly and easily with a few standard ruby libraries and a dozen lines of code. We must warn you that the methods and endpoints mentioned in this screencast are not officially supported by Slack. However, we have been using this code for over a year to automatically allow users on the Unicorn.TV site join our private slack communities by sending themselves an invite. We hope that this tutorial helps you in the same way it has helped us!

require 'json'
require 'csv'
require 'uri'
require 'open-uri'
require 'colorize'

CSV.foreach("contacts.csv") do |row|
  # Give our row indexes pretty names
  email = row[1]
  first_name = row[2]
  last_name = row[3]
  invitation = row[4]

  # Get the channel ID from<YOUR_TOKEN>
  channels = ''

  # Get the auth token from:
  token = ''

  # Guard clause if we've already invited the user
  next if (invitation && invitation == "yes") || ($. == 1)

  # Construct the API request URL
  # This is not documented by Slack, and may not work forever
  # As it is an unofficial API endpoint, use at your own risk!
  url = ""
  url += "?channels=#{channels}"
  url += "&set_active=true"
  url += "&_attempts=1"
  url += "&token=#{token}"
  url += "&email=#{URI::escape(email)}"
  url += "&first_name=#{URI::escape(first_name)}"
  url += "&last_name=#{URI::escape(last_name)}"

  # Make the request and capture the response
  response = JSON.parse(open(url).read)

  if response['ok']
    puts "invitation sent to: #{first_name} #{last_name}".colorize(:green)
    puts "invitation failed to send to #{first_name} #{last_name}".colorize(:red)
    puts response.inspect.colorize(:yellow)