Oauth Python twitter auth - python

import oauth2 as oauth
key = "xxxxx"
secret = "xxxxx"
request_token_url = "https://api.twitter.com/oauth/request_token"
consumer = oauth.Consumer(key= key, secret= secret)
client = oauth.Client(consumer)
resp, content = client.request(request_token_url, "GET")
print content
Once i have executed this script it works fine but what would be the best way to deal with the output it gives me.
The output is something like "xxxxxxxx&yyyyyyyyyy&zzzzzzzzz"
And i need to use the varaibles xxxx and yyyy how can i parse these and put them into variables?
Thanks
William

output = content.split('&')
x = output[0]
y = output[1]
also check out Tweepy for Python interaction with Twitter.
https://github.com/tweepy/tweepy

Related

How to create tweet using tweepy API V 2

import tweepy
ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXX'
ACCESS_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
CONSUMER_KEY = 'XXXXXXXXXXXXXXXXXXXXXX'
CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXX'
api = tweepy.Client(bearer_token='XXXXXXXXXXXXXXXXXXX',
access_token=ACCESS_KEY,
access_token_secret=ACCESS_SECRET,
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET)
api.create_tweet(text='I want to Post 3 Photos and description')
I'm using tweepy V2 But I don't know how to upload photos + descriptions
Does anyone help me? I want to tweet images with text, I've 3 image's
Had to do a little digging, as I don't have experience with tweepy, but I think I found an answer.
When you send the tweet, you can attach media using a "media id". Somewhat like this:
api.create_tweet(text = 'Images can be fun too!', media = {media_ids = ["1455952740635586573", "1234567890"]})
The media_ids list can contain multiple media IDs. However, you need to upload the images to Twitter to get the media IDs.
Tweepy provides a file upload function, that can be used like so:
mediaID = api.media_upload(filename)
Simply upload your files, put them into a dictionary, and send your tweet!
I made a little example that you can add to the end of your program.
import tweepy
ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXX'
ACCESS_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
CONSUMER_KEY = 'XXXXXXXXXXXXXXXXXXXXXX'
CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXX'
api = tweepy.Client(bearer_token='XXXXXXXXXXXXXXXXXXX',
access_token=ACCESS_KEY,
access_token_secret=ACCESS_SECRET,
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET)
mediaID1 = mediaID = api.media_upload("media1.png")
mediaID2 = mediaID = api.media_upload("image2.png")
mediaID3 = mediaID = api.media_upload("image3.png")
api.create_tweet(text='I want to Post 3 Photos and description',
media={media_ids=[mediaID1,mediaID2,mediaID3]})
Please refer to the Twitter documentation if you need a more accurate depiction of the Twitter API:
https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets
https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/api-reference/post-media-upload
I'm still a little rusty at Python and this is my first time using Stackoverflow but this should work.

"Invalid OAuth access token" on Marketing API in Python

I'm trying to access Facebook Marketing Api in Python, but I encounter some issues with the access token.
I run the following code:
def get_app_access_token(app_id, app_secret):
args = {'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret}
f = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" +
urllib.urlencode(args))
resp = json.loads(f.read())
### resp gives me {"access_token":"xxxxxx|yyyyyy", "token_type":"bearer"}
### so I extract yyyyyy as my access_token
result = resp["access_token"].split('|')[1]
access_token = get_app_access_token(APP_ID, SECRET_KEY)
api = FacebookAdsApi.init(APP_ID, SECRET_KEY, access_token)
account = AdAccount(AD_ACCOUNT)
adsets = account.get_ad_sets(fields=[AdSet.Field.name])
And I get the error "Invalid OAuth access token" on the last line.
Do you know what I did wrong?
Thank you!
I think changing result from result = resp["access_token"].split('|')[1] to result = resp["access_token"]
The Python API can use the format of "xxxxxx|yyyyyy" if you are feeding it to FacebookAdsApi however unless everything is setup properly on the Facebook developer settings for the tokens you get, I am not sure You can get proper access.
Using above I can get to the ad account okay. However my permissions for client tokens didn't allow for access to campaigns and I was using a depreciated API.

How do I call an API Gateway with Cognito credentials in Python

I've managed to setup an API Gateway secured with Cognito. The unauthenticated user role has an access policy that should grant it access to the gateway. I've also managed to use boto3 to retrieve an identity ID from the pool and obtain the associated open ID token, as well as the associated secret and access keys.
How do I now make a call to the gateway using these credentials? Is there a way to use boto3 to handle signing a request to a particular method on the API?
My code is based largely on the questioner's own answer, but I've tried to make it clearer where all the values come from.
import boto3
import requests
from requests_aws4auth import AWS4Auth
# Use 'pip install boto3 requests requests-aws4auth' to get these
region_name = 'ap-southeast-2' # or 'us-west-1' or whatever
# 12 decimal digits from your AWS login page
account_id = '123456789012'
# I've only found this in the sample code for other languages, e.g. JavaScript
# Services→Cognito→Manage Federated Identities→(your-id-pool)→Sample code
identity_pool_id = 'ap-southeast-2:fedcba98-7654-3210-1234-56789abcdef0'
# Create a new identity
boto3.setup_default_session(region_name = region_name)
identity_client = boto3.client('cognito-identity', region_name=region_name)
identity_response = identity_client.get_id(AccountId=account_id,
IdentityPoolId=identity_pool_id)
# We normally wouldn't log this, but to illustrate:
identity_id = identity_response['IdentityId']
print ('identity_id:', identity_id) # good idea not to log this
# Get the identity's credentials
credentials_response = identity_client.get_credentials_for_identity(IdentityId=identity_id)
credentials = credentials_response['Credentials']
access_key_id = credentials['AccessKeyId']
secret_key = credentials['SecretKey']
service = 'execute-api'
session_token = credentials['SessionToken']
expiration = credentials['Expiration']
# Again, we normally wouldn't log this:
print ('access_key_id', access_key_id)
print ('secret_key', secret_key)
print ('session_token', session_token)
print ('expiration', expiration)
# The access_key_id will look something like 'AKIABC123DE456FG7890', similar to
# Services→IAM→Users→(AWS_USER_NAME)→Security credentials→Access key ID
# Get the authorisation object
auth = AWS4Auth(access_key_id, secret_key, region_name, service,
session_token=session_token)
current_app['auth'] = auth
# Just an illustration again:
print ('auth: %(service)s(%(date)s) %(region)s:%(access_id)s' % auth.__dict__)
# We'll use that object to send a request to our app. This app doesn't
# exist in real life, though, so you'll need to edit the following quite
# heavily:
# Services→Cognito→Manage your User Pools→(your-user-pool)→Apps→App name
app_name = 'my-app-name'
api_path = 'dev/helloworld'
method = 'GET'
headers = {}
body = ''
url = 'https://%s.%s.%s.amazonaws.com/%s' % (app_name, service, region_name,
api_path)
response = requests.request(method, url, auth=auth, data=body, headers=headers)
The following code (and the requests-aws4auth library) did the job:
import boto3
import datetime
import json
from requests_aws4auth import AWS4Auth
import requests
boto3.setup_default_session(region_name='us-east-1')
identity = boto3.client('cognito-identity', region_name='us-east-1')
account_id='XXXXXXXXXXXXXXX'
identity_pool_id='us-east-1:YYY-YYYY-YYY-YY'
api_prefix='ZZZZZZZZZ'
response = identity.get_id(AccountId=account_id, IdentityPoolId=identity_pool_id)
identity_id = response['IdentityId']
print ("Identity ID: %s"%identity_id)
resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
sessionToken = resp['Credentials']['SessionToken']
expiration = resp['Credentials']['Expiration']
print ("\nSecret Key: %s"%(secretKey))
print ("\nAccess Key %s"%(accessKey))
print ("\nSession Token: %s"%(sessionToken))
print ("\nExpiration: %s"%(expiration))
method = 'GET'
headers = {}
body = ''
service = 'execute-api'
url = 'https://%s.execute-api.us-east-1.amazonaws.com/dev/helloworld' % api_prefix
region = 'us-east-1'
auth = AWS4Auth(accessKey, secretKey, region, service, session_token=sessionToken)
response = requests.request(method, url, auth=auth, data=body, headers=headers)
print(response.text)
Next code is working really well.
Hope to help:
from pprint import pprint
import requests
from pycognito import Cognito
USER_POOL_ID = 'eu-central-1_XXXXXXXXXXX'
CLIENT_ID = 'XXXXXXXXXXXX'
CLIENT_SECRET = 'XXXXXXXXXXX'
u = Cognito(USER_POOL_ID,CLIENT_ID, client_secret=CLIENT_SECRET, username='cognito user name')
u.authenticate('cognito user password')
id_token = u.id_token
headers = {'Authorization': 'Bearer ' + id_token}
api_url = 'https://XXXXXXXXXXX.execute-api.eu-central-1.amazonaws.com/stage/XXXXXXXXXXX'
r = requests.get(api_url, headers=headers)
pprint(dict(r.headers))
print(r.status_code)
print(r.text)
Here is an example from our public docs: http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html
Cognito creds are no different than any other temporary creds, and the signing process is also the same. If you want to move back to Python the example above should be good, or I would guess that there are third-party libraries out there to do the signature for you.
identity_pool_id how to get
If you have not federated pool which could give you "identity_pool_id" ,
execution code below will give you identity_pool_id
import boto3
boto3.setup_default_session(
aws_access_key_id='AKIAJ7TBC72BPWNEWIDQ',
aws_secret_access_key='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',
region_name='ap-southeast-2')
client = boto3.client('cognito-identity')
response = client.list_identity_pools(MaxResults=3,)
print("IdentityPoolId-- ", response)

OAuth generates expired bearer token

I've been following the guide for Twitter's 3-legged oauth setup:
https://dev.twitter.com/docs/auth/implementing-sign-twitter
Step 1: Obtaining a request token
For their authentication, step 1 requires making a post request containing the base64 encoded public and secret key.
key = "CONSUMER_KEY"
secret = "CONSUMER_SECRET"
auth = base64.encodestring("%s:%s" % (key, secret)).replace("\n", "")
data = {}
data["grant_type"] = "client_credentials"
headers = {}
headers["Authorization"] = "Basic " + auth
headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
headers["Accept-Encoding"] = "gzip"
response = requests.post("https://api.twitter.com/oauth2/token",
headers=headers, data=data)
This first request returns a valid response code 200 along with an access token. The response looks like this:
{u'access_token': u'AAAAAAAAAAAAAAAAAAAAAHHHHH... ...vncbi', u'token_type': u'bearer'}
Step 2: Redirecting the user
This is where the problem is occurring. According to the docs, the user then just needs to be redirected to the authorization url formatted like this:
https://api.twitter.com/oauth/authenticate?oauth_token=AAAAAAAAAAAAAAAAAAAAAHHHHH... ...vncbi
However when I get to this page I get an error message:
Is there something I missed? The access_token is being generated without an issue. I'm not sure if this message is showing up because I set something up incorrectly earlier in the process. I'm also not sure how to check if the oauth token has expired.
Actually, you have been following https://dev.twitter.com/docs/api/1.1/post/oauth2/token which is quite different, e.g. only used for public resources and not private like status updates. For the three step one checkout https://gist.github.com/ib-lundgren/4487236 or better yet http://twython.readthedocs.org/en/latest/
If you only want to access public resources like user timelines you can do so via the code below.
# OBS: If you want to look at per user details and make status updates
# you want the OAuth1 version. This is only for publicly available
# resources such as user timelines.
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
# Credentials you get from registering a new application
client_id = '<the id you get from github>'
client_secret = '<the secret you get from github>'
# TODO remove
client_id = 'VVq5UniipB5nXFAqtTA'
client_secret = 'PlaHnaSDbeY4eYkv8XiqxS1nzGWyKoq5WYSNjdeaw'
client_id = 'I1Xi7fOeYnA9jabyvGUaZxY20'
client_secret = 'k5PZpINooRpjAfQccGwLUr2ZMEtRJtoX8cKaooHjKewWupxRBG'
token_url = 'https://api.twitter.com/oauth2/token'
client = BackendApplicationClient(client_id)
twitter = OAuth2Session(client_id, client=client)
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
twitter.fetch_token(token_url, headers=headers, auth=(client_id, client_secret))
# Only public resources available to this application-only clients.
r = twitter.get('https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi')
print r.content
Make sure you use the github version of the libraries
pip install git+https://github.com/idan/oauthlib.git
pip install git+https://github.com/requests/requests-oauthlib.git

“Incorrect Signature” Python Twitter

I have the following code:
import urlparse
import oauth2 as oauth
PROXY_DOMAIN = "twitter1-ewizardii.apigee.com"
consumer_key = '...'
consumer_secret = '...'
consumer = oauth.Consumer(consumer_key, consumer_secret)
oauth_token = '...'
oauth_token_secret = '...'
token = oauth.Token(oauth_token, oauth_token_secret)
client = oauth.Client(consumer, token)
request_token_url = "https://twitter1-ewizardii.apigee.com/1/account/rate_limit_status.json"
resp, content = client.request(request_token_url, "GET", PROXY_DOMAIN)
print resp
print content
However I continue to get the error "error":"Incorrect signature" this was working earlier, and I tried out solutions people have suggested online, generated new credentials etc, but it doesn't seem to work anymore after working for a week like this.
Thanks,
Although I have switched to tweepy for anyone who finds this question this may be of use to you:
http://dev.twitter.com/pages/libraries
It could have been a glitch on the day I was testing as I didn't go back to trying out the oauth-python module since tweepy has been working for me. But that link list all the possible libraries available and is a valuable resource if such a problem arises again.

Categories