1

I'm very very new to the Facebook API and I've been trying post comments with images and have had no luck. I found a script that posts comments with the requests module but I am having trouble with getting it to post an image attachment.

I first tried it like this:

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

The comment posts... but the image does not appear on the comment.

I read on this post that requests does not produce multipart/form

So I tried this:

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)

Now I'm getting the error : TypeError: a bytes-like object is required, not 'set'

I'm really not sure what to do here. Maybe there is a better way of accomplishing this? Any help is appreciated.

I've slightly modified the script from this post. All credit for this code goes to them.

I've only modified comment_on_posts and some optional values from the original script, everything else is the same.

rawsomeman
  • 13
  • 2

1 Answers1

2

Try to use the source field (not file ) field as in Facebook Docs and pass the image as 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)
  • I'm pretty sure this worked. However, I am running into an issue. I'm getting ``. I gave it the permissions `user_events`, `pages_show_list`, `pages_read_engagement`, `pages_read_user_content`, `pages_manage_posts`, `pages_manage_engagement` and `public_profile`. From what I've read in the documentation that should be all I need. – rawsomeman Oct 22 '20 at 03:48
  • It worked for me many thanks! I was trying to use the graph api (with methods such as `graph.put_comment` and `graph.put_object`) but it didn't work – sound wave Mar 29 '22 at 09:18