How to use Ruby to Send Text Messages with Twilio
Have you ever wondered how to send SMS in ruby from the terminal?
Yes! You are in the right place!
Let me walk you through the steps on how I was able to send SMS using Twilio on my terminal.
Prerequisites
For this tutorial I assume you will:
Open an account with Twillo if you don't have any
After installing Twilio then open your terminal
Install the twilio-ruby
gem by typing
gem install twilio-ruby
Type irb
in your terminal to switch to the Interactive Ruby environment
Then next you type require twilio-ruby
to use the twilio-ruby gem
In case you get this error just like I encountered on my Mac machineĀ :
LoadError: Could not open library 'sodium': dlopen(sodium, 5): image not found.
Could not open library 'libsodium.dylib': dlopen(libsodium.dylib, 5): image not found
Sodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more
I fixed this error by installing libsodium
with Homebrew brew install libsodium
with the solution, I got this from Stack Overflow and could now run require twilio-ruby
You need to set your Account SID ENV["ACCOUNT_SID"]
and Auth Token ENV["AUTH_TOKEN"]
generated from your Twilio account settings in the environment variables.
Type on the below piece of code on the console
client = Twilio::REST::Client.new(ENV["ACCOUNT_SID"], ENV["AUTH_TOKEN"])
Next, you run
client.messages.create :to => "+234806XXXXXXX", :from => "+234803XXXXXXX", :body => "Hi Nelson it's me Johnwealth from Twilio!"
The to
is the receiver's phone number, from
is the sender phone number while the body
is the body of the message.
You might run into the error below if you are using a phone number not registered with Twilio
Twilio::REST::RestError: [HTTP 400] 21606 : Unable to create record The From phone number +234803XXXXXXX is not a valid, SMS-capable inbound phone number or short code for your account.
To fix the above error, you need to go and get your own Twilio phone number of which in my own case I got this Twilio phone number "+120XXXXXXXX".
I later used it as the sender number i.e. from
:
client.messages.create :to => "+234806XXXXXXX", :from =>"+120XXXXXXXX", :body => "Hi Nelson it's me Abieno saying hi!"
Yippee! I got the SMS alert on my phone!
It's so easy, right?
Thank you!
Your feedback is highly welcomed.
You can also check here for more about the Twilio documentation.