[Twilio+Python] Twilio API を使用した SMS 送信

[Twilio+Python] Twilio API を使用した SMS 送信

Twilio API を使用して Python アプリケーションから SMS を送信する手順を紹介します。 Twilio アカウントが作成済みである想定です。
参考ページ: https://www.twilio.com/docs/messaging/quickstart/python

作業環境

バージョン

OS: Windows 11 (23H2)
Python: 3.11.9
twilio-python: 9.4.5

Twilio CLI のインストール

Scoop を使用して Windows 環境に Twilio CLI をインストールします。 Powershell を管理者権限で起動し、次のコマンドを実行します。

$ scoop bucket add twilio-scoop https://github.com/twilio/scoop-twilio-cli
$ scoop install twilio
Installing 'twilio' (5.22.11) [64bit] from 'twilio-scoop' bucket
Loading twilio-win32-x64.tar.xz from cache
Checking hash of twilio-win32-x64.tar.xz ... ok.
Extracting twilio-win32-x64.tar.xz ... done.
Linking ~\scoop\apps\twilio\current => ~\scoop\apps\twilio\5.22.11
Creating shim for 'twilio'.
Running post_install script...
*************************************************************************
*                                                                       *
* To get started, please create a twilio-cli profile:                   *
*                                                                       *
*     twilio login                                                      *
*                                                                       *
*     OR                                                                *
*                                                                       *
*     twilio profiles:create                                            *
*                                                                       *
*************************************************************************

 » If you’re using autocomplete, you’ll need to run 'twilio autocomplete' after the install and then open a new terminal window. The CLI needs to re-build its cache.
done.
'twilio' (5.22.11) was installed successfully!

twilio login コマンドでログインします。

$ twilio login
? The Account SID for your Twilio Account or Subaccount: ****** # Account SID を入力します
? Your Twilio Auth Token for your Twilio Account or Subaccount: ****** # Auth Token を入力します
? Shorthand identifier for your profile: python-sample # 任意の名前を入力します

Python の Twilio ライブラリをインストールする

pip で twilio-python をインストールします。

$ pip install twilio

SMS の送信

SMS 送信を行う Python スクリプトを作成します。

main.py

from twilio.rest import Client

account_sid = "****" # Account SID を入力します
auth_token = "****" # Auth Token を入力します
client = Client(account_sid, auth_token)

# メッセージの送信
message = client.messages.create(
    body="あのイーハトーヴォのすきとおった風",
    from_="****", # Twilio で購入した番号を入力します
    to="****", # 送信先の電話番号を入力します
)

print(message.body)

作成したスクリプトを実行します。

$ python main.py
あのイーハトーヴォのすきとおった風

SMS が届くことを確認します。

test-sms

おわりに

Twilio API を使用することで、非常に簡単に SMS 送信を実装することができました。 次回 は自動返信機能の実装について解説します。

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.