Tuesday, October 11, 2016

Combine Facebook API with Twitter Bot

It has been a while since I last looked at Facebook Graph API. I had a small project that would benefit from crawling a Facebook group, here is what I want to do:

1. Crawl a Facebook group for feed periodically.
2. Parse out the Feeds for a particular person.
3. Tweet to me when that happens.

For #1 and #3, I have already done that before with Twython and AWS Lambda in this post. So I just need to figure out how to crawl Facebook group. Here were the steps I took:

1. Create a Facebook App ID and get App secret. This is pretty easy and self-explanatory.

2. Use the Facebook Graph API Page and Documentation to find the right URI to get the feed that you want. This was the most time consuming as Facebook changes access rights from version to version, and there are differences between App Token and User Token. What I finally found was using the User Token for version 2.2 (latest was 2.7) was what I needed.

Here is the curl example. You can get the group ID from going directly to the Facebook group and looking at the URI. The feed limit is just to speed up the response:

○ → curl -i -X GET \

>  "https://graph.facebook.com/v2.2/<facebook group ID>?fields=feed.limit(10)&access_token=<token>" 

3. The user token is only good for about an hour, you can make it a 60 day long term token. Here was the Facebook LInk, but I find this instruction to be much easier. 

4. Now that I have the feed, I just need to parse it out for message, creation time, and other fields that I wanted and fill in what I did before for Twitter bot and upload to Lambda. One thing that I did wrong was previously using update_status which spammed all of my followers, so I switched to direct_message. Here is the code: 


import requests, pprint, json, re, datetime
from twython import Twython
from twython.exceptions import TwythonError

with open('credentials.json') as f:
  credentials = json.loads(f.read())

client = Twython(credentials["consumer_key"],
                 credentials["consumer_secret"],
                 credentials["access_token_key"],
                 credentials["access_token_secret"])


url = "https://graph.facebook.com/v2.2/<group>?fields=feed.limit(50)&access_token=<long term access token>"

def lambda_handler(event, context):
    r = requests.get(url)
    for i in r.json()['feed']['data']:
        if i['from']['id'] == '<some user ID>':
            if re.search('shirt', i['message']):
                name = (i['from']['name'])
                #print(i['from']['id'])
                createdTime = (i['created_time'])
                message = (i['message'])
                print("Tweeting..")
                text = <your text>
                client.send_direct_message(screen_name="<some user>", text = text)


Thanks for reading. Happy Coding!




No comments:

Post a Comment