0

hope you are doing it right these days.

To summarize my problem, I think this is not working becuase I am using a free Twilio account instead of a paid one. But that's just my beginner theory. Now, the issue:

I have tried an official Twilio tutorial (https://www.twilio.com/blog/automating-ngrok-python-twilio-applications-pyngrok, I shared the link in case someone finds it interesting or needs it), which allows us to automate SMS webhook (sms_url) configuration by using Client (twilio) and pyngrok (ngrok).

def start_ngrok():
   from twilio.rest import Client
   from pyngrok import ngrok

   url = ngrok.connect(5000)
   print(' * Tunnel URL:', url)
   client = Client()
   client.incoming_phone_numbers.list(
       phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
           sms_url=url + '/bot')

I can't explain all the things that I tried in the last 4 days, with no success. I keep getting the same error:

   client.incoming_phone_numbers.list(phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(sms_url=url + '/bot')
IndexError: list index out of range

Something is not working with the list, it comes empty, although environment variables are working properly. I will work with just one phone_number, so there no need for list, indeed, so I started to change that line to avoid different errors and ended up with this:

def start_ngrok():
   from twilio.rest import Client
   from pyngrok import ngrok

   url = ngrok.connect(5000)
   print(' * Tunnel URL:', url)
   client = Client()
   client.incoming_phone_numbers("my_number").update(sms_url=str(url) + '/bot')

Then I got the final error that I can't solve by my self:

 File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py", line 442, in update
   payload = self._version.update(method='POST', uri=self._uri, data=data, )
 File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/twilio/base/version.py", line 106, in update
   raise self.exception(method, uri, response, 'Unable to update record')
twilio.base.exceptions.TwilioRestException: 
HTTP Error Your request was:

POST /Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json

Twilio returned the following information:

Unable to update record: The requested resource /2010-04-01/Accounts/my_account_SID/IncomingPhoneNumbers/+my_number.json was not found

More information may be available here:

https://www.twilio.com/docs/errors/20404

I tried all different phone numbers combinations/formats: nothing works.

Thanks for your time reading all this!

alexdlaird
  • 1,174
  • 12
  • 34
ringurla
  • 1
  • 1

1 Answers1

0

Looks like something changed since the blog was written or there was a mistake.

Try the below:

  • The only difference is adding .public_url to the url object. Also allowed a GET to /bot for testing.
from dotenv import load_dotenv
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse

load_dotenv()
app = Flask(__name__)


@app.route('/bot', methods=['POST','GET'])
def bot():
    user = request.values.get('From', '')
    resp = MessagingResponse()
    resp.message(f'Hello, {user}, thank you for your message!')
    return str(resp)


def start_ngrok():
    from twilio.rest import Client
    from pyngrok import ngrok

    url = ngrok.connect(5000)
    print('This is',url)
    print(' * Tunnel URL:', url)
    client = Client()
    client.incoming_phone_numbers.list(
    phone_number=os.environ.get('TWILIO_PHONE_NUMBER'))[0].update(
        sms_url=url.public_url + '/bot')


if __name__ == '__main__':
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        start_ngrok()
    app.run(debug=True)
Alan
  • 10,465
  • 2
  • 8
  • 9
  • Hi @Alan, thanks! Still getting same error. It seems to me the request is well done and twilio still gives me an empty list (as you can see below). Maybe I am setting wrongly my phone number or some twilio configuration. Does it work for you? {"first_page_uri": "/2010-04-01/Accounts/MY_AC/IncomingPhoneNumbers.json?PhoneNumber="MY_PHONE"&PageSize=50&Page=0", "end": 0, "previous_page_uri": null, ***"incoming_phone_numbers": []***, "uri": "/2010-04-01/Accounts/MY_AC/IncomingPhoneNumbers.json?PhoneNumber=MY_PHONE&PageSize=50&Page=0", "page_size": 50, "start": 0, "next_page_uri": null, "page": 0} – ringurla Jan 18 '21 at 13:51
  • What does this output (it should show you the phone numbers in your account)? (make sure to use your production Account SID and Auth Token replacing '$TWILIO_ACCOUNT_SID' and $TWILIO_AUTH_TOKEN) when you try it: `curl -X GET 'https://api.twilio.com/2010-04-01/Accounts/'$TWILIO_ACCOUNT_SID'/IncomingPhoneNumbers.json?PageSize=20' \ -u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN` – Alan Jan 18 '21 at 13:53
  • Hi @Alan, this is what I get. I used credentials found in /console (I guess those are production, I have a free Twilio account): {"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}curl: (3) URL using bad/illegal format or missing URL curl: (3) URL using bad/illegal format or missing URL. – ringurla Jan 18 '21 at 20:38
  • Sounds like the command syntax is off, try the below replacing the ACXXX and AUTH_TOKEN with your own (correct on main page of Twilio Console): `curl -X GET 'https://api.twilio.com/2010-04-01/Accounts/ACXXX/IncomingPhoneNumbers.json?PageSize=20' -u ACXXX:AUTH_TOKEN ` – Alan Jan 18 '21 at 23:30
  • Hi @Alan, thanks for your following up, I really do appreciate it. Now it seems to work and it is a similar message as I shown a few comments above: {"first_page_uri": "/2010-04-01/Accounts/AC88148adbefbae8b3e1bbf9980f142926/IncomingPhoneNumbers.json?PageSize=20&Page=0", "end": 0, "previous_page_uri": null, "incoming_phone_numbers": [], "uri": "/2010-04-01/Accounts/AC88148adbefbae8b3e1bbf9980f142926/IncomingPhoneNumbers.json?PageSize=20&Page=0", "page_size": 20, "start": 0, "next_page_uri": null, "page": 0}%. – ringurla Jan 18 '21 at 23:58
  • Verify you have phone numbers in your account. What the blog code does is bind a Twilio phone number to the Ngrok dynamic URL. – Alan Jan 19 '21 at 00:08
  • Hi @Alan, thanks for your time again. You were right, I hadn’t set a number. I was using “Twilio SandBox for WhatsApp” number, because I thought the code would change that webhook URL (“When a message comes in”). I apologize for such a silly mistake. If you don’t mind, could you tell me if there is a way to do something similar and change the webhook URL field for the Sandbox for WhatsApp? Thank you very much again for your patience – ringurla Jan 19 '21 at 16:06
  • I don't believe the WhatsApp Sandbox exposes the configuration via API to change. – Alan Jan 19 '21 at 16:53