通过请求将带有图像的评论发布到 Facebook

Posting comments with images to Facebook with requests

我对 Facebook API 非常陌生,我一直在尝试 post 使用图片发表评论,但没有成功。 我找到了 post 对 requests 模块进行评论的脚本,但我无法将其添加到 post 图片附件。

我第一次尝试是这样的:

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) returns <Response [200]>

评论 posts... 但是图片没有出现在评论中。

我在 上看到请求没有产生 multipart/form

所以我尝试了这个:

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 和原始脚本中的一些可选值,其他一切都是一样的。

尝试像 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)