How to grab first available Twilio Number to use in python script?

186 Views Asked by At

Im having trouble following the docs on Twilio for their API. It looks like theres a lot of unnecessary steps, unless im just an idiot. This code that I copy and pasted below works great, it prints out a list of the numbers that I would like to buy. My question is, is there an easy way to just purchase the first one available and assign it to a variable?

From what I understand, I have to go through an extra step of using this code in order to actually purchase the number.

incoming_phone_number = client.incoming_phone_numbers \
                          .create(phone_number='+15017122661')

Does this mean I have to manually enter the phone number I want to use? This would be fine, except im going to be using a lot of numbers in the application im building and I would like to be able to do .create(phone_number=chosenNumber

from twilio.rest import Client
#
account_sid = "accountsid"
auth_token = "authtoken"
client = Client(account_sid, auth_token)
    
local = client.available_phone_numbers('PR').mobile.list(
                                                       area_code=747,
                                                       limit=20
                                                   )
for record in local:
    print(record.friendly_name)
1

There are 1 best solutions below

4
On BEST ANSWER

Is this what you are looking for?

try:
    first_number = local[0] # First element of list
    incoming_phone_number = client.incoming_phone_numbers \
                          .create(phone_number=first_number.friendly_name)

except IndexError: # If the list was empty
    print("No available numbers")