I am extremely new to python , scripting and APIs, well I am just learning. I came across a very cool code which uses facebook api to reply for birthday wishes.
I will add my questions, I will number it so that it will be easier for someone else later too. I hope this question will clear lots of newbies doubts.
1) Talking about APIs, in what format are the usually in? is it a library file which we need to dowload and later import? for instance, twitter API, we need to import twitter ?
Here is the code :
import requests
import json
AFTER = 1353233754
TOKEN = ' <insert token here> '
def get_posts():
"""Returns dictionary of id, first names of people who posted on my wall
between start and end time"""
query = ("SELECT post_id, actor_id, message FROM stream WHERE "
"filter_key = 'others' AND source_id = me() AND "
"created_time > 1353233754 LIMIT 200")
payload = {'q': query, 'access_token': TOKEN}
r = requests.get('https://graph.facebook.com/fql', params=payload)
result = json.loads(r.text)
return result['data']
def commentall(wallposts):
"""Comments thank you on all posts"""
#TODO convert to batch request later
for wallpost in wallposts:
r = requests.get('https://graph.facebook.com/%s' %
wallpost['actor_id'])
url = 'https://graph.facebook.com/%s/comments' % wallpost['post_id']
user = json.loads(r.text)
message = 'Thanks %s :)' % user['first_name']
payload = {'access_token': TOKEN, 'message': message}
s = requests.post(url, data=payload)
print "Wall post %s done" % wallpost['post_id']
if __name__ == '__main__':
commentall(get_posts())`
Questions:
importing json--> why is json imported here? to give a structured reply?
What is the 'AFTER' and the empty variable 'TOKEN' here?
what is the variable 'query' and 'payload' inside get_post() function?
Precisely explain almost what each methods and functions do.
I know I am extremely naive, but this could be a good start. A little hint, I can carry on.
If not going to explain the code, which is pretty boring, I understand, please tell me how to link to APIs after a code is written, meaning how does a script written communicate with the desired API.
This is not my code, I copied it from a source.
json is needed to access the web service and interpret the data that is sent via HTTP.
The 'AFTER' variable is supposed to get used to assume all posts after this certain timestamp are birthday wishes.
To make the program work, you need a token which you can obtain from Graph API Explorer with the appropriate permissions.
Related
im working in a personal project that needs new email in the start, and i want create a new email with python also i don't want run a complicate smtp server(I don't know much about that yet) i want do something like temp mail with api, i'd tried temp mail api but i got error i do something like this
import requests
url = "privatix-temp-mail-v1.p.rapidapi.com/request/mail/id/md5 of my temp mail"
req = request.get(url)
print(req)
but i got 401 status code that says your api key is invalid
then i go to rapidapi website and see examples there was a header for req so i put that to my code that was like:
import requests
url = "https://privatix-temp-mail-v1.p.rapidapi.com/request/mail/id/md5"
headers = {
'x-rapidapi-host': "privatix-temp-mail-v1.p.rapidapi.com",
'x-rapidapi-key': "that was a key"
}
req = request.get(url, headers=headers)
then i got this
{"message":"You are not subscribed to this API."}
now i get confused and i don't know what is problem if you know temp mail api or something liks this service or any suggest pls help me
In order to use any API from RapidAPI Hub, you need to subscribe to that particular API. It's pretty simple.
Go to the Pricing Page of this API and choose a plan according to your need. Click on the subscribe button and you will be good to go. However, the Basic plan is free but a soft limit is associated with it so it may ask for your card details.
I'm trying to parse with Graph API job titles(but problem exist for other methods) with method type=adworkposition.
def getJobs(job):
URL = 'https://graph.facebook.com/search?type=adworkposition&q=' + job + '&limit=10000&locale=ru_RU&access_token='+TOKEN
response = requests.get(URL)
response = json.loads(response.text)['data']
df = pd.DataFrame.from_dict(response)
return df
When job = 'developer' I expect to see at least a list of Java Developer, Game Developer, .NET developer, because I know for sure that they exist cause I see them in Facebook Ads Manager.
And also an example from the documentation says that it works that way. But it does not and request returns only ".NET developer". What do I do wrong? Maybe there some regex which I don't know?
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'd like to start off by saying that I love this tool and the API is written in a very easy to follow way if you are familiar with Zap. The only troubles I've had is that I can't find much documentation on the python API, so I've gone off of the source code and verifying how it works against the app. I've been able to pull of scans and set contexts, but I can't seem to be able to correctly call anything from the authentication module. One of my problems, I believe, is that I'm not entirely sure the exact variables to use or their respective formats when calling the functions. below is some example code that I've scrapped together. Every use of the authentication functions below fail me. Even if someone were to look at this and tell me where to go or look to solve this problem myself, I would be very grateful.
from zapv2 import ZAPv2
context = 'new_attack'
authmethodname = 'formBasedAuthentication'
authmethodconfigparams = "".join('loginUrl=someloginpage' 'loginRequestData=username%3D%7B%25user1%25%7D%26' 'password%3D%7B%25password%25%7D')
target = 'some target but I cant put more than 2 links in this question'
apikey = 'password'
zap = ZAPv2(apikey=apikey)
print zap.context.new_context('new_attack')
print zap.context.include_in_context(context, 'https://192.168.0.1.*')
print zap.context.context(context)
#anything below here gives me 'Missing Params' an error from zap
print zap.authentication.set_logged_in_indicator(context, loggedinindicatorregex='Logged in')
print zap.authentication.set_logged_out_indicator(context, 'Sorry, the username or password you entered is incorrect')
print zap.authentication.set_authentication_method(context, authmethodname, authmethodconfigparams)
A Dev member on the project was able to answer my question so I thought I would put it here as well. Essentially the authentication functions take the contextid and userid as parameters and I was passing the context name and user name. There are a few other mistakes that I interpreted from the source code as well. Hopefully this helps someone else who's starting out with the API as well, since there is not a lot of documentation.
from github page zaproxy; username thc202 - "
from zapv2 import ZAPv2
context = 'new_attack'
authmethodname = 'formBasedAuthentication'
authmethodconfigparams = "".join('loginUrl=https://192.168.0.1/dologin.html' '&loginRequestData=username%3D%7B%25username%25%7D%26' 'password%3D%7B%25password%25%7D')
target = 'https://192.168.0.1'
apikey = 'password'
zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8119', 'https': 'http://127.0.0.1:8119'}, apikey=apikey)
contextid = zap.context.new_context(context)
print contextid
print zap.context.include_in_context(context, 'https://192.168.0.1.*')
print zap.context.context(context)
print zap.authentication.set_authentication_method(contextid, authmethodname, authmethodconfigparams)
# The indicators should be set after setting the authentication method.
print zap.authentication.set_logged_in_indicator(contextid, loggedinindicatorregex='Logged in')
print zap.authentication.set_logged_out_indicator(contextid, 'Sorry, the username or password you entered is incorrect')
userid = zap.users.new_user(contextid, 'User 1')
print userid
print zap.users.set_authentication_credentials(contextid, userid, 'username=MyUserName&password=MySecretPassword')
print zap.users.set_user_enabled(contextid, userid, True)
print zap.spider.scan_as_user(contextid, userid, target)
"
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 ?