在Python中通过Twilio发送文本消息

时间:2020-02-07 15:58:05

标签: python twilio

我正在学习本教程:How to Send an SMS With Python Using Twilio

我已经在Windows计算机上将这些变量设置为环境变量:

CELL_PHONE_NUMBER = +12015555555
TWILIO_ACCOUNT_SID = my_twilio_account_sid
TWILIO_AUTH_TOKEN = my_twilio_auth_token
TWILIO_PHONE_NUMBER = +12016666666

这是我的代码:

import os
from twilio.rest import Client


account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')

client = Client(account_sid, auth_token)

client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
                       to=os.environ.get('CELL_PHONE_NUMBER'),
                       body='You just sent an SMS from Python using Twilio!')

但是我遇到了这个错误:

Traceback (most recent call last):
  File ".\sms.py", line 10, in <module>
    client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
  File "C:\Users\tdun0002\AppData\Local\Programs\Python\Python38-32\lib\site-packages\twilio\rest\api\v2010\account\message\__init__.py", line 86, in create
    payload = self._version.create(method='POST', uri=self._uri, data=data, )
  File "C:\Users\tdun0002\AppData\Local\Programs\Python\Python38-32\lib\site-packages\twilio\base\version.py", line 209, in create
    raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
[31m[49mHTTP Error[0m [37m[49mYour request was:[0m

[36m[49mPOST /Accounts/PN7afb27dc8e041f18dcf91fefe306ad34/Messages.json[0m

[37m[49mTwilio returned the following information:[0m

[34m[49mUnable to create record: Authentication Error - invalid username[0m

[37m[49mMore information may be available here:[0m

[34m[49mhttps://www.twilio.com/docs/errors/20003[0m

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

根据Twilio docs

错误-20003
权限被拒绝
您缺少对所请求资源和方法的许可。

故障排除步骤

验证帐户SID和身份验证令牌正确
验证是否访问了正确的帐户
确保该帐户处于活动状态,没有被暂停或关闭
确保没有多余的字符或空格
确保仅将JWT与API密钥一起使用

尝试打印account_sidauth_token,以再次检查它们是否正确,并验证它们是否与twilio控制台上的

匹配。