通过请求在Facebook上发布带有图片的评论



我对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]>

评论帖子。。。但是该图像没有出现在评论上。

我在这篇文章中读到,请求不会产生多部分/表单

所以我尝试了这个:

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'

我真的不知道在这里该怎么办。也许有更好的方法来实现这一点?感谢您的帮助。

我对这篇文章的脚本做了一些修改。这个代码的所有功劳都归于他们。

我只修改了原始脚本中的comment_on_posts和一些可选值,其他的都是一样的。

尝试像在Facebook文档中那样使用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)

最新更新