In [1]:
# 隨時更新才可用
ACCESS_TOKEN = ""
In [2]:
import facebook # pip install facebook-sdk
import requests
import json
from random import randint
# A helper function to pretty-print Python objects as JSON
def pp(o):
print json.dumps(o, indent=1)
# Create a connection to the Graph API with your access token
g = facebook.GraphAPI(ACCESS_TOKEN)
In [3]:
# 重覆讀取next url 資訊
def resUrl(content,total_posts):
# debug用
for one in content['data']:
total_posts.append(one)
if content['paging'].has_key("next"):
content = requests.get(content['paging']['next']).json()
resUrl(content,total_posts)
# 計算總留言
def commentsSum(message):
# 該篇留言的comments數
total_posts = [ one for one in message['comments']['data']]
# 該篇留言的comments數 nextpage
if message['comments']['paging'].has_key("next"):
content = requests.get(message['comments']['paging']['next']).json()
resUrl(content,total_posts)
return total_posts
In [4]:
# lifencku
about = g.get_object('https://www.facebook.com/lifencku')
comments = g.get_object('https://www.facebook.com/lifencku/photos/a.348937965310999.1073741828.348140638724065/361833650688097/?type=1&__mref=message_bubble')
data = commentsSum(comments)
In [5]:
# 原始留言的數目
len(data)
Out[5]:
In [6]:
# 不計算重覆留言的人
compareList = []
dataSet=[]
for tmp in data:
if tmp[u'from'][u'name'] not in compareList:
compareList.append(tmp[u'from'][u'name'])
dataSet.append(tmp)
In [7]:
# 去掉重覆留言的人數
len(dataSet)
Out[7]:
In [8]:
# 設定抽獎人數
peopleNum = 7
# 已經抽中的人List
alreadyList=[]
print(about['name'])
print('----------------------------')
i=1
while i <= peopleNum:
numr = randint(0,len(dataSet)-1)
# 去除已經抽中的人
if numr not in alreadyList:
alreadyList.append(numr)
i+=1
print(dataSet[numr][u'from'][u'name'])
In [174]:
In [ ]: