pageinsight.py 1.09 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import json
import time

class PageInsight() :

token = ""
data = {}
page_insight = {}

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)
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)
return self.page_insight

def getPageInsightByKey(self, key):

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

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