PRAW: Authorizing with OAuth prevents me from getting submissions/comments - python

If I use OAuth, I am unable to get new submissions or comments from a subreddit.
My Oauth code looks like this:
import praw
import webbrowser
r = praw.Reddit(user_agent)
r.set_oauth_app_info(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
authURL = r.get_authorize_url("FUZZYPICKLES", "identity submit", True)
webbrowser.open(authURL)
authCode = input("Enter the code: ")
accInfo = r.get_access_information(authCode)
After that I can try to get submissions
submission = r.get_subreddit("test").get_new()
or comments
comments = r.get_comments("test")
but if I use either value, the program crashes with the error:
raise OAuthInsufficientScope('insufficient_scope', response.url)
praw.errors.OAuthInsufficientScope: insufficient_scope on url https://oauth.reddit.com/r/test/comments/.json
If I don't use OAuth, either by using login() or by just not authorizing, I have no such issues. I am using Python 3.4. What am I doing wrong?

I found the solution myself. To read posts, you need "read" in your list of requested scopes. So, "identity submit" should be "identity read submit".

Related

LinkedIn Job Search REST API Issue(s)

I see there has been questions similar to this but the responses to them explains my asking a similar question here. I am wanting to utilize LinkedIn's REST API for my personal job hunt, specifically utilizing the job search API capabilities.
My problem comes in with retrieving an access token and autorisation to actually use the app. I have tried the below code - the first cell is to retrieve autorisation and the second is to retrieve an access token:
from linkedin import linkedin
APPLICATON_KEY = 'XXXXXX'
APPLICATON_SECRET = 'XXXXX'
RETURN_URL = 'http://localhost:8000'
authentication = linkedin.LinkedInAuthentication(APPLICATON_KEY, APPLICATON_SECRET, RETURN_URL,
linkedin.PERMISSIONS.enums.values())
print (authentication.authorization_url) #open this url on your browser
Access token:
authentication = linkedin.LinkedInAuthentication(
APPLICATON_KEY,
APPLICATON_SECRET,
RETURN_URL,
linkedin.PERMISSIONS.enums.values()
)
authentication.authorization_code = '#############################################'
result = authentication.get_access_token()
print ("Access Token:", result.access_token)
print ("Expires in (seconds):", result.expires_in)
When I attempt to retreieve authorisation (required for access token) the following error occurs:
File "/usr/local/lib/python3.6/dist-packages/linkedin/linkedin.py", line 294
except (requests.ConnectionError, requests.HTTPError), error:
^
SyntaxError: invalid syntax
It's an obvious syntax error, however am ignorant to what it is exactly - I have a feeling it might be my localhost
That error points to the comma separating the exception classes from the variable name.
A comma there is Python 2.x syntax, so that means the linkedin library you're using is not compatible with Python 3.
If you're using this library, you can see it's not been updated in 5 years. This (PyPI) seems like a slightly fresher fork.

Need a Python script for Slack to deactivate a user [duplicate]

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.

PRAW 4: 400 ERROR when trying to download a users comments

I'm trying to create a Reddit bot that when a username is mentioned it gets the users comments and sends it to an API to analyze them and return a request but when I try to download them it gives me
prawcore.exceptions.BadRequest: received 400 HTTP response
This is the code:
if text.startswith('/u/PersonalityInsights'):
print "Mentioned!"
print comment
username = text.split()[1]
print username
if username.startswith('/u/'):
validusername = username[3:]
print validusername
global redditor
redditor = bot.redditor(username)
else:
global redditor
redditor = bot.redditor(username)
file = codecs.open('userscommentsreddit.txt', 'w+', encoding='utf8')
for comment in redditor.get_comments(limit=None):
print comment.body
The method I'm using is: get_comments(limit=None)
in PRAW 3 it worked but here it fails. I tried lowercasing the username but it failed with the same error. The account I'm trying to download the comments is mine: /u/UnknownDeveloper
I tried lowering the username but the same error, Replaced the for loop with this: for comment in redditor.comments.new(limit=None): and still an error 400
If you are interested in the full code here is a link to a GitHub gist.
Version of Praw 4.1.0
I know this is almost a year old, and chances are you have moved on or solved this already, but I really like doing research and answering SO questions so here we go!:
Here is what the 400 error means, so we are on the same page:
The HTTP 400 Bad Request response status code indicates that the server could not understand the request due to invalid syntax.source
Now into the actual answer:
The method I'm using is: get_comments(limit=None)
in PRAW 3 it worked but here it fails. I tried lowercasing the username but it failed with the same error.
The get_comments() call was depreciated, and I assume you figured this out based on the fact you also tried the comments.new() function.
But that doesn't matter at all, because the real issue is in redditor = bot.redditor(username). That call takes the raw username (without the /u/) So the solution to your code would be to remove the /u/ from the username variable before calling redditor = bot.redditor(username), or you could make things simpler by using regex to identify a valid username but only return the part after the /u/.

Python - Facebook API - Need a working example

Ok, so i've googled around, i've found threads here on stackoverflow and i've checked the official Facebook wiki and.. and what not..
I now hope that one of you guys sits on a Facebook API sample code for Python.
This is what i've got so far and all i get is "Invalid Signature" via PyFacebook which appears to be a dead project:
from facebook import Facebook
api_key = '123456789______'
secret = '<proper secret key>'
OTK = 'XXXXX' # <-- You get this from: https://www.facebook.com/code_gen.php?v=1.0&api_key=123456789______
long_term_key = None
fb = Facebook(api_key, secret)
def generate_session_from_onetime_code(fb, code):
fb.auth_token = code
return fb.auth.getSession()
if not long_term_key:
long_term_key = generate_session_from_onetime_code(fb, OTK)['session_key']
print 'Replace None with this in the .py file for long_term_key:'
print long_term_key
fb.session_key = long_term_key
fb.uid = 000000001 # <-- Your user-id
fb.signature = api_key # <-- This doesn't work at all, MD5 of what?
#fb.validate_signature(fb) # <-- doesn't work either, prob need to pass MD5 handle?
print fb.friends.get() # <-- Generates "Invalid Signature"
"all" i want, is to retrieve my friends list for now,
if there's a better API point me in the right direction but Facebook has officially declared their own Python SDK dead and pyfacebook is almost working for me but not quite..
So, please help.
The unofficial fork of the python sdk is still working fine for me.
To retrieve your friends, generate an access token here:
https://developers.facebook.com/tools/access_token/
Limitations:
A user access token with user_friends permission is required to view
the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
Code
import facebook
token = 'your token'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
friend_list = [friend['name'] for friend in friends['data']]
print friend_list

What is a post_form_id? (using python urllib2)

I'm interested in writing a python script to log into Facebook and then request some data (mainly checking the inbox). There are few nice examples out there on how to do this. One interesting script i found over here and there is some nice example on stackoverflow itself.
Now i could just copy-paste some of the code i need and get to do what i want, but that wouldn't be a good way to learn. So i am trying to understand what i am actually coding and can't understand some elements of the script in the first example, namely: what is a post_form_id?
Here is the section of the code which refers to "post_form_id" (line 56-72):
# Initialize the cookies and get the post_form_data
print 'Initializing..'
res = browser.open('http://m.facebook.com/index.php')
mxt = re.search('name="post_form_id" value="(\w+)"', res.read())
pfi = mxt.group(1)
print 'Using PFI: %s' % pfi
res.close()
# Initialize the POST data
data = urllib.urlencode({
'lsd' : '',
'post_form_id' : pfi,
'charset_test' : urllib.unquote_plus('%E2%82%AC%2C%C2%B4%2C%E2%82%AC%2C%C2%B4%2C%E6%B0%B4%2C%D0%94%2C%D0%84'),
'email' : user,
'pass' : passw,
'login' : 'Login'
})
Would you be so kind to tell me what a post_form_id is? And accessorily: would you know what the lsd key/value stands for?
Thanks.
I don't understand why you are trying to "hack" this ...
There is an official api from facebook to read the mailbox of a user, and you need to ask the "read_mailbox" permission for this.
So I advice you to check my post here on how to use facebook and python/django together, and how to login to facebook from python.
And then I would recommend you to read the facebook doc about the messages/inbox.
Basically you need an access_token then you can do http://graph.facebook.com/me/inbox/?access_token=XXX
You can also ask for the "offline_access" permission so you'll need only to get an access token once and you will be able to use it "forever"
And the you can do http://graph.facebook.com/MESSAGE_ID?access_token=XXX to get the details about a particular message.
Or using the api I use in the other thread :
f = Facebook()
res = f.get_object("me/inbox")
...
Feel free to comment if you have any question about this ?

Categories