使用 twilio 消息发送自定义 OTP python

Send custom OTP with twilio message python

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)
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

这不是js...在python中,你需要用一个f-string来格式化一个字符串:

body=f'Your OTP is {random_str}'

read on f string

编辑:

生成随机 OTP 的更简洁的方法是使用 random.randint 函数,它接受 2 个数字作为其范围,并将 return 在该范围内随机选择:

random_otp = random.randint(10000, 99999)

现在 random_otp 将是 10000 到 99999 之间的数字