'Client' object has no attribute 'sms' - python

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

Related

Show first and last name in header when using Gmail API (python)

I have my mail my_name#company.com and uses gmails API (and python) to send some mails. The problem is that when the mail hit the inbox the "from" is shown as my_name#company.com '<my_name#company.com>' where I want it to be First Name <my_name#company.com>.
I have tried using different variations of "First Name '<my_name#company.com>'" but I get a RefreshError: ('invalid_request: Invalid impersonation "sub" field.', '{\n "error": "invalid_request",\n "error_description": "Invalid impersonation \\u0026quot;sub\\u0026quot; field."\n}').
from __future__ import print_function
from googleapiclient.discovery import build
from apiclient import errors
from httplib2 import Http
from email.mime.text import MIMEText
import base64
from google.oauth2 import service_account
# Email variables. Modify this!
EMAIL_FROM = "First Last '<my_name#company.com>'"
EMAIL_TO = 'some_mail#hotmail.com'
EMAIL_SUBJECT = 'Hello from Me!'
EMAIL_CONTENT = 'Some body'
# Call the Gmail API
def service_account_login():
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
SERVICE_ACCOUNT_FILE = 'my-credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(EMAIL_FROM)
service = build('gmail', 'v1', credentials=delegated_credentials)
return service
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
return {"raw": raw}
def send_message(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
service = service_account_login()
message = create_message(EMAIL_FROM, EMAIL_TO, EMAIL_SUBJECT, EMAIL_CONTENT)
sent = send_message(service,'me', message)
I just sent an email recently showing the name as you wanted, I got it with this line, similar to what you already had but without the single quotation marks:
message['from'] = "First Name <something#example.com>"
So the trick is fairly simple - the EMAIL_FROM is first used to create a service with that email, which is why you cannot write My Name <my_name#company.com>. You can do that when you need to specify the "FROM " mail e.g in the very buttom of create_message= f"First name<{EMAIL_FROM}>,...)

Power BI Rest API - AADSTS50034: The user account {EmailHidden} does not exist in the XXXXX directory

I'm trying to get an access token instead of getting this error message
AdalError: Get Token request returned http error: 400 and server response: {"error":"invalid_grant","error_description":"AADSTS50034: The user account {EmailHidden} does not exist in the XXXXX directory. To sign into this application, the account must be added to the directory.\r\nTrace ID: f18021a8-b10a-40bf-9f0a-7975b38e2300\r\nCorrelation ID: 4f61c8f5-ed06-41f1-8d7b-756dd7c09e10\r\nTimestamp: 2020-12-16 03:27:49Z","error_codes":[50034],"timestamp":"2020-12-16 03:27:49Z","trace_id":"f18021a8-b10a-40bf-9f0a-7975b38e2300","correlation_id":"4f61c8f5-ed06-41f1-8d7b-756dd7c09e10","error_uri":"https://login.windows.net/error?code=50034"}
My python code
import adal
import json
import pyodbc
import requests
AUTHORITY_URL = 'https://login.windows.net/XXXXX'
RESOURCE = 'https://analysis.windows.net/powerbi/api'
CLIENT_ID = 'XXXXX'
userid='nurdin#xxxxx.com.my'
userpassword='xxxxx'
completedtime = []
verify = []
def make_headers(access_token):
return {
'Authorization': 'Bearer {}'.format(access_token)
}
context = adal.AuthenticationContext(AUTHORITY_URL)
token = context.acquire_token_with_username_password(RESOURCE,userid,userpassword,CLIENT_ID)
access_token = token['accessToken']
print(access_token)
Your code works fine on my side, make sure your work account is under the tenant in the AUTHORITY_URL, if not, you could follow this link to create a new user without MFA-enabled.
import adal
AUTHORITY_URL = 'https://login.windows.net/<tenant-id>'
RESOURCE = 'https://analysis.windows.net/powerbi/api'
CLIENT_ID = '<client-id>'
userid='username#tenantname.onmicrosoft.com'
userpassword='xxxxxx'
context = adal.AuthenticationContext(AUTHORITY_URL)
token = context.acquire_token_with_username_password(RESOURCE,userid,userpassword,CLIENT_ID)
access_token = token['accessToken']
print(access_token)

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.

Twitter API OAuth cannot find 'authorization_url'

I'm writing a code that uses Twitter API to get users' statuses, number of followers etc. I need to write a script that opens browser and asks users to sign in and let me get the authentication from them.
from requests_oauthlib import OAuth1Session
import requests
from requests_oauthlib import OAuth1
from urlparse import parse_qs
client_key = "keykeykeykey"
client_secret = "keykeykeykeykey"
request_token_url = 'https://api.twitter.com/oauth/request_token'
oauth = OAuth1Session(client_key, client_secret=client_secret)
fetch_response = oauth.fetch_request_token(request_token_url)
#print(fetch_response)
resource_owner_key = fetch_response.get('oauth_token')
resource_owner_secret = fetch_response.get('oauth_token_secret')
oauth = OAuth1(client_key, client_secret=client_secret)
r = requests.post(url=request_token_url, auth=oauth)
#print(r.content)
credentials = parse_qs(r.content)
resource_owner_key = credentials.get('oauth_token')[0]
resource_owner_secret = credentials.get('oauth_token_secret')[0]
base_authorization_url = 'https://api.twitter.com/oauth/authorize'
authorization_url = oauth.authorization_url(base_authorization_url)
print 'Please go here and authorize,', authorization_url
redirect_response = raw_input('Paste the full redirect URL here: ')
oauth_response = oauth.parse_authorization_response(redirect_response)
#print(oauth_response)
verifier = oauth_response.get('oauth_verifier')
authorize_url = base_authorization_url + '?oauth_token='
authorize_url = authorize_url + resource_owner_key
print 'Please go here and authorize,', authorize_url
verifier = raw_input('Please input the verifier')
I have found this kind of example from internet but it gives an error like :
AttributeError: 'OAuth1' object has no attribute 'authorization_url'
I have checked the session info and actually there is authorization_url here:
https://github.com/requests/requests-oauthlib/blob/master/requests_oauthlib/oauth1_session.py
It looks like you use the oauth variable as an OauthSession object and a Oauth1 object.
oauth = OAuth1Session(client_key, client_secret=client_secret)
oauth = OAuth1(client_key, client_secret=client_secret)
It should work if you use it as a session object

Cannot retrieve authenticated data from Twitter using access_token

I am trying to create generic class in python which will do all the oAuth process and then will allow to retrieve data from any oAuth supporting service (for example Twitter,LinkedIn).
Edited:
I have customer key and secret and access token key and secret,when I try to request any resource request I get the following error:
{"error":"Could not authenticate with OAuth.","request":"\/1\/statuses\/retweeted_by_me.json}'
any idea why?
My Code is:
import httplib
import time
import oauth as oauth
# settings for the local test consumer
SERVER = 'api.twitter.com'
RESOURCE_URL = 'https://api.twitter.com/1/statuses/retweeted_by_me.json'
CONSUMER_KEY = 'MY_CUSTOMER_KEY'
CONSUMER_SECRET = 'MY_CUSTOMER_SECRET'
ACCESS_TOKEN_KEY = 'MY_ACCESS_TOKEN_KEY'
ACCESS_TOKEN_SECRET = 'MY_ACCESS_TOKEN_SECRET'
# example client using httplib with headers
class SimpleOAuthClient(oauth.OAuthClient):
def __init__(self, server):
self.server = server
self.connection = httplib.HTTPSConnection(self.server)
def access_resource(self, oauth_request):
# via post body
# -> some protected resources
self.connection.request(oauth_request.http_method, RESOURCE_URL)
response = self.connection.getresponse()
return response.read()
def run_example2():
print '** OAuth Python Library Example **'
client = SimpleOAuthClient(SERVER, )
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
pause()
# access some protected resources
print '* Access protected resources ...'
pause()
token = oauth.OAuthToken('ACCESS_TOKEN_KEY', 'ACCESS_TOKEN_SECRET')
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='GET', http_url=RESOURCE_URL)
oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
print 'REQUEST (via post body)'
print 'parameters: %s' % str(oauth_request.parameters)
pause()
params = client.access_resource(oauth_request)
print 'GOT'
print 'non-oauth parameters: %s' % params
pause()
def pause():
print ''
time.sleep(1)
if __name__ == '__main__':
run_example2()
print 'Done.'
AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authenticate'
This is the incorrect URL to use for OAuth. If you look at Twitter's 3-legged OAuth documentation, they state "The GET oauth/authorize endpoint is used instead of /oauth/authenticate". Change the URL to "https://api.twitter.com/oauth/authorize" and try again.
I managed to fix it by changing self.connection.request(oauth_request.http_method, RESOURCE_URL)
to self.connection.request(oauth_request.http_method, oauth_request.to_url())
Notice that will will work only if oauth_request.http_method is GET

Categories

Resources