FB custom API: Accepting friend request on Facebook

This is third post in series of web scraping FB for creation of own API. Today I will show how to accept friend request. Previously in entry Your own Facebook API – logging in I showed how to log into your Facebook account.

Getting list of friend request is quite simple using low-end Facebook interface. You just need to go to https://mbasic.facebook.com/friends/center/requests/ and parse every “a” tag which “href” attribute starts with “/a/notifications.php?confirm=”. If you care about name of user who sent you friend request, you’d like to remember last parsed “a” tag with “href” attribute starting with “/friends/hovercard/mbasic/” and read text value from it. Of course, if your account has many friend requsts, not all of them will be available under single page. To get more of them you’d need to find and parse “a” tag which “href” attribute starts with “/friends/center/requests/”. But it is out of this post’s scope.

We need to add class field containing requests url and method which will return friend requests. Whole class should look following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  class Facebook:
    fbUrl = "https://mbasic.facebook.com"
    loggedIn = False
    receivedFriendRequestsUrl = "https://mbasic.facebook.com/friends/center/requests/"
    headers = {"User-Agent": "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0",
               "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
               "Accept - Language": "en-US,en;q=0.5",
               "Accept - Encoding": "gzip, deflate, br",
               "Referer": "https://mbasic.facebook.com/"
    }
 
    def login(self, login, password):
        response = requests.get(self.fbUrl, headers = self.headers)
        parser = LoginParser()
        parser.feed(response.text)
        form = parser.data
        form["email"] = login
        form["pass"] = password
        response = requests.post(parser.action, form, cookies = response.cookies, headers = self.headers, allow_redirects = False)
        self.cookies = response.cookies
 
    def ensureLoggedIn(self):
        if self.cookies is None:
            raise RuntimeError("Not logged in")
 
    def getFriendRequests(self):
        self.ensureLoggedIn()
        parser = FriendConfirmParser()
        response = requests.get(self.receivedFriendRequestsUrl, cookies = self.cookies)
        parser.feed(response.text)
        return [FriendRequest(self.cookies, username, path) for username, path in parser.requests.items()]

As you can see, I created new classes: FriendRequest and FriendConfirmParser. First is an object representing friend request, containing user name and approval link. The second one is another parser, to find information we’re looking for. They should look like that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  class FriendRequest:
    def __init__(self, cookies, username, path):
        self.url = Facebook.fbUrl + path
        self.cookies = cookies
        self.username = username
 
    def accept(self):
        print self.url
        print self.cookies
        requests.get(self.url, headers=Facebook.headers, cookies=self.cookies)
 
  class FriendConfirmParser(HTMLParser):
    requests = {}
    insideHovercardTag = False
    lastHovercardTagValue = None
 
    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = {k[0]: k[1] for k in attrs}
 
            if attrs["href"].find("/a/notifications.php?confirm=") == 0:
                self.requests[self.lastHovercardTagValue] = attrs["href"]
            elif attrs["href"].find("/friends/hovercard/mbasic/") == 0:
                self.insideHovercardTag = True
 
    def handle_data(self, data):
        if self.insideHovercardTag:
            self.lastHovercardTagValue = data
 
    def handle_endtag(self, tag):
        if self.insideHovercardTag:
            self.insideHovercardTag = False

Having above code we can easily get couple first friend requests, display usernames or accept their to our friend list, like on example below.

1
2
3
4
5
6
   fb = Facebok()
   fb.login("email", "pass")
   for request in fb.getFriendRequests():
      print request.username
      if request.username == "Joe Doe":
         request.accept()

Leave a Reply

Your email address will not be published. Required fields are marked *