0

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)
jkorn95
  • 45
  • 6

1 Answers1

1

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

Dave Fol
  • 515
  • 3
  • 11
  • i did something dirtier, and i like what you did better. thats super helpful. this is what i did btw ` local = client.available_phone_numbers('PR').local.list( limit=1 ) for record in local: print(record.friendly_name) incoming_phone_number = client.incoming_phone_numbers \ .create(phone_number=record.friendly_name) print(incoming_phone_number.friendly_name) ` – jkorn95 Aug 02 '20 at 21:13
  • Glad you figured it out! – Dave Fol Aug 02 '20 at 21:20
  • this actually isnt working, im getting "Expected type 'str', got 'LocalInstance' instead" - any ideas? happens here .create(phone_number=first_number) – jkorn95 Aug 02 '20 at 21:21
  • 1
    Try first_number.friendly_name. I'm not familiar with the Twilio API – Dave Fol Aug 02 '20 at 21:24