Credentials are required to create a TwilioClient - python

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.

Related

Getting error making calls with twilio python api

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'

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

'Client' object has no attribute 'sms'

I'm an intro to programming student. The following code is supposed to send a text message to my phone, but it is giving me the error message:
'Client' object has no attribute 'sms'
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
auth_token = "42xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
client = Client(account_sid, auth_token)
message = client.sms.messages.create(
body="Hello!",
to="+19545555555", # Replace with your phone number
from_="+17725555555") # Replace with your twilio number
print message.sid
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
auth_token = "42xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
client = Client(account_sid, auth_token)
message = client.messages.create(
body="Hello!",
to="+19545555555", # Replace with your phone number
from_="+17725555555") # Replace with your twilio number
print message.sid
Try this. It there shouldn't be an sms

HttpError 400 Bad Request - Google Admin Directory API (Python)

I'm having difficulty creating a Google Project as a Service Account. I am using the Admin SDK in Python, specifically the Directory API. I believe I am authenticating correctly but when it comes to calling users.list I get the following error:
Traceback (most recent call last):
File "googleproject.py", line 17, in <module>
userlist = service.users().list().execute(http = http_auth)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 135, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/admin/directory/v1/users?alt=json returned "Bad Request">
My code is as follows:
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build
#----AUTHORISATION----#
client_email = '*****#developer.gserviceaccount.com'
with open('*****.p12') as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/admin.directory.user')
http_auth = credentials.authorize(Http())
#--------------------#
service = build('admin', 'directory_v1', http = http_auth)
userlist = service.users().list().execute(http = http_auth)
I have tried it with and without passing http = http_auth as an argument to execute(). I've basically followed the example given here: https://code.google.com/p/google-api-python-client/source/browse/samples/service_account/tasks.py
I have enabled Admin SDK in the Developers console, as well as added the client id and scope in the Google Apps control panel.
I managed to fix it! The problem was I wasn't setting the domain in the list argument. So the new code is as follows:
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
from apiclient.discovery import build
#----AUTHORISATION----#
client_email = '*****#developer.gserviceaccount.com'
with open('*****') as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/admin.directory.user', sub = 'super-admin#domain.com')
http_auth = credentials.authorize(Http())
#--------------------#
service = build('admin', 'directory_v1', http = http_auth)
user = service.users().list(showDeleted = False, domain = 'domain.com').execute()

Creating a DfpClient with a Service Account in Python

I use the google DFP api to collect some statistics on ads clicked on our website. The
code is written in Python. Currently, I am trying to upgrade the code to use oAuth 2.
Since, the code runs automatically everyday without any user involvement, I created a
service account under my google project and added the account to the DoubleClick for
Publishers network of our company. Based on the sample codes on the web, I wrote this:
import httplib2
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.discovery import build
from googleads.dfp import DfpClient
GOOGLE_DFP_SCOPE="https://www.googleapis.com/auth/dfp"
API_VERSION="v201411"
KEY_FILE="*******.p12"
ACCT_EMAIL="************************#developer.gserviceaccount.com"
NETWORK_CODE="**********"
with open(KEY_FILE) as config_file:
my_private_key = config_file.read()
credentials = SignedJwtAssertionCredentials(service_account_name=ACCT_EMAIL, private_key=my_private_key,scope=GOOGLE_DFP_SCOPE)
http = httplib2.Http()
http_auth = credentials.authorize(http)
dfp_client = build(serviceName='dfp',version=API_VERSION,http=http_auth)
This code does not seem to be correct, because the network_code has not been passed
anywhere in the code. In addition, it fails with the following message:
apiclient.errors.UnknownApiNameOrVersion: name: dfp version: v201411.
Also, the line below:
dfp_client = DfpClient.LoadFromStorage()
does not work for my case, because, this is based on googleads.yaml which seems
to be formatted only for web-app accounts with client secret, not P12 private key.
Any advice? Thanks.
Apiclient.discovery uses a default route to check the services.
But I did not find a service for DoubleClick for publishers.
I use this code to use API with Oauth2. Using Flask
import json
import requests
import flask
from googleads import dfp
from googleads import oauth2
app = flask.Flask(__name__)
CLIENT_ID = ''
CLIENT_SECRET = '' # Read from a file or environmental variable in a real app
SCOPE = 'https://www.googleapis.com/auth/dfp'
REDIRECT_URI = ''
APPLICATION_NAME = 'DFP API SERVICE'
NETWORK_CODE = ''
#app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('oauth2callback'))
credentials = json.loads(flask.session['credentials'])
if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauth2callback'))
else:
try:
refresh_token = credentials['refresh_token']
oauth2_client = oauth2.GoogleRefreshTokenClient(CLIENT_ID, CLIENT_SECRET, refresh_token)
dfp_client = dfp.DfpClient(oauth2_client, APPLICATION_NAME, NETWORK_CODE)
user_service = dfp_client.GetService('UserService', version='v201508')
user = user_service.getCurrentUser()
return flask.render_template('index.html', name=user['name'])
except:
flask.session.pop('credentials', None)
return flask.redirect(flask.url_for('oauth2callback'))
#app.route('/oauth2callback')
def oauth2callback():
if 'code' not in flask.request.args:
auth_uri = ('https://accounts.google.com/o/oauth2/auth?response_type=code'
'&access_type=offline&client_id={}&redirect_uri={}&scope={}&').format(CLIENT_ID, REDIRECT_URI, SCOPE)
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
data = {'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code'}
r = requests.post('https://www.googleapis.com/oauth2/v3/token', data=data)
flask.session['credentials'] = r.text
return flask.redirect(flask.url_for('index'))
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = False
app.run()
I hope this help you
You are correct. You have to pass the network code when you create a dfp client. And version is not necessary. Try the following code to create the client in python.
import os
from googleads import oauth2
from googleads import dfp
def get_dfp_client():
application_name = "Your application name" # from google developer console. eg: Web Client
network_code = ********
private_key_password = 'notasecret'
key_file = os.path.join('path/to/p12file')
service_account_email = '****#***.iam.gserviceaccount.com'
# create oath2 client(google login)
oauth2_client = oauth2.GoogleServiceAccountClient(
oauth2.GetAPIScope('dfp'), service_account_email, key_file)
dfp_client = dfp.DfpClient(oauth2_client, application_name, network_code)
return dfp_client
client = get_dfp_client()
Reference
Please comment if you need more clarification.
Update
googleads renamed module dfp to ad_manager, docs here – Gocht

Categories

Resources