简体   繁体   中英

How to send a text message using the Twilio API

I am working on a Python project to send a text message to a specific phone number. The code below should load the api credentials into the Twilio REST client then send a message to RECIPIENT .

# Download the helper library from https://www.twilio.com/docs/python/install
from email import message
import os
from twilio.rest import Client
from dotenv import load_dotenv
import logging
import os
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# Set environment variables
ACCOUNT_SID         = os.getenv("ACCOUNT_SID")
AUTH_TOKEN          = os.getenv("AUTH_TOKEN")
PHONE               = os.getenv("PHONE")
RECIPIENT           = os.getenv("RECIPIENT")

# Load environment variables
load_dotenv()

accountSID   = ACCOUNT_SID
authToken    = AUTH_TOKEN
myNumber     = RECIPIENT
twilioNumber = PHONE
twilioCli = Client(accountSID,authToken)
messages = twilioCli.messages.create(body="The boring task is finished",from_=twilioNumber, to=myNumber)

logging.debug(f"{message.sid}")

Expected: The message should be sent and the message SID should be printed out.

Actual:

File "C:\Users\EvanGertis\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\twilio\rest\__init__.py", line 58, in __init__
    raise TwilioException("Credentials are required to create a TwilioClient")
twilio.base.exceptions.TwilioException: Credentials are required to create a TwilioClient

Why is this not working?

看起来像: # Load environment variables is below your assignments, put it at thr top before assignment.

Look at that "# Set environment variables" section,

Try to put these in things

    ACCOUNT_SID         = os.getenv("# Put your account Sid here")
    AUTH_TOKEN          = os.getenv("# your auth token here")
    PHONE               = os.getenv("# your phone you registered on twilio")
    RECIPIENT           = os.getenv("# the number you got from twilio")

this will help you to run the code & if this doesn't work then there a trick:

look at the "# Load environment variables" section,

Try to put these in things

     accountSID   = # Put your account Sid here
     authToken    = # your auth token here
     myNumber     = # your phone you registered on twilio
     twilioNumber = # the number you got from twilio

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM