Skip to content

Instantly share code, notes, and snippets.

@jcuervo
Created August 23, 2023 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcuervo/3da1228f9fa694697474163251e37e90 to your computer and use it in GitHub Desktop.
Save jcuervo/3da1228f9fa694697474163251e37e90 to your computer and use it in GitHub Desktop.
Send Message via net/http for Twilio Messaging Service
require 'uri'
require 'net/http'
class TwilioMessage
def initialize(options = {})
@account_sid = ENV.fetch('TWILIO_ACCOUNT_SID')
@account_token = ENV.fetch('TWILIO_AUTH_TOKEN')
@message_service_sid = ENV.fetch('TWILIO_MSID')
@body = options[:body]
@to = options[:to]
end
def send
req = Net::HTTP::Post.new(uri)
req.basic_auth @account_sid, @account_token
req.content_type = 'application/x-www-form-urlencoded'
req.set_form_data(
'Body' => @body,
'MessagingServiceSid' => @message_service_sid,
'To' => @to
)
req_options = {
use_ssl: uri.scheme == 'https'
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(req)
end
case response
when Net::HTTPSuccess
puts JSON.parse response.body
when Net::HTTPUnauthorized
puts "#{response.message}: username and password set and correct?"
when Net::HTTPServerError
puts "#{response.message}: try again later?"
else
puts response.message
end
end
private
def uri
URI('https://api.twilio.com/2010-04-01/Accounts/' + @account_sid + '/Messages.json')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment