python - Facebook 发布到页面

标签 python facebook facebook-graph-api

我正在尝试将我是管理员(不是个人资料)的 Facebook 页面张贴到墙上,但是没有成功。我如何实现这一目标?我卡在了页面访问 token 检索部分。

#!/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

最佳答案

我不建议使用 curl 通过命令行执行此操作,因为它不太安全且不太可靠。您可以使用 urllib2 和 json 模块完成所有这些操作

要获取访问 token ,您只需调用 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 以纯文本形式为您提供访问 token ,因此您不需要 json 模块。我已经更新了示例以显示您应该做什么。注意 target.read() 会给你字符串 'access_token=ACCESS_TOKEN' 然后你只是解析它以删除标识符。

要查看对 url 的响应并输入您的信息,您将得到一个带有 acess_token 的 json 字典。

下半场this page应该有您需要的所有信息。

关于python - Facebook 发布到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7355615/

相关文章:

python - 如何在 Plotly 中为瀑布图添加总值列

facebook - block for-in 循环

python - 如何使用 FaceBook Python SDK 上传多张图片?

php - Facebook 贴到墙 £ 显示为特殊字符

Python 正则表达式将列表解析为文本以进行响应

python - PyQt - 检测哪个项目已更改

php - Facebook 第二次验证用户身份

javascript - 如何审核 Facebook 评论

javascript - 如何转发 Facebook 帖子

python - ModuleNotFoundError : No module named 'pgzrun' when I have it installed?