Search code examples
pythonpython-3.xfacebookfacebook-graph-api

Character problem with endpoint '/{GROUP_ID}/feed' of Facebook API


The code below works without error, but the posted text is cut off in Facebook as soon as a "&" character is found.

TOKEN_ID = '<Token>'
GROUP_ID = '<group_id>'
headers   = { 'Content-Type': 'text/html; charset=UTF-8;', }
msg = 'Automation test & Python script'
fb_url = f"https://graph.facebook.com/v13.0/{GROUP_ID}/feed?message={msg}&access_token={TOKEN_ID}"
resp = requests.post(fb_url, headers=headers)
pprint(resp.json())

return: 'id': '686578895356485_972982316716140'}

I want to post Automation test & Python script and the post only have Automation test as you can see with the capture with problem

It seems to be an encoding problem, but I don't see how to fix it.

Thanks for your help.


Solution

  • I found a solution that works. As supposed, it was an encoding problem.

    import urllib.parse
     
    TOKEN_ID = '<Token>'
    GROUP_ID = '<group_id>'
    headers   = { 'Content-Type': 'text/html; charset=UTF-8;', }
    msg = 'Automation test & Python script'
    msg = urllib.parse.quote_plus(msg)
    fb_url = f"https://graph.facebook.com/v13.0/{GROUP_ID}/feed?message={msg}&access_token={TOKEN_ID}"
    resp = requests.post(fb_url, headers=headers)
    pprint(resp.json())
    

    If you have something better or cleaner, I'll take it.