Twilio Autopilot Python quickstart tutorial - python

I am trying to follow the following Twilio Autopilot tutorial https://www.twilio.com/docs/autopilot/quickstart/python?code-sample=code-create-your-first-assistant-with-autopilot-7&code-language=Python&code-sdk-version=6.x
I am trying to create my first assistant with autopilot and my own account_sid and auth_token.
# Download the helper library from
https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
assistant = client.autopilot \
.assistants \
.create(
friendly_name='Quickstart Assistant',
unique_name='quickstart-assistant'
)
print(assistant.sid)
However i receive the following error when i try execute the script.

Twilio developer evangelist here.
Did you by chance run this script more than once? The unique_name must be unique, so if you ran the script twice without changing that value, the second try would fail.
I tried running the code example you posted (with my own account credentials), and it worked the first time but failed the second time with the same exact error message you got (35002). Changing the unique_name value to quickstart-assistant-2, the script ran successfully again.
If you can log in to Twilio, you should be able to see the list of autopilot assistants you have created, which would tell you if you were able to create the assistant successfully on the first try.
Let me know if you have any additional questions or issues.

Related

Twilio Whatsapp Sandbox Configuration for deploying application via AWS elastic beanstalk

enter image description here
Currently I am developing a chatbot for my application with django, using a twilio trial account.
The chatbot functions properly with ngrok.io, i.e. when the server is operating locally, which mean that when I send a whatsapp message to the twilio sandbox with operation of simply "python manage.py runserver", he will automatically reply me according to my script.
However, as I started deploying the application using the AWS elastic beanstalk, I found that it is only possible for the sandbox to send out whatsapp message by POST request on the web application, but not capable to respond to POST request sent out from whatsapp.
In what way I can deal with it? Is it related to AWS settings or Twilio settings? Some CORS related issues?
Great thanks in advance.
(Please forgive me if my use of language is not accurate as I am not with computer science background.)
Below is part of the code that I applied.
#csrf_exempt
def message(request):
account_sid = 'xxx'
auth_token = 'xxx'
client = Client(account_sid, auth_token)
client_phone_number = request.POST.get('From').removeprefix("whatsapp:+852")
client_phone_number.removeprefix("+852")
incoming_message = request.POST.get('Body')
conversation_sid = request.POST.get('conversation_sid')
incoming_message = incoming_message.lower()
response = MessagingResponse()
#processing the incoming message to produce the text
resp = "text"
response.message(resp)
return HttpResponse(str(response))
I have tried pasting https://xxxxx-env.yyyyyyy.us-east-1.elasticbeanstalk.com/whatsapp/ to the sandbox configuration cell as shown in the image and it resulted to what I mentioned above. The whatsapp url is set just like typically done for other urls for django, followed by message(request) to process the request sent out from the whatsapp. Any other proper way I can do it?

Must I always use `url` field in making outbound calls with Twilio API in Python?

I've been trying to figure out how to make outbound call to leave a voicemail when answering machine is detected. I'm still in the beginning of the exploration and been trying to follow Twilio example like this. I want to use Python, so I'm copy-pasting the example from Twilio below:
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'your account sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
call = client.calls.create(
url='http://demo.twilio.com/docs/voice.xml',
to='+1555123456',
from_='+1501123456'
)
print(call.sid)
In the above code, it seems like Twilio's Python SDK always expects url (publicly available XML file/response) as resource to ping to. I'm wondering if I can build a valid XML (TwiML) file and refer to it in the above client.calls.create(...) call. In other words, how do I make Twilio 'speak' what I designed in my local (on my computer) XML file (if that's even possible)? I only plan to run my Python script from my personal computer on need basis, and I don't have any access to server anywhere.
Thank you in advance for your answer/suggestion!
A publicly accessible URL is a requirement. You can use Twilio Studio or Twilio Serverless Functions if you want Twilio to host your logic so you don't need to expose a public URL.
For development, you can use a tool called Ngrok, which will tunnel the Twilio TwiML request to your private application.
You can find more detail here.
How to test webhooks locally with ngrok - Twilio Tip #6
Well you could test this about by using pythons simple http server. and just have it server that file.
curl http://demo.twilio.com/docs/voice.xml -o voice.xml
python -m SimpleHTTPServer
#run to above commands then
#try using bellow?
call = client.calls.create(
url='http://localhost:8000/voice.xml',
to='+1555123456',
from_='+1501123456'
)
#the file at that location is dead simple
<Response>
<Say voice="alice">Thanks for trying our documentation. Enjoy!</Say>
<Play>http://demo.twilio.com/docs/classic.mp3</Play>
</Response>

Authentication OneDrive API Python

Using code sample from GitHub that is specifically for setting up authentication for Python access to OneDrive API (I'm beginning to think this source is outdated), I've failed to make it past the part where you paste code provided by Microsoft after executing program..
Python code:
import onedrivesdk
redirect_uri = 'https://login.microsoftonline.com/common/oauth2/nativeclient'
client_secret = '*this code omitted*'
client_id='*this code omitted*'
api_base_url='https://api.onedrive.com/v1.0/'
scopes=['onedrive.readwrite']
http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(
http_provider=http_provider,
client_id=client_id,
scopes=scopes)
client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
# Ask for the code
print('Paste this URL into your browser, approve the app\'s access.')
print('Copy everything in the address bar after "code=", and paste it below.')
print(auth_url)
code = raw_input('Paste code here: ')
client.auth_provider.authenticate(code, redirect_uri, client_secret)
After executing code and pasting url in browser, a popup shows up, where I verify that I want to give my app access to API.. I hit "Ok."
I am then presented with code in URL taskbar. I copy and paste code into program..
Then the error I get is:
raise Exception(str(message["error"]))
Exception: invalid_request
Link to GitHub source used: https://github.com/OneDrive/onedrive-sdk-python
Note: I had to omit scopes such as the first two in this list:
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
because they apparently don't exist (according to error code provided by Microsoft after pasting URL into taskbar)
Is there a better source for setting up authentication for a Python program to communicate with OneDrive API?
I am a relatively new Python user, your patience is appreciated.
I ran into the same issue and the solution was to include the redirect_uri in the app registration.
This can be done at https://portal.azure.com/ und Azure Active Directory > App registrations > "Your App" > Authentication. In my case, I needed to add http://localhost:8080/ to the redirect URIs.
I found the suggestion here:
https://github.com/OneDrive/onedrive-sdk-python/issues/98
Hope it helps someone save some time.

How to send customized reposne using Twilio API?

I am new to Twilio API and I am calling to a number and I want to play a customized message. Can anyone tell me how to do it? I know that I have to create a response file but I am not sure how to give that file in URL.
Here is my code.
# Download the library from twilio.com/docs/libraries
from twilio.rest import TwilioRestClient
# Get these credentials from http://twilio.com/user/account
account_sid = "xxxxxx"
auth_token = "yyyyyy"
client = TwilioRestClient(account_sid, auth_token)
# Make the call
call = client.calls.create(to="aaaaa", # Any phone number
from_="bbbbb", # Must be a valid Twilio number
url="??????")
print call.sid
What should I write in URL?
Thanks
Twilio developer evangelist here.
There are a couple of things you can do here. The url you enter in the outgoing call needs to respond with some XML (TwiML) when Twilio requests it.
If you want Twilio to play a message, you could write the following TwiML:
<Response>
<Say>Hello from my new Twilio app</Say>
</Response>
This can be a static file hosted anywhere. For example, you could use http://twimlbin.com/ to host it and then use the url given to you by that service.
Alternatively, you could create a webserver application using something like Python's Flask. There is a guide to this on the Twilio site here: https://www.twilio.com/docs/quickstart/python/twiml/say-response. You can then open your local development site to Twilio using a tool like ngrok and there's a good explanation of how to do that in this blog post: https://www.twilio.com/blog/2013/10/test-your-webhooks-locally-with-ngrok.html.
Hope that helps, let me know if there's anything more I can help you with.

Unable to generate refresh token for AdWords account using OAuth2

I am having trouble generating a refresh token using Python for the AdWords API & need some help. Here is the situation:
I have a client on AdWords that I want to pull reports for through the AdWords API (we have a developer token now for this). Let's say that, in AdWords, the clients account is 521-314-0974 (making this up). Here is where I am confused:
Below is the following code snippet needed to generate a refresh token that I am trying to get working:
"""Generates a refresh token for use with AdWords."""
__author__ = 'Nathaniel Payne'
import sys
import urllib2
from oauthlib import oauth2
# Your OAuth 2.0 Client ID and Secret. If you do not have an ID and Secret yet,
# please go to https://console.developers.google.com and create a set.
CLIENT_ID = 'INSERT_CLIENT_ID_HERE'
CLIENT_SECRET = 'INSERT_CLIENT_SECRET_HERE'
# You may optionally provide an HTTPS proxy.
HTTPS_PROXY = None
# The AdWords API OAuth 2.0 scope.
SCOPE = u'https://adwords.google.com/api/adwords'
# This callback URL will allow you to copy the token from the success screen.
CALLBACK_URL = 'urn:ietf:wg:oauth:2.0:oob'
# The HTTP headers needed on OAuth 2.0 refresh requests.
OAUTH2_REFRESH_HEADERS = {'content-type':
'application/x-www-form-urlencoded'}
# The web address for generating new OAuth 2.0 credentials at Google.
GOOGLE_OAUTH2_AUTH_ENDPOINT = 'https://accounts.google.com/o/oauth2/auth'
GOOGLE_OAUTH2_GEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'
def main():
oauthlib_client = oauth2.WebApplicationClient(CLIENT_ID)
authorize_url = oauthlib_client.prepare_request_uri(
GOOGLE_OAUTH2_AUTH_ENDPOINT, redirect_uri=CALLBACK_URL, scope=SCOPE)
print ('Log in to your AdWords account and open the following URL: \n%s\n' %
authorize_url)
print 'After approving the token enter the verification code (if specified).'
code = raw_input('Code: ').strip()
post_body = oauthlib_client.prepare_request_body(
client_secret=CLIENT_SECRET, code=code, redirect_uri=CALLBACK_URL)
if sys.version_info[0] == 3:
post_body = bytes(post_body, 'utf8')
request = urllib2.Request(GOOGLE_OAUTH2_GEN_ENDPOINT, post_body,
OAUTH2_REFRESH_HEADERS)
if HTTPS_PROXY:
request.set_proxy(HTTPS_PROXY, 'https')
raw_response = urllib2.urlopen(request).read().decode()
oauth2_credentials = oauthlib_client.parse_request_body_response(raw_response)
print ('Your access token is %s and your refresh token is %s'
% (oauth2_credentials['access_token'],
oauth2_credentials['refresh_token']))
print ('You can cache these credentials into a yaml file with the '
'following keys:\nadwords:\n client_id: %s\n client_secret: %s\n'
' refresh_token: %s\n'
% (CLIENT_ID, CLIENT_SECRET, oauth2_credentials['refresh_token']))
if __name__ == '__main__':
main()
Questions:
1) Do I need to have a special project set-up for every AdWords customer in the console.developers.google.com, in order to pull from the AdWords Reporting API? Or, can I simply provide the client secret and ID for a generic account in the console?
2) Following from this, can someone please confirm what should go in place of the client_ID & Client_Secret in order to make the Python code block below work. What I mean is, I was using the client ID and client secret from https://console.developers.google.com ... for the analytics account that we have billing set-up on (and which I have used for BigQuery API access previously). Is that correct? I am not seeing clearly how this will be linked to the AdWords account for this client.
2) In the consent screen, I put my own e-mail, since I am owner of the project,. That said, when I run the code, I get the link to the URL that I need to run to generate the code. That said, when I sun this snippet:
print ('Log in to your AdWords account and open the following URL: \n%s\n' %
authorize_url)
print 'After approving the token enter the verification code (if specified).'
code = raw_input('Code: ').strip()
I get an error. This is the message that I get in error:
Error: redirect_uri_mismatch
The redirect URI in the request: urn:ietf:wg:oauth:2.0:oob did not match a registered redirect URI
Learn more
Request Details
cookie_policy_enforce=false
scope=https://adwords.google.com/api/adwords
response_type=code
access_type=online
redirect_uri=urn:ietf:wg:oauth:2.0:oob
display=page
client_id=XXXXXXXXX.apps.googleusercontent.com
I am puzzled here. Some folks suggested changing the e-mail address in the consent screen (which I did ... but was unsuccessful). Again, my simple goal is to be able to pull one report from tis clients through the AdWords API (which I will expand once I get there). Any help would be appreciated. Cheers.
After some work, I was able to successfully navigate through this issue. Here are the detailed steps that I took to get to the point where I could successfully pull data through the API. In my situation, I manage an AdWords MCC with multiple accounts. Thus, I went back to the beginning of many of the help manuals and did the following:
Create a new project called AdWords-API-XXXX.
In the credentials screen on the console, I created a new "Client ID for native application". This allowed me to generate my CLIENT_ID and the CLIENT_SECRET that I needed. Critically, it also generated a re-direct URI which was the source of my problem.
I took both of these values, added them to the main script, and ran the generate_refresh_token.py script. This allowed me to generate a working refresh token. I had to be signed into my AdWords account MCC, in order to make sure that OAuth2 provided me the ability to access all potential AdWord clientsinside my MCC. I got an authentication screen generated by URL for this process which asked me to confirm that permission was being granted for AdWords access.
Following this, I created a new googleads.yaml script and placed this in my c:\gsutil directory. This is the code in most Python programs where the program looks for the file googleads.yaml:
adwords_client = adwords.AdWordsClient.LoadFromStorage()
Once this was done, I was able to successfully run the script from my command line to generate the final output. The script was:
python download_criteria_report.py
Note of course that I have changed my path variable previously in order to run Python 2.7 from the command line. This script was run inside the directory of the download_criteria_report.py file. This script ran successfully and enabled me to pull data from the AdWords API for one of my test clients.
The next challenge will be working with the returned output from the API and putting it into a format that I can quickly use for analysis & storage.

Categories

Resources