-
-
Save mjg123/ed233dcc234c41d2bea5b14f9adfaa37 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| using HTTP | |
| using JSON | |
| # Use a ; to separate positional and named arguments | |
| # Here, we only have named args | |
| function send_sms(;message, from, to) | |
| account_sid = ENV["TWILIO_ACCOUNT_SID"] | |
| auth_token = ENV["TWILIO_AUTH_TOKEN"] | |
| # Note: String interpolation | |
| endpoint = "api.twilio.com/2010-04-01/Accounts/$account_sid/Messages.json" | |
| url = "https://$account_sid:$auth_token@$endpoint" | |
| # This is a nice function: | |
| # help?> HTTP.URIs.escapeuri | |
| # escapeuri(query_vals) | |
| # Percent-encode and concatenate a value pair(s) as they would conventionally | |
| # be encoded within the query part of a URI. | |
| request_body = HTTP.URIs.escapeuri([:From => from, :To => to, :Body => message]) | |
| request_headers = ["Content-Type" => "application/x-www-form-urlencoded"] | |
| try | |
| response = HTTP.post(url, request_headers, request_body) | |
| return JSON.parse(String(response.body)) | |
| catch e | |
| if e isa HTTP.ExceptionRequest.StatusError | |
| # response status was 4xx or 5xx | |
| # throw an error with the body of the API response | |
| error(JSON.parse(String(e.response.body))["message"]) | |
| else | |
| # Some other kind of error, which we can't handle | |
| rethrow() | |
| end # if | |
| end # try/catch | |
| end # function | |
| result = send_sms(message="Hello from Twilio! ☎", from="<YOUR_TWILIO_NUMBER>", to="<YOUR_REAL_NUMBER>") | |
| println(result["sid"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment