require "json" require "openssl" require "net/http" require "securerandom" class NuntioSample def self.deliver(secret:, account:, url:, state:) raise ArgumentError, "Choose published or uncertain" unless %w[published uncertain].include?(state) uri = URI(url) raise ArgumentError, "Use your HTTPS receiver /nuntio address" unless uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty? && uri.port == 443 && uri.userinfo.nil? && uri.query.nil? && uri.fragment.nil? && uri.path == "/nuntio" event = SecureRandom.uuid timestamp = Time.now.to_i.to_s body = JSON.generate(event_id: event, account_id: account, type: "publication.#{state}", state: state, provider: "instagram", test: true) signature = OpenSSL::HMAC.hexdigest("SHA256", secret, "nuntio.webhook.v1\n#{timestamp}\n#{event}\n#{body}") request = Net::HTTP::Post.new(uri, "Content-Type" => "application/json", "Nuntio-Event" => event, "Nuntio-Timestamp" => timestamp, "Nuntio-Signature" => "v1=#{signature}") request.body = body Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 5, read_timeout: 10, write_timeout: 10, max_retries: 0) { |http| http.request(request).code } end end if $PROGRAM_NAME == __FILE__ abort "Choose a test chat channel first, then run: ruby sample.rb --send published|uncertain" unless ARGV.size == 2 && ARGV.first == "--send" status = NuntioSample.deliver(secret: ENV.fetch("NUNTIO_SIGNING_KEY"), account: ENV.fetch("NUNTIO_WORKSPACE"), url: ENV.fetch("NUNTIO_RECEIVER"), state: ARGV.last) puts "Receiver status: #{status}. Check its receipt and the test chat channel." end