Getting error making calls with twilio python api - python

Getting this error when I try to make a call with the twilio python api:
Jacob-Mac-mini:downloads kovyjacob$ python3 twilio_call.py
Traceback (most recent call last):
File "/Users/kovyjacob/Downloads/twilio_call.py", line 11, in <module>
call = client.calls.create(
File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/rest/api/v2010/account/call/__init__.py", line 141, in create
payload = self._version.create(method='POST', uri=self._uri, data=data, )
File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/base/version.py", line 205, in create
raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
POST /Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json
Twilio returned the following information:
Unable to create record: The requested resource /2010-04-01/Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
I checked the link, but a) I'm not sure what the problem is exactly, and b) it doesn't say how to fix it.
This is the code:
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ['AC766eaf7ef8d79de658756223cee446df']
auth_token = ['74ef4743a7a9a748cxxxxxxxxxxxxxxx']
client = Client(account_sid, auth_token)
call = client.calls.create(
twiml='<Response><Say>Ahoy, World!</Say></Response>',
to='+14372341004',
from_='+14243560675'
)
print(call.sid)

account_sid and auth_token should be passed as strings, not array with string inside.
Twillio Rest Client Source Code
Edit your code to:
account_sid = 'AC766eaf7ef8d79de658756223cee446df'
auth_token = '74ef4743a7a9a748cxxxxxxxxxxxxxxx'

Related

Error when extracting data from JSON webhook

I am not able to access the data from the event in the python function
I am trying to get the name from the JSON
def handler(event, context):
resp = event
user_name = resp['body']['user']['name']
but I get the following error
ERROR] TypeError: string indices must be integers
Traceback (most recent call last):
File "/var/task/index.py", line 28, in handler
user_name = resp['body']['user']['name']
It seems that resp is of string type. load your response in JSON before accessing it.
import json
resp = json.loads(resp)
The below solution worked for me. The event body should be retrieved first
import json
def handler(event, context):
resp = json.loads(event["body"])
user_name = event['user']['name']

Credentials are required to create a TwilioClient

I want to send whatsapp messages using python using the Twilio module. I got a code from youtube and when ran the code ,it came with an error as
Traceback (most recent call last):
File "whatsapp.py", line 4, in <module>
client = Client()
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\twilio\rest\__init__.py", line
54, in __init__
raise TwilioException("Credentials are required to create a TwilioClient")
twilio.base.exceptions.TwilioException: Credentials are required to create a TwilioClient
Here is my code:
from twilio.rest import Client
client = Client()
from_whatsapp_number = 'whatsapp: +60***86744'
to_whatsapp_number = 'whatsapp: +8134***727'
client.messages.create(body='Testing message using python',
from_ = from_whatsapp_number,
to = to_whatsapp_number)
From the docs, a Client should be declared as follows:
from twilio.rest import Client
# Your Account SID from twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
# Your Auth Token from twilio.com/console
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
You were missing your account_sid and auth_token when you declared your Client.
As #Alan pointed out, if account_sid and auth_token are not declared in the Client, Twilio looks for them as environment variables, TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN respectively.

Why do I get an authentication error with SMTP?

Every time I run this program, it runs the first time, but the second time it gives this error in terminal:
Traceback (most recent call last):
File "main.py", line 30, in <module>
timenow = datetime.now()
File "main.py", line 27, in temperature
moApparent = regexApparentTemp.search(str(json_object))
File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 888, in append_row
return self.spreadsheet.values_append(self.title, params, body)
File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 119, in values_append
r = self.client.request('post', url, params=params, json=body)
File "/usr/local/lib/python3.7/dist-packages/gspread/client.py", line 79, in request
raise APIError(response)
gspread.exceptions.APIError: {
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
The code is:
import requests, pprint, re, gspread, time
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
def temperature():
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Singapore-Weather-84def2be176a.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open('Singapore Weather').sheet1
r = requests.get('https://api.darksky.net/forecast/b02b5107a2c9c27deaa3bc1876bcee81/1.312914,%20103.780257')
json_object = r.text
regexCurrentTemp = re.compile(r'"temperature":(\d\d.\d\d)')
moTemp = regexCurrentTemp.search(str(json_object))
temperature = moTemp.group(1)
regexApparentTemp = re.compile(r'"apparentTemperature":(\d\d.\d\d)')
moApparent = regexApparentTemp.search(str(json_object))
apparent = moApparent.group(1)
timenow = datetime.now()
wks.append_row([str(timenow), temperature, apparent])
while True:
temperature()
time.sleep(3597)
I put the autentication within the function in the loop so it would work, but it didn't. What is the problem?
As you can see on Github googleapis/oauth2client is deprecated
I would suggest you to try official Gmail API Python example:
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string(
))}
If you struggle with an example above try the Gmail API Quickstart Python tutorial

Authenticate to linkedin

I am trying to write a code that get some user's linkedin profile and just print it
this is my code
from linkedin import linkedin
CONSUMER_KEY = "XXXXX"
CONSUMER_SECRET = "XXXXX"
RETURN_URL = r"http://localhost:8000"
authentication = linkedin.LinkedInAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(authentication)
a = application.get_profile(member_url=my_url)
print(a)
I get the following error
Traceback (most recent call last):
File "C:/Users/Linkedin/main.py", line 28, in <module>
a = application.get_profile(member_url=my_url)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 189, in get_profile
response = self.make_request('GET', url, params=params, headers=headers)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 169, in make_request
params.update({'oauth2_access_token': self.authentication.token.access_token})
AttributeError: 'NoneType' object has no attribute 'access_token'
What do I do wrong?
Not tested. Try this
As per the documentation. Access token must be generated to grand access to the application.
authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(token=authentication.get_access_token())
print authentication.authorization_url
When you grant access to the application, you will be redirected to the return url with the following query strings appended to your RETURN_URL:
"http://localhost:8000/?code=AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8&state=ea34a04b91c72863c82878d2b8f1836c"
Copy the code manually and set like
authentication.authorization_code = 'AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8'
authentication.get_access_token() #AQTFtPILQkJzXHrHtyQ0rjLe3W0I
application = linkedin.LinkedInApplication(token='AQTFtPILQkJzXHrHtyQ0rjLe3W0I')

Python Dropbox API error: 'The provided token does not allow this operation' [duplicate]

I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.

Categories

Resources