Last active
December 30, 2015 12:39
-
-
Save serek/7831009 to your computer and use it in GitHub Desktop.
Simple Twilio wrapper for Sending SMS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Usage: | |
# sms = SMS.new('+1XXXXXX', 'Message') | |
# sms = SMS.new('+1XXXXXX', 'Message', :full_sms_queue, :invalid) | |
# sms.data - results in hash | |
# | |
class SMS | |
def initialize(number, message, from_error=nil, to_error=nil) | |
@client = SMS.client | |
send_sms(number, message, from_error, to_error) | |
end | |
def send_sms(number, message, from_error=nil, to_error=nil) | |
@data = {} | |
begin | |
sms = @client.account.sms.messages.create( | |
from: SMS.from_number(from_error), | |
to: SMS.to_number(number, to_error), | |
body: message | |
) | |
@data.merge!(sms: sms) | |
rescue Twilio::REST::RequestError => error | |
@data.merge!(error: error.message) | |
rescue Twilio::REST::ServerError => error | |
@data.merge!(error: error.message) | |
else | |
@data.merge!(message: 'Thank you. You will recieve sms message soon.') | |
end | |
end | |
def data | |
@data | |
end | |
def self.from_number(error = nil) | |
if Rails.env == "development" | |
case error | |
when :full_sms_queue | |
'+15005550008' | |
when :not_owned | |
'+15005550007' | |
when :invalid | |
'+15005550001' | |
when :no_sms | |
'+15005550000' | |
when :production | |
'change_to_your_production_number' | |
else | |
'+15005550006' | |
end | |
else | |
'change_to_your_production_number' | |
end | |
end | |
def self.to_number(number, error = nil) | |
if Rails.env == "development" | |
case error | |
when :invalid | |
'+15005550001' | |
when :cannot_route | |
'+15005550002' | |
when :cannot_international | |
'+15005550003' | |
when :blacklisted | |
'+15005550004' | |
when :no_sms | |
'+15005550009' | |
else | |
number | |
end | |
else | |
number | |
end | |
end | |
def self.client | |
Twilio::REST::Client.new(SMS.config.first, SMS.config.last) | |
end | |
def self.config | |
acc_sid, acc_tok = ENV['twilio_sid'], ENV['twilio_token'] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment