Python 通过请求将带有图像的评论发布到Facebook
我对Facebook API非常陌生,我一直在尝试用图片发表评论,但运气不好。 我发现一个脚本可以在Python 通过请求将带有图像的评论发布到Facebook,python,facebook,python-requests,Python,Facebook,Python Requests,我对Facebook API非常陌生,我一直在尝试用图片发表评论,但运气不好。 我发现一个脚本可以在requests模块中发布评论,但是我在让它发布图像附件时遇到了麻烦 我第一次是这样尝试的: def comment_on_posts(posts, amount): counter = 0 for post in posts: if counter >= amount: break else:
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)
打印
返回
评论帖子。。。但这张图片并没有出现在评论中
我了解到请求不会生成多部分/表单
所以我试了一下:
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:需要一个类似字节的对象,而不是“set”
我真的不知道该怎么办。也许有更好的方法来实现这一点?
感谢您的帮助
我稍微修改了脚本。这些代码的所有功劳都归他们所有
我只修改了帖子上的
comment\u和原始脚本中的一些可选值,其他所有内容都是一样的。尝试使用源字段(而不是文件)字段作为中的,并将图像作为多部分/表单数据传递:
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)
我很确定这是有效的。然而,我遇到了一个问题。我得到了
。我给了它权限user\u events
,pages\u show\u list
,pages\u read\u engagement
,pages\u read\u user\u content
,pages\u manage\u engagement
和public\u profile
。从我在文档中读到的内容来看,这应该是我所需要的。