I am trying to follow some user in a list with python-twitter library. But I am taking "You've already requested to follow username" error for some users. That means I have sent a following request to that user so I cant do that again. So how can I control users, I sent following request. Or is there other way to control it.
for userID in UserIDs:
api.CreateFriendship(userID)
EDIT: I am summerizing: You can follow some users when you want. But some ones don't let it. Firstly you must send friendship request, then he/she might accept it or not. What I want to learn is, how I can list requested users.
You have two options here:
call GetFriends before the loop:
users = [u.id for u in api.GetFriends()]
for userID in UserIDs:
if userID not in users:
api.CreateFriendship(userID)
use try/except:
for userID in UserIDs:
try:
api.CreateFriendship(userID)
except TwitterError:
continue
Hope that helps.
It has been close to three years since this question was asked but responding for reference as it shows up as the top hit when you Google the issue.
As of this post, this is still the case with python-twitter (i.e. there is no direct way with python-twitter to identify pending friendship or follower requests).
That said, one can extend the API class to achieve it. An example is available here: https://github.com/itemir/twitter_cli
Relevant snippet:
class ExtendedApi(twitter.Api):
'''
Current version of python-twitter does not support retrieving pending
Friends and Followers. This extension adds support for those.
'''
def GetPendingFriendIDs(self):
url = '%s/friendships/outgoing.json' % self.base_url
resp = self._RequestUrl(url, 'GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data.get('ids',[])
def GetPendingFollowerIDs(self):
url = '%s/friendships/incoming.json' % self.base_url
resp = self._RequestUrl(url, 'GET')
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
return data.get('ids',[])
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 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/.
I'm trying to read facebook conversations of a page using a python script. With this code
import facebook
at = "page access token"
pid = "page id"
api = facebook.GraphAPI( at )
p = api.get_object( 'me/conversations')
print p
I get a dictionary containing the following
{'paging': {'next': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&until=1454344040&__paging_token=<my_access_token>', 'previous': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&since=1454344040&__paging_token=<my_access_token>'}, 'data': [{'link': '/Python-1745249635693902/manager/messages/?mercurythreadid=user%3A100000386799941&threadid=mid.1454344039847%3A2e3ac25e0302042916&folder=inbox', 'id': 't_mid.1454344039847:2e3ac25e0302042916', 'updated_time': '2016-02-01T16:27:20+0000'}]}
What are those fields? How can I get the text of the message?
Edit: I tried asking for the "messages" field by adding
msg = api.get_object( p['data'][0]['id']+'/messages')
print msg
but it just returns the same fields. I've searched in the API docs for a while, but I didn't find anything helpful. Is it even possible to read the message content of a facebook page's conversation using python?
I managed to find the answer myself; the question was not well posed and did not match what I was exactly looking for.
I wanted to get the content of the messages of facebook conversations of a page. Following the facebook graph API documentation, this can be achieved by asking for the conversations ({page-id}/conversations), then the messages in said conversations ({conversation-id}/messages, https://developers.facebook.com/docs/graph-api/reference/v2.5/conversation/messages), and finally asking for the message itself should return a dict with all the fields, content included (/{message-id}, https://developers.facebook.com/docs/graph-api/reference/v2.5/message).
At least this is how I believed it should have been; however the last request returned only the fields 'created_time' and 'id'.
What I was really trying to ask was a way to fetch the 'message' (content) field. I was assuming the function graph.get_object() from the official python facebook sdk should have returned all the fields in any case, since it has only one documented argument (http://facebook-sdk.readthedocs.org/en/latest/api.html) - the graph path for the requested object, and adding additional field request is not allowed.
The answer I was looking for was in this other question, Request fields in Python Facebook SDK.
Apparently, it's possible to ask for specific fields ( that are not returned otherwise ) by passing an **args dict with such fields along with the path requested.
In a GET request to the Facebook graph that would be the equivalent of adding
?fields=<requested fieds>
to the object path.
This is the working code:
#!/usr/bin/env python
import facebook
at = <my access token>
pid = <my page id>
api = facebook.GraphAPI( at )
args = {'fields' : 'message'} #requested fields
conv = api.get_object( 'me/conversations')
msg = api.get_object( conv['data'][0]['id']+'/messages')
for el in msg['data']:
content = api.get_object( el['id'], **args) #adding the field request
print content
I'm trying to get all people I follow using the Instagram API. The call returns 50 users at a time and I'm paginating to store every follower. I follow 500 people but am only receiving 150 in total. What could be going wrong?
# returns a list of ids
def find_users_we_follow():
ids = []
followed_users = IGapi.user_follows(CLIENT_ID, as_generator=True)
# IG returns 50 users at a time which we have to paginate through
for page in followed_users:
for user in page[0]:
ids.append(user)
return ids
Thanks!
Sounds crazy.. but.. try something like this:
def find_users_we_follow():
ids = set()
if len(ids) != 500:
followed_users = IGapi.user_follows(CLIENT_ID, as_generator=True)
for page in followed_users:
for user in page[0]:
ids.add(user)
else:
return ids
ok why?
In my experience, their is like no logic to how instagram returns your followers with this call. Keep making the call until you get 500 unique ids.
You can just use the Instagram User endpoint to get number of followers and follows.
GET/users/user-id
Get basic information about a user. To get information about the owner of the access token, you can use self instead of the user-id.
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 ?