pageinsight.py 1.76 KB
  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
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import json
import time

class PageInsight() :

token = ""
data = {}
page_insight = {}
page_dscp = {'page_fans/lifetime': 'Lifetime_Total_Likes',
'page_impressions_unique/day': 'Daily_Total_Reach',
'page_engaged_users/day': 'Daily_Page_Engaged_Users',
'page_storytellers_by_story_type/day': 'Daily_Talking_About_This_By_Story_Type',
'page_impressions_unique/week': 'Weekly_Total_Reach',
'page_engaged_users/week': 'Weekly_Page_Engaged_Users',
'page_storytellers_by_story_type/week': 'Weekly_Talking_About_This_By_Story_Type'}

def __init__(self, token):
self.token = token.getToken()

def getPageInsight(self, page_id, item):

for i in item:
time.sleep(0.5)
url = 'https://graph.facebook.com/v2.5/%s/insights/%s?debug=all&method=get&pretty=0&suppress_http_code=1&since=%d&until=%d%s' \
% (page_id, i, int(time.time()), int(time.time()) + 12 * 60 * 60, self.token)
txt = requests.get(url).text
self.data = json.loads(txt)

try:
name = str(self.data['data'][0]['title'])
val = self.data['data'][0]['values'][0]['value']
if type(val) == type({}):
val = sum(val.values())
self.page_insight[name] = str(val)
except:
self.page_insight[self.page_dscp[i].replace("_", " ")] = 0
return self.page_insight

def getPageInsightByKey(self, key):

key_x = key.replace("_", " ")

try:
result = self.page_insight[key_x]
except:
result = 0
return result