当前位置: 代码迷 >> python >> 使用python脚本评论Facebook
  详细解决方案

使用python脚本评论Facebook

热度:53   发布时间:2023-07-14 08:47:31.0

我试图使用以下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的令牌时检查了所有权限。 仍然不起作用。 脚本将在给定时间范围内放置在我墙上的帖子打印出来。

首先,

“”“返回id字典,即在开始时间和结束时间之间张贴在我墙上的人们的名字”“”“

我使用filter_key ='others'进行了测试,发现它仍然在我的墙上包含我自己的帖子。 因此,您可以使用actor_id!= me()代替:

从流中选择post_id,actor_id,filter_key,消息actor_id!= me()AND source_id = me()AND created_time> 1392891447限制200

其次,我建议您将LIMIT降低到100或150,否则您的请求过大,可能很有可能发生超时错误。

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

第四,由于commentall(get_posts())尚未运行,因此打印“ Wall post%s done”(完成墙张贴%s)%wallpost ['post_id']是例外。

第五,在您对下一篇文章发表评论之前,请先睡上几秒钟。 否则,您最有可能达到Graph API速率限制。 此速率限制是为了防止人们发送垃圾邮件。