使用 twilio 消息发送自定义 OTP python
Send custom OTP with twilio message python
- 我正在尝试实施
Twilio Messaging
,其中我在 python 的帮助下生成 OTP,我想将该 OTP 发送给发件人。
- 但是在这样做的时候我无法理解我应该如何将生成的 OTP 与它集成。我试过了
${random_str}
$random_str
.
- 代码
import random
import math
import os
from twilio.rest import Client
digits = [i for i in range(0, 10)]
random_str = ""
## create a number of any length for now range = 6
for i in range(6):
index = math.floor(random.random() * 10)
random_str += str(digits[index])
## display the otp
print(random_str)
account_sid = '<sid>'
auth_token = '<auth_token>'
client = Client(account_sid, auth_token)
message = client.messages.create(
messaging_service_sid='<SID>',
body='Your OTP is $random_str',
to='<number>'
)
print(message.sid)
- 我收到的 OTP 为
Sent from your Twilio trial account - Your OTP is ${random_str}
Sent from your Twilio trial account - Your OTP is {random_str}
Sent from your Twilio trial account - Your OTP is $random_str
- 在文档中也没有提及相同的 Twilio
这不是js...在python中,你需要用一个f-string
来格式化一个字符串:
body=f'Your OTP is {random_str}'
编辑:
生成随机 OTP 的更简洁的方法是使用 random.randint
函数,它接受 2 个数字作为其范围,并将 return 在该范围内随机选择:
random_otp = random.randint(10000, 99999)
现在 random_otp 将是 10000 到 99999 之间的数字
- 我正在尝试实施
Twilio Messaging
,其中我在 python 的帮助下生成 OTP,我想将该 OTP 发送给发件人。 - 但是在这样做的时候我无法理解我应该如何将生成的 OTP 与它集成。我试过了
${random_str}
$random_str
. - 代码
import random
import math
import os
from twilio.rest import Client
digits = [i for i in range(0, 10)]
random_str = ""
## create a number of any length for now range = 6
for i in range(6):
index = math.floor(random.random() * 10)
random_str += str(digits[index])
## display the otp
print(random_str)
account_sid = '<sid>'
auth_token = '<auth_token>'
client = Client(account_sid, auth_token)
message = client.messages.create(
messaging_service_sid='<SID>',
body='Your OTP is $random_str',
to='<number>'
)
print(message.sid)
- 我收到的 OTP 为
Sent from your Twilio trial account - Your OTP is ${random_str}
Sent from your Twilio trial account - Your OTP is {random_str}
Sent from your Twilio trial account - Your OTP is $random_str
- 在文档中也没有提及相同的 Twilio
这不是js...在python中,你需要用一个f-string
来格式化一个字符串:
body=f'Your OTP is {random_str}'
编辑:
生成随机 OTP 的更简洁的方法是使用 random.randint
函数,它接受 2 个数字作为其范围,并将 return 在该范围内随机选择:
random_otp = random.randint(10000, 99999)
现在 random_otp 将是 10000 到 99999 之间的数字