1

I'm trying to send an image with a facebook bot. I can send text fine, but whenever I try to send a message I get an error: TypeError: open file 'plot.jpg', mode 'rb' at 0x7f34a2fe8b70 is not JSON serializable. I'm using flask and heroku for the bot if that makes a difference.

This is my code:

def send_message(recipient_id, message_text):

    log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text))

    params = {
        "access_token": os.environ["PAGE_ACCESS_TOKEN"]
    }
    headers = {
        "Content-Type": "application/json"
    }
    log(os.getcwd())
    data = json.dumps({
        'recipient': {
            'id': recipient_id
        },
        'message': {
            'attachment': {
                'type': 'image',
                'payload': {}
            }
        },
        'filedata': (os.path.basename('plot.jpg'), open('plot.jpg', 'rb'))
    })
    r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=data)
    if r.status_code != 200:
        log(r.status_code)
        log(r.text)
AChampion
  • 29,683
  • 4
  • 59
  • 75
Kevin
  • 11
  • 1
  • 4
  • 1
    Maybe it's expecting the file _contents_ instead of the file _object_?, i.e. `open('plot.jpg', 'rb').read()` – John Gordon Jul 01 '17 at 05:09
  • Thanks! That suggestion definitely set me on right track. I had to add .encode('base64') it could read the file. Now I'm getting this error: {"error":{"message":"(#100) Incorrect number of files uploaded. Must upload exactly one file.","type":"OAuthException","code":100,"error_subcode":2018005,"fbtrace_id":"CgQWOrVTm5H"}} Do you have any idea what's going on? – Kevin Jul 02 '17 at 04:26
  • Maybe `filedata` is supposed to be _just_ the file contents, instead of a two-part tuple? Just a wild guess. – John Gordon Jul 02 '17 at 06:16
  • Thanks for taking the time to reply! Unfortunately I get the same error when I set filedata to "filedata": open('plot.jpg', 'rb').read().encode('base64') – Kevin Jul 03 '17 at 01:42
  • @Kevin Soory this is a bit off topic. I'm also building an echo chatbot on python and have a problem where the message gets repeated multiple times. https://stackoverflow.com/questions/44848406/facebook-webhook-maiking-multiple-calls-for-the-same-message – Arsenal Fanatic Jul 03 '17 at 12:15

1 Answers1

0

I got the same issue and i solved it by using multipart/form-data, instead of encoding the entire payload using json.dumps() you can use the MultipartEncoder from requests-toolbelt-0.8.0 to multipart encode the payload.

Note - Facebook's Graph API is accepting only png images for some unknown reasons, in the below example i've used a png file.

*Edited the code(redundant end parenthesis)

import json

import requests
from requests_toolbelt import MultipartEncoder

def send_message(recipient_id, message_text):

    log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text))

    params = {
        "access_token": os.environ["PAGE_ACCESS_TOKEN"]
    }
    log(os.getcwd())
    data = {
        # encode nested json to avoid errors during multipart encoding process
        'recipient': json.dumps({
            'id': recipient_id
        }),
        # encode nested json to avoid errors during multipart encoding process
        'message': json.dumps({
            'attachment': {
                'type': 'image',
                'payload': {}
            }
        }),
        'filedata': (os.path.basename('plot.png'), open('plot.png', 'rb'), 'image/png')
    }

    # multipart encode the entire payload
    multipart_data = MultipartEncoder(data)

    # multipart header from multipart_data
    multipart_header = {
        'Content-Type': multipart_data.content_type
    }

    r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=multipart_header, data=multipart_data)
    if r.status_code != 200:
        log(r.status_code)
        log(r.text)
tera_mx
  • 145
  • 1
  • 11
Sanjay Ortiz
  • 75
  • 1
  • 12