Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rushikb/8658321 to your computer and use it in GitHub Desktop.
Save rushikb/8658321 to your computer and use it in GitHub Desktop.
from collections import Counter # To count stuff for us
import datetime # Because datetime printing is hard
import facebook # FB API wrapper ("pip install facebook-sdk")
import time # Get current time
import subprocess # Used to send notifications on mac
import sys # Get system info
__author__ = 'Henri Sweers'
# For printing pretty colors in terminal
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
# If you're on mac, install terminal-notifier ("brew install terminal-notifier")
# to get nifty notifications when it's done
def notify_mac():
if sys.platform == "darwin":
try:
subprocess.call(
["terminal-notifier", "-message", "Done", "-title", "FB_Bot",
"-sound", "default"])
except OSError:
print "If you have terminal-notifier, this would be a notification"
def log(message, *colorargs):
if len(colorargs) > 0:
print colorargs[0] + message + color.END
else:
print message
# Method for counting various total likes in a group
def count_group_likes():
# Access token can be obtained by doing the following:
# - Log into facebook
# - Go to this url: https://developers.facebook.com/tools/explorer
fb_API_access_token = "token_goes_here"
# Only necessary if you want to get an extended access token
# You'll have to make a facebook app and generate a token with it
# You'll also need to get the following two values from it
fb_app_id = "id_goes_here"
fb_secret_key = "key_goes_here"
# Counter object to do the counting for us
total_likes_counter = Counter()
top_liked_posts_counter = Counter()
top_liked_comments_counter = Counter()
group_id = "id_goes_here" # Unique ID of the group to search.
# Max number of posts to retrieve. Note this errors if it's too high
num_of_posts = "1000"
num_of_items_to_return = 10 # Return the top ____ most liked ____
# Query strings for FQL
posts_query = \
"SELECT post_id, like_info, actor_id, created_time FROM stream" + \
" WHERE source_id=" + group_id + " LIMIT " + num_of_posts
comments_query = "SELECT fromid, likes, id FROM comment WHERE post_id="
person_query = "SELECT first_name, last_name FROM user WHERE uid="
# Authorize our API wrapper
graph = facebook.GraphAPI(fb_API_access_token)
# Code to programatically extend key
if extend_key:
result = graph.extend_access_token(fb_app_id, fb_secret_key)
new_token = result['access_token']
new_time = int(result['expires']) + time.time()
# This will print out new extended token and new expiration date
# Copy them and replace your token above with this one
print 'New token: ' + new_token
print 'New expiration date: ' + datetime.datetime.fromtimestamp(
new_time).strftime('%Y-%m-%d %H:%M:%S')
log('Getting group posts')
# Get group posts
try:
group_posts = graph.fql(query=posts_query)
except facebook.GraphAPIError:
# 99% of the time this is just an expired API access token
sys.exit("API key is probably invalid")
log(str(len(group_posts)) + " posts")
log('Parsing comments')
oldest_time = time.time()
# Iterate over posts
for post in group_posts:
# Check oldest time
if post['created_time'] < oldest_time:
oldest_time = post['created_time']
# Add post's like count to that user in our total_likes_counter
total_likes_counter[post['actor_id']] += post[
'like_info']['like_count']
# Add to top like posts counter
top_liked_posts_counter[post['post_id']] = post['like_info'][
'like_count']
# Get likes on post
comments = graph.fql(
comments_query + "\"" + str(post['post_id']) + "\" LIMIT 150")
# Iterate over comments
for c in comments:
# add their like counts to their respective users
# in our total_likes_counter
total_likes_counter[c['fromid']] += c['likes']
# add like count to top_comments_likes_counter
top_liked_comments_counter[c['id']] = c['likes']
log('Done, time to pretty print')
log('Oldest post was from ' + datetime.datetime.fromtimestamp(
oldest_time).strftime('%Y-%m-%d %H:%M:%S'))
# Returns key-value list of most liked people
most_common_people = total_likes_counter.most_common(
num_of_items_to_return)
top_posts = top_liked_posts_counter.most_common(num_of_items_to_return)
top_comments = top_liked_comments_counter.most_common(
num_of_items_to_return)
# Iterate over top people and retrieve names from their ID's
log('\nTop people!', color.BOLD)
for x in most_common_people:
person = graph.fql(person_query + str(x[0]))[0]
print person['first_name'] + " " + person['last_name'] + " - " + str(
x[1])
# Iterate over top posts and get info
log('\nTop posts!', color.BOLD)
for x in top_posts:
post = graph.get_object(str(x[0]))
print str(x[1]) + " - " + post['from']['name'] + " - " + post['type']
if 'message' in post:
m = str(post['message']).replace('\n', ' ')
if len(m) > 70:
print '--' + m[0:70] + "..."
else:
print '--' + m
print '-- http://www.facebook.com/' + post['id']
# Iterate over top comments and get info
log('\nTop comments!', color.BOLD)
for x in top_comments:
comment = graph.get_object(str(x[0]))
print str(x[1]) + " - " + comment['from']['name']
if 'message' in comment:
c = str(comment['message']).replace('\n', ' ')
if len(c) > 70:
print '--' + c[0:70] + "..."
else:
print '--' + c
print '-- http://www.facebook.com/' + comment['id']
args = sys.argv
extend_key = False # boolean for if we want to extend token access
if len(args) > 1:
if "--extend" in args: # Pass in flag
extend_key = True
else:
log('No args specified')
count_group_likes()
notify_mac()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment