使用Python脚本在Facebook上发表评论

1 投票
1 回答
5330 浏览
提问于 2025-04-17 21:31

我正在尝试用以下的Python脚本在Facebook上评论帖子:

import requests
import json
from time import strftime

AFTER = "1392891447"

TOKEN = 'access_token_here'

def get_posts():
    """Returns dictionary of id, first names of people who posted on my wall
    between start and end time"""

    query = ("SELECT post_id, actor_id, message FROM stream WHERE "
    "filter_key = 'others' AND source_id = me() AND "
    "created_time > " + AFTER + " LIMIT 200")

    payload = {'q': query, 'access_token': TOKEN}

    r = requests.get('https://graph.facebook.com/fql', params=payload)

    result = json.loads(r.text)

    return result['data']

print get_posts()
def commentall(wallposts):
    """Comments thank you on all posts"""


    for wallpost in wallposts:
        r = requests.get('https://graph.facebook.com/%s' %
        wallpost['actor_id'])
        url = 'https://graph.facebook.com/%s/comments' % wallpost['post_id']
        user = json.loads(r.text)
        message = 'Thanks %s :)' % user['first_name']
        payload = {'access_token': TOKEN, 'message': message}

        s = requests.post(url, data=payload)
        print s

        print "Wall post %s done" % wallpost['post_id']


commentall(get_posts())

我添加了额外的'print s'来看看发生了什么。
这个脚本运行后会输出:

<Response[403] >

我搞不清楚错误是什么。最开始我以为是因为令牌的权限不够。我在获取图形浏览器API的令牌时检查了所有权限,但还是不行。这个脚本可以打印出我在指定时间范围内发布在我墙上的帖子。

1 个回答

0

首先,

"""返回一个字典,里面有在我墙上发帖的人的ID和名字,时间在开始和结束时间之间"""

我用filter_key = 'others'进行测试,发现还是包含了我自己在墙上的帖子。所以你可以用actor_id!=me()来替代:

SELECT post_id, actor_id, filter_key, message FROM stream WHERE actor_id!=me() AND source_id = me() AND created_time > 1392891447 LIMIT 200

其次,我建议你把LIMIT减少到100或150,否则你的请求会太大,可能会出现超时错误。

第三,print get_posts()和commentall(get_posts())都是调用了流API两次。

第四,print "Wall post %s done" % wallpost['post_id']是个例外,因为commentall(get_posts())还没有运行。

第五,请在尝试对下一个帖子评论之前,等几秒钟。否则你很可能会触碰到Graph API的速率限制。这个限制是为了防止人们发送垃圾信息。

撰写回答