diff --git a/app/controllers/rsvps_controller.rb b/app/controllers/rsvps_controller.rb index 7a8b488..535b584 100644 --- a/app/controllers/rsvps_controller.rb +++ b/app/controllers/rsvps_controller.rb @@ -1,12 +1,15 @@ class RsvpsController < ApplicationController def create @rsvp = Rsvp.find_or_create_by_email!(rsvp_params[:email]) + Rsvp.invite_to_slack(rsvp_params[:email]) if @rsvp.airtable_record_id.blank? @rsvp.update!(url_params: rsvp_params[:url_params]) end redirect_to root_path, flash: { notice: "Thanks for your interest; check your email for next steps!" } rescue ActiveRecord::RecordInvalid redirect_to root_path, flash: { alert: "Please enter a valid email address." } + rescue => e + redirect_to root_path, flash: { alert: "#{e.message}" } end private diff --git a/app/models/rsvp.rb b/app/models/rsvp.rb index a3114d1..c1b5a7a 100644 --- a/app/models/rsvp.rb +++ b/app/models/rsvp.rb @@ -7,6 +7,45 @@ class Rsvp < ApplicationRecord find_or_create_by!(email: email.downcase.strip) end + def self.invite_to_slack(email) + channels = [ + "C75M7C0SY", # #welcome + "C039PAG1AV7", # #slack-welcome-start + "C08Q1H6D79B", # #highway + "C08PJ6G88QN", # #highway-announcements + "C08S22XRYMU" # #highway-pitstop + ].join(",") + + uri = URI("https://slack.com/api/users.admin.inviteBulk") + headers = { + "Cookie" => "d=#{ENV.fetch('SLACK_COOKIE')}", + "Content-Type" => "application/json", + "Authorization" => "Bearer #{ENV.fetch('SLACK_BROWSER_TOKEN')}" + } + data = { + token: ENV.fetch("SLACK_BROWSER_TOKEN"), + invites: [ + { + email: email, + type: "restricted", + mode: "manual" + } + ], + restricted: true, + channels: channels + } + http = Net::HTTP.new(uri.hostname, uri.port) + http.use_ssl = true + request = Net::HTTP::Post.new(uri, headers) + request.body = data.to_json + response = http.request(request) + j = JSON.parse(response.body) + raise "Slack API general error: #{j['error']}" unless j["ok"] + raise "Slack API error: successful but no invites" if !j["invites"] || j["invites"].empty? + raise "Slack API error on invite: #{j["invites"][0]["error"]}" unless j["invites"][0]["ok"] + { ok: true } + end + def sync_with_airtable! uri = URI("https://api.airtable.com/v0/appuDQSHCdCHyOrxw/tblhGTc3WX9nYzU18")