根据请求将带有图像的评论发布到Facebook

时间:2020-10-21 07:32:05

标签: python facebook python-requests

我是Facebook API的新手,我一直在尝试发布带有图像的评论,但没有运气。 我找到了一个脚本,该脚本使用requests模块发布评论,但是在发布图像附件时遇到了麻烦。

我首先是这样尝试的:

def comment_on_posts(posts, amount):
    counter = 0 
    for post in posts: 
        if counter >= amount: 
            break 
        else: 
            counter = counter + 1 
        url = "https://graph.facebook.com/{0}/comments".format(post['id']) 
        message = "message here"
        dir = os.listdir("./assets/imagedir")
        imageFile = f"./assets/imagedir/{dir[0]}"
        img = {open(imageFile, 'rb')}
        parameters = {'access_token' : access_token, 'message' : message, 'file' : img}
        s = requests.post(url, data = parameters)
        print("Submitted comment successfully!")
        print(s)
     

print(s)返回<Response [200]>

评论发表...但是图像未出现在评论中。

我在this post上读到,请求没有产生多部分/表格

所以我尝试了这个:

url = "https://graph.facebook.com/{0}/comments".format(post['id']) 
        message = "message here"
        dir = os.listdir("./assets/imagedir")
        imageFile = f"./assets/imagedir/{dir[0]}"
        img = {open(imageFile, 'rb')}
        data = {'access_token' : access_token, 'message' : message}
        files = {'file' : img}
        s = requests.post(url, data = data, files = files)
        print("Posted comment successfully")
        print(s)

现在我遇到了错误:TypeError: a bytes-like object is required, not 'set'

我真的不确定在这里做什么。也许有更好的方法可以做到这一点? 任何帮助表示赞赏。

我对this post中的脚本做了一些修改。这些代码的全部功劳归他们所有。

我只修改了comment_on_posts和原始脚本中的一些可选值,其他所有内容都是相同的。

1 个答案:

答案 0 :(得分:1)

尝试像Facebook Docs中那样使用source字段(而不是file )字段,并以multipart/form-data的形式传递图像:

import requests

post_id = '***'
access_token = '***'
message = '***'
image_path = '***'

url = f'https://graph.facebook.com/v8.0/{post_id}/comments'
data = {'message': message, 'access_token': access_token}
files = {'source': open(image_path, 'rb')}

requests.post(url, params=data, files=files)