2011-09-08 191 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下半年应该有你需要的所有信息。