'Send custom OTP with twilio message python

  • I am trying to implement Twilio Messaging where in I am generating a OTP with the help of python and I want to send that OTP to the sender.
  • But while doing so I am not able to understand how should I integrate the generated OTP with it. I tried ${random_str} $random_str.
  • Code
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)
  • I am receiving the OTP as
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
  • In the documentation also nothing is mentioned for the same Twilio


Solution 1:[1]

This is not js... In python, you need to use an f-string to format a string:

body=f'Your OTP is {random_str}'

read on f string

edit:

A cleaner way to generate the random OTP will be to use random.randint function, it accept 2 numbers as its range and will return a random choice within that range:

random_otp = random.randint(10000, 99999)

now random_otp will be a number between 10000 and 99999

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1