Search code examples
pythonpycurlpushbullet

Pushbullet pycurl with linefeed in message


I'm trying to send pushbullet notifications with linefeed / newlines but it doesnt work. when i add %0d or \n it doesnt do anything.

in bash i just add -d to my curl command and it works. is there a similar solution for pycurl ?

Thanks in advance

any suggestions ?

import pycurl


text2 = "line%0dline2"
postData =  '{"type":"note", "title":"Title", "body":"%s"}' %text2.encode("utf-8")
c = pycurl.Curl()
c.setopt(pycurl.WRITEFUNCTION, lambda x: None)
c.setopt(pycurl.URL, 'https://api.pushbullet.com/v2/pushes')
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json'])
c.setopt(pycurl.USERPWD, "api")
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, postData)
c.perform()

Solution

  • I'm guessing that you are using something like:

    postData = '{"type":"note", "title":"Title", "body":"line\nline2"}'
    

    This means that when you send it to the server, the server sees this:

    {"type":"note", "title":"Title", "body":"line
    line2"}
    

    You can see this by doing:

    print(postData)
    

    JSON specifies that a newline character must be escaped when it appears in a string, so what you really want to send is:

    {"type":"note", "title":"Title", "body":"line\nline2"}
    

    To get that in python, you should either use "\\n" or a raw string:

    postData = '{"type":"note", "title":"Title", "body":"line\\nline2"}'