Search code examples
pythonseleniumtwiliotwilio-api

Reading OTP from Twilio using python


I am currently working in a web automation using selenium python-pytest framework. Here I have a scenario when after providing my phone number, an OTP will be generated and I need to get the OTP and put the same in a text box in the web application. I have seen some tutorial that how twilio works and I have learned that how to send OTP using Twilio library of python. But here the OTP should be sent by the web application itself after clicking some button but I am not sure how to retrieve the OTP in this case. Instead of my personal phone number, if I put the Twilio number in the phone number textbox and get the OTP there in my twilio profile, how to retrieve the same using python? Which API I need to hit to retrieve the OTP from the inbox of my twilio profile? Any leads will be much helpful.


Solution

  • This documentation is having all the code you need to read . Below is one sample taken from the above location to read message resource.

    import os
    from twilio.rest import Client
    
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    auth_token = os.environ['TWILIO_AUTH_TOKEN']
    client = Client(account_sid, auth_token)
    
    message = client.messages('MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch()
    
    print(message.body)