小编典典

以编程方式获取使用Facebook Graph API的访问令牌

python

我正在尝试将bash或python脚本放在一起以与facebook graph
API一起玩。使用API​​看起来很简单,但是我在bash脚本中设置curl来调用authorize和access_token遇到麻烦。有人有可行的例子吗?


阅读 143

收藏
2020-12-20

共1个答案

小编典典

更新2018-08-23

由于这仍然有一些意见和支持,我只想提一提,到目前为止,似乎存在一个维护良好的第三方SDK:https : //github.com/mobolic/facebook-
sdk


迟到总比不到好,也许其他人正在寻找它。我在MacBook上使用Python 2.6了。

这需要你有

  • 安装的Python facebook模块:https : //github.com/pythonforfacebook/facebook-sdk,
  • 实际的Facebook应用设置
  • 并且您要发布到的个人资料必须已授予适当的权限,以允许所有不同的内容(例如读写)。

您可以在Facebook开发人员文档中阅读有关身份验证的内容。有关详细信息,请参见https://developers.facebook.com/docs/authentication/

这篇博客文章也可能对此有所帮助:http : //blog.theunical.com/facebook-
integration/5-steps-to-publish-on-a-facebook-wall-using-
php/

开始:

#!/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     = 'XXXXXXXXXXXXXXX'
FACEBOOK_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
FACEBOOK_PROFILE_ID = 'XXXXXX'


# Trying to get an access token. Very awkward.
oauth_args = dict(client_id     = FACEBOOK_APP_ID,
                  client_secret = FACEBOOK_APP_SECRET,
                  grant_type    = 'client_credentials')
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]

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

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

对获取令牌进行错误检查可能会更好,但是您会想到要做什么。

2020-12-20