繁体   English   中英

使用 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}'

在 f 弦上读

编辑:

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

random_otp = random.randint(10000, 99999)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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