I've been following the instructions in the tweepy documentation:
https://docs.tweepy.org/en/stable/authentication.html
When I pass in an oauth_verifier to get a user's access tokens, it throws out:
tweepy.errors.TweepyException: 'oauth_token'
#views.route("/")
def home():
with open("oauth1_user_handler", "rb") as userHandler:
oauth1_user_handler=pickle.load(userHandler)
oauth_verifier = request.args.get("oauth_verifier")
user_access_token, user_access_token_secret = oauth1_user_handler.get_access_token(
oauth_verifier
)
return "<p>user_access_token, user_access_token_secret</p>."
I've tried multiple variations of passing in the oauth_verifier, the oauth_token, and combinations of the 2, exactly as they are in the url parameters, but that hasn't worked either.
Any help would be greatly appreciated.
Since you're reinitializing OAuth1UserHandler and not using the same instance, you need to set the request token and secret before using the verifier to get the access token and secret.
There's a section on this in the documentation you linked: https://tweepy.readthedocs.io/en/v4.10.1/authentication.html#legged-oauth
Related
I have tried multiple approaches to this. Tried first getting the user without any user id - this returns me just my user, then tried getting user with other id's and it also retrieves data correctly. However, I can't seem to be able to set user attribute 'deleted'. i'm using this python approach.
slack_client.api_call('users.profile.set', deleted=True, user='U36D86MNK')
However I get the error message of:
{u'error': u'invalid_user', u'ok': False}
Maybe someone has already done this? It says in documentation that it's a paid service mentioning this message under a user property:
This argument may only be specified by team admins on paid teams.
But shouldn't it give me a 'paid service' response in that case then?
The users.profile.set apparently does not work for for setting each and every property of a user.
To set the deleted property there is another API method called users.admin.setInactive. Its an undocumented method and it will only work on paid teams.
Note: This requires a legacy token and doesn't work with App tokens - these are only available on paid plans and new legacy tokens can't be created anymore
in python you can do the following:
import requests
def del_slack_user(user_id): # the user_id can be found under get_slack_users()
key = 'TOKEN KEY' #replace token key with your actual token key
payload = {'token': key, 'user': user_id}
response = requests.delete('https://slack.com/api/users.admin.setInactive', params=payload)
print(response.content)
def get_slack_users():
url = 'https://slack.com/api/users.list?token=ACCESSTOKEN&pretty=1'
response = requests.get(url=url)
response_data = response.json() # turns the query into a json object to search through`
You can use Slack's SCIM API to enable and disable a user. Note that, as with the undocumented API endpoint mentioned in other answers this requires a Plus/Enterprise account.
I'm using the python-twitter API
and whatever I pass to the below code as user, still returns my timeline and not the required user's. Is there something I'm doing wrong?
import twitter
api = twitter.Api(consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
access_token_key=ACCESS_KEY,
access_token_secret=ACCESS_SECRET)
user = "#stackfeed"
statuses = api.GetUserTimeline(user)
print [s.text for s in statuses]
When I do not pass the required fields into twitter.Api, it gives me an authentication error.
You should use screen_name keyword argument, e.g.:
statuses = api.GetUserTimeline(screen_name="#gvanrossum")
I'm making a web app in python using the Flask framework to request the access token from Facebook using the SDK supplied in their site.
The access token is returned and it is correctly set in the GraphAPI object. However, it is returning the following error:
GraphAPIError: Invalid OAuth access token.
If I query the graph API from my local python environment using the same access token, it works just fine. The problem seems to be when executing in the webserver.
See code snippet below:
#app.route('/facebook')
def fb():
if 'token' in session:
graph = facebook.GraphAPI(session['token'])
return graph.get_object("me")
#app.route('/facebook/login')
def fblogin():
code = request.args.get('code','')
if(code == ""):
args = dict(client_id=app_id, redirect_uri=request.base_url)
#args = dict(client_id=app_id, redirect_uri=request.url_root + 'facebook')
return redirect(
"https://graph.facebook.com/oauth/authorize?" +
urllib.urlencode(args))
else:
token = facebook.get_access_token_from_code(code, request.base_url, app_id, app_secret)
session['token'] = [token.itervalues().next()]
return redirect (request.url_root + 'facebook')
Has anyone faced this before and/or can provide some insights?
Ok, 2 issues that I have managed to correct in this code and get it working:
1) The following line of code makes a list, that why the GraphAPI object is not able to identify a valid access token:
session['token'] = [token.itervalues().next()]
2) The following line of code gives an error stating that 'dict' is not callable. This is because the returned variable is a dictionary and, in order to be returned as a view, one must first transform it into a string:
return graph.get_object("me")
I am using oAuth2WebServerFlow to get an oAuth access token and then retrieve a list of a user's contacts. I'm using web2py as the web framework.
flow = oauth2client.client.OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope='https://www.google.com/m8/feeds',
user_agent=USER_AGENT)
callback = 'http://127.0.0.1:8000/Test/searcher/oauth2callback'
authorise_url = flow.step1_get_authorize_url(callback)
session.flow = pickle.dumps(flow)
redirect(authorise_url)
With the redirect then being handled as follows
flow = pickle.loads(session.flow)
credentials = flow.step2_exchange(request.vars)
My question is how to change the OAuth2Credentials object returned above into an OAuth2AccessToken object, that I can then use to authorise a request to the contacts library with something like:
gc = gdata.contacts.client.ContactsClient(source="")
token.authorize(gc)
gc.GetContacts
I've tried various methods with no success, normally getting an oAuth2AccessTokenError message of "Invalid Grant". I'm thinking something like this may work but also think there must be a simpler way!
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope='https://www.google.com/m8/feeds', user_agent=USER_AGENT)
token.redirect_uri = 'http://127.0.0.1:8000/Test/searcher/oauth2callback'
token.get_access_token(<<code to pass the access_token out of the Credentials object??>>)
Can anyone help with this?
I managed to get this working. It was pretty straightforward actually, I just stopped using the OAuth2WebServerFlow, which didn't seem to be adding much value anyway. So the new code looks like this:
token = gdata.gauth.OAuth2Token(client_id, client_secret, scope, ua)
session.token = pickle.dumps(token)
redirect(token.generate_authorize_url(redirect_uri='http://127.0.0.1:8000/Test/default/oauth2callback'))
Followed by
def oauth2callback():
token = pickle.loads(session.token)
token.redirect_uri='http://127.0.0.1:8000/Test/default/oauth2callback'
token.get_access_token(request.vars.code)
gc = gdata.contacts.client.ContactsClient(source='')
gc = token.authorize(gc)
feed = gc.GetContacts()
Hope this is helpful to someoone!
Assuming you have code for newer OAuth2.0 APIs setup correctly, you can get this working by creating a Token class that modifies headers that converts Credentials -> Token class.
OAUTH_LABEL='OAuth '
#Transforms OAuth2 credentials to OAuth2 token.
class OAuthCred2Token(object):
def __init__(self, token_string):
self.token_string = token_string
def modify_request(self, http_request):
http_request.headers['Authorization'] = '%s%s' % (OAUTH_LABEL,
self.token_string)
ModifyRequest = modify_request
You can test it as follows:
gc = gdata.contacts.client.ContactsClient(source='')
token = OAuthCred2Token(creds.access_token)
gc.auth_token = token
print gc.GetContacts()
Note that this code will not handle token refreshes, which code using credentials handles.
In my own application, it is acceptable to make a simple call using a service to refresh the credentials before making a call to get contacts.
Here is sample code that I'm working with.
def index(request):
flow = OAuth2WebServerFlow(
client_id='xyz.apps.googleusercontent.com',
client_secret='xyz',
scope='https://www.googleapis.com/auth/plus.me',
user_agent='sample/1.0')
callback = 'http://%s/oauth2callback' % request.META[ 'HTTP_HOST' ]
authorize_url = flow.step1_get_authorize_url(callback)
return HttpResponse(flow)
For some reason 'flow' is always set to " " or empty instead of a request token. I have searched for days on this issue.
Can anyone tell me why I can't get a request token from google using this method?
fyi: I know that I should be redirecting the user to the authorize url, but I want to see if flow is set before I do since Google will provide the authorize url even if a request token wasn't returned.
Before you can use OAuth 2.0, you must register your application using
the Google APIs Console. After you've registered, go to the API Access
tab and copy the "Client ID" and "Client secret" values, which you'll
need later.
http://code.google.com/p/google-api-python-client/wiki/OAuth2#Registering
If this answer actually helps with your problem then I must bid an R.I.P. to S.O.