Twilio SMS Ruby クイックスタート
Twilio Programmable SMSを使用すればたった数行のコードで、Rubyアプリケーションでテキストメッセージを送受信できるようになります。 このRuby SMSクイックスタートでは、開発を容易にするためにCommunication REST API、Twilio Rubyヘルパーライブラリー、そしてRubyのSinatraフレームワークを使用してこれを行う方法をお教えします。 Railsを使用したい場合は、こちらのブログ投稿(英語)をお読みください。 本クイックスタートでは下記のことを学習します:
1. Twilioにサインアップし、最初のSMS機能対応Twilio電話番号を入手します
2. メッセージの送受信を行う開発環境をセットアップする
3. はじめてのSMSを送信する
4. テキストメッセージを受信する
5. 受信メッセージに対してSMSで返信する
ビデオを見ながらの入門がお好みですか? YouTube上のRuby SMSクイックスタートビデオ(英語)をご覧ください。
Sign up for - or sign in to - Twilio
Already have a Twilio account? Go ahead and skip this section.
You can sign up for a free Twilio trial account here.
- When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
- Once you verify your number, you'll be asked a series of questions to customize your experience.
- Once you finish the onboarding flow, you'll arrive at your project dashboard in the Twilio Console. This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.
Install the Twilio CLI
We'll need to use the Twilio CLI (command line interface) for a few tasks, so let's install that next.
One of the easiest ways to install the CLI on Mac OS X is to use Homebrew. If you don't already have it installed, visit the Homebrew site for installation instructions and then return here.
Once Homebrew is installed, simply run the following command to install the CLI:
brew tap twilio/brew && brew install twilio
Updating
If you already installed the CLI with brew and want to upgrade to the latest version, run:
brew upgrade twilio
Warning for Node.js developers
If you have installed Node.js version 10.12 or higher on your Mac, you can avoid potential Node.js version conflicts by installing the CLI using npm:
npm install twilio-cli -g
Before we can install, we need to make sure you have Node.js installed (version 10.12 or above). To see if you have node installed, try running this command:
node -v
If your system reports v10.12.0 or above, you can skip the next step.
Installing Node.js on Windows
Using the Windows Installer (.msi) is the recommended way to install Node.js on Windows. You can download the installer from the Node.js download page.
Installing Twilio CLI
The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:
npm install twilio-cli -g
Note the -g option is what installs the command globally so you can run it from anywhere in your system.
Updating
If you already installed the CLI with npm and want to upgrade to the latest version, run:
npm install twilio-cli@latest -g
Before we can install, we need to make sure you have Node.js installed (version 10.12 or above). Even if you already installed Node yourself, the CLI works best when you install it using nvm. Here's how to get nvm installed on most Linux systems:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
Please visit the nvm installation instructions for additional options and troubleshooting steps. Once you have nvm installed, run the following to install and use the most recent LTS release of Node.js:
nvm install --lts nvm use <insert version reported from above>
Installing other Twilio CLI prerequisites for Linux
Depending on your distribution, you will need to run one of the following commands:
- Debian/Ubuntu:
sudo apt-get install libsecret-1-dev
- Red Hat-based:
sudo yum install libsecret-devel
- Arch Linux:
sudo pacman -S libsecret
Installing Twilio CLI
The CLI is installed with npm (Node Package Manager), which comes with Node.js. To install the CLI run the following command:
npm install twilio-cli -g
Note the -g option is what installs the command globally so you can run it from anywhere in your system.
Updating
If you already installed the CLI with npm and want to upgrade to the latest version, run:
npm install twilio-cli@latest -g
Run twilio login
to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console, and you’ll find your unique Account SID and Auth Token to provide to the CLI.
認証トークンは、目玉アイコンをクリックすると表示されます:
Get a phone number
If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. With the CLI, run:
twilio phone-numbers:buy:local --country-code US --sms-enabled
Replace US with your ISO-3166-1 country code if you would like a phone number in another country. If you aren't finding any SMS enabled numbers, try looking for a mobile number instead of a local number: twilio phone-numbers:buy:mobile --country-code DE --sms-enabled
Select a phone number to add it to your account.
Next, we need to install Ruby and the Twilio Ruby Helper Library.
RubyとTwilioヘルパーライブラリーをインストールする
すでに他のRubyクイックスタートを終えていて、RubyおよびTwilio Rubyヘルパーライブラリーがインストールされている場合は、このステップを読み飛ばしてすぐに最初のテキストメッセージを送信できます。
最初のSMSを送信するには、RubyおよびTwilio Rubyヘルパーライブラリーがインストールされている必要があります。
Rubyをインストールする
あなたがMacやLinuxマシン上にある場合、あなたはおそらくすでにRubyがインストールされています。 ターミナルを開いて下記のコマンドを入力することでこれを確認できます:
$ ruby --version
下記のように表示されます:
ruby 2.4
Windowsユーザーは、RubyInstallerをRubyのインストールに使用できます。
TwilioのRuby SDKはRubyのバージョン2.0.0から2.4.0まででテストおよびサポートされています。 (旧バージョンをお使いですか? PVMまたはHomebrewを使用してサポートされている最小限のバージョンにアップグレード可能です。
Twilio Ruby ヘルパーライブラリー
twilio-rubyをインストールするもっとも簡単な手段はRubyGemを使用することです。
gem install twilio-ruby
手動インストール
また、twilio-rubyのソースコードをクローンし、そこからライブラリーをインストールできます。
"Permission Denied" (権限がありません)
コマンドラインが「Permission Denied (権限がありません) 」といったような文言を含んだ長いエラーメッセージを出力する場合は、sudo gem install twilio-ruby といったように上記のコマンドをsudoを伴い実行してみてください。
RubyでSMSを送信する
これでRubyとtwilio-ruby
ライブラリーがインストールできたので、今しがた購入したTwilio電話番号から、1回のAPIリクエストでSMSを送信できます。 send_sms.rb
という名前のファイルを作成して開き、下記のコードサンプルを入力またはペースとします。
メッセージ送信が行えるようになる前にこのファイルをもう少し編集する必要があります。
プレースホルダーのクレデンシャル値を置き換える
account_sidとauth_tokenのプレースホルダー値をご使用のTwilioのクレデンシャルで置き換えます。
Go to https://www.twilio.com/console and log in. On this page, you’ll find your unique Account SID and Auth Token, which you’ll need any time you send messages through the Twilio Client like this. You can reveal your auth token by clicking on 'view':
send_sms.rb
を開き、account_sid
およびauth_token
に対応する値をご使用のアカウントの一意な値に置き換えます。
ご注意ください: 初めのうちは認証情報をハードコーディングしても構いませんが、本番環境にデプロイするにあたっては、環境変数を使用してこれらが漏洩しないようにしてください。 追加情報については、環境変数の設定方法を参照してください。
「From」電話番号を置き換える
Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing from number with that one, making sure to use E.164 formatting:
[+][country code][phone number including area code]
「To」電話番号を置き換える
Replace the to phone number with your mobile phone number. This can be any phone number that can receive text messages, but it’s a good idea to test with your own phone to see the magic happen! As above, you should use E.164 formatting for this value.
Save your changes and run this script from your terminal:
ruby send_sms.rb
一丁上がり! ほどなくして、Twilio電話番号から携帯電話にSMSが受信されるはずです。
あなたのお客様は米国またはカナダにお住まいですか? もう1行コードを追加すれば、MMSメッセージの送信も可能です。 方法を確認するには、MMS送信のガイドを参照してください。
トライアルアカウントをご使用の場合、Twilioで検証済みの電話番号に送信先が制限されます。電話番号はTwilioコンソール内の検証済み発信者番号にて検証できます。
Sinatraをインストールし開発環境をセットアップする
SMSメッセージを受信、またそれに返信するには、受信リクエストを受け入れ可能な軽量のWebアプリケーションを作成する必要があります。 クイックスタートではSinatraを使用しますが、Railsの使用をご希望の場合は、こちらのブログ記事 (英語) で手順がご覧いただけます。。
まず、下記の内容を含むGemfileが必要になります。
# Gemfile
source 'https://rubygems.org'
gem 'sinatra'
gem 'twilio-ruby'
Node.jsはBundlerを使用して依存関係を管理します。 開発環境にSinatraとTwilio SDKを組み込むために必要なコマンドは bundle install
です。
bundle install
...
Use `bundle show [gemname]` to see where a bundled gem is installed.
簡単なSinatraアプリケーションを作成する
We can test that our development environment is configured correctly by creating a simple Sinatra application. Copy the following code and drop it in a new file called quickstart.rb
:
require 'sinatra' get '/' do "Hello World!" end
We can then try running our new Sinatra application with the command ruby quickstart.rb
. You can then open http://localhost:4567 in your browser and you should see a "Hello World!" message.
Sinatraでメッセージの受信と返信を行う
Twilio電話番号にSMSの受信があった場合、Twilioは皆さんのサーバーにHTTPリクエストを送信して、次に何を行うべきことの指示を問い合わせます。 リクエストを受信したら、TwilioにSMSで返信したり、音声通話を発信したり、データベースにSMSの詳細を保存したり、あるいはまったく別の何かをトリガーしたり……すべては皆さん次第です!
For this quickstart, we’ll have our Sinatra app reply to incoming SMS messages with a thank you to the sender. Open up quickstart.rb
again and update the code to look like this code sample:
このファイルを保存し、アプリケーションを下記のコマンドで再起動します
ruby quickstart.rb
localhostのポートでngrokがまだ実行されていることを再確認します。 これで、Twilioは皆さんのアプリケーションにアクセスできますが、まずはTwilioに探す場所を伝えることが必要です。
WebhookのURLを設定する
Now, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in. Just run this CLI command, replacing the phone number with your Twilio phone number:
twilio phone-numbers:update "+15017122661" --sms-url="http://localhost:4567/sms-quickstart"
The CLI will start an ngrok tunnel (so Twilio can reach your development machine) and wait patiently for incoming text messages!
SMSを送信しアプリケーションをテストする
これですべての設定が完了したので、いよいよテストしてみましょう。
お使いの携帯電話からTwilio電話番号にテキストメッセージを送信します(日本から米国のTwilio番号にSMSを送信すると高額な送信量が携帯キャリアーによって課されるため、じゅうぶんご注意ください)。 ほどなくして、いくつかのことが起こるのを目撃することになるでしょう -
- Your Sinatra dev server will note a new connection
- TwilioはレスポンスをSMSとして転送します!
関連トピック
RubyおよびSinatraを使用したメッセージ送受信の基本について理解できたところで、下記の資料について調べてみるのも良いかもしれません。
- Twilio SMS用APIリファレンスドキュメントの詳細を参照する
- RubyでSMSの会話を作成する方法を学ぶ
- Rubyでメッセージの配信ステータスを追跡する
- 音声通話中にSMSを送信する
- インタラクティブに、そしてご自身のペースでTwilioの使い方を学べるゲーム、TwilioQuestでクールなものを開発する方法を学ぶ
皆さまが何を開発されるのか、目にするのが待ちきれません!
ヘルプが必要ですか?
誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。