2011-09-08 189 views
2

我試圖張貼到我是管理員(不是個人資料)一個Facebook頁面的牆上,但沒有運氣。我如何實現這一目標?我被困在頁面訪問令牌檢索部分。Facebook的發佈到頁面

#!/usr/bin/python 
# coding: utf-8 

import facebook 
import urllib 
import urlparse 
import subprocess 
import warnings 

# Hide deprecation warnings. The facebook module isn't that up-to-date (facebook.GraphAPIError). 
warnings.filterwarnings('ignore', category=DeprecationWarning) 




# Parameters of your app and the id of the profile you want to mess with. 
FACEBOOK_APP_ID  = 'XXXXXXXXXXXXXX' 
FACEBOOK_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXX' 
FACEBOOK_PROFILE_ID = 'XXXXXXXXXXX' 


# Trying to get an access token. Very awkward. 
oauth_args = dict(client_id  = FACEBOOK_APP_ID, 
        client_secret = FACEBOOK_APP_SECRET, 
        scope   = 'manage_pages', 
        response_type = 'token' 
       ) 
oauth_curl_cmd = ['curl', 
        'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(oauth_args)] 
oauth_response = subprocess.Popen(oauth_curl_cmd, 
            stdout = subprocess.PIPE, 
            stderr = subprocess.PIPE).communicate()[0] 

print urllib.urlencode(oauth_args) 

try: 
    oauth_access_token = urlparse.parse_qs(str(oauth_response))['access_token'][0] 
except KeyError: 
    print('Unable to grab an access token!') 
    exit() 
print oauth_access_token 

facebook_graph = facebook.GraphAPI(oauth_access_token) 


# Try to post something on the wall. 
try: 
    fb_response = facebook_graph.put_wall_post('Hello from Python', \ 
               profile_id = FACEBOOK_PROFILE_ID) 
    print fb_response 
except facebook.GraphAPIError as e: 
    print 'Something went wrong:', e.type, e.message 

回答

1

我不會推薦使用curl通過命令行來執行此操作,因爲它不太安全,也不太可靠。你可以做這一切與urllib2的和JSON模塊

以獲得訪問令牌,你只是想打個電話給https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials

,所以你會怎麼做:

url='https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials' 
target=urllib2.urlopen(url) 
token = target.read()[13:] 

編輯: 我不好,我忘了facebook/oauth以純文本的形式給你訪問令牌,所以你不需要json模塊。我已經更新了示例以顯示您應該做的事情。注意target.read()會給你字符串'access_token = ACCESS_TOKEN',然後你只是解析它來移除標識符。

,看看有什麼反應是去url並把你的信息,你將一個JSON字典與acess_token。

this page下半年應該有你需要的所有信息。