pythonattachmentpushover

Python publish picture attachment to pushover


I am successfully sending messages to pushover using the below code, however I would like to send picture attachment as introduced in the latest API. How am I able to convert the last code sample to work in python.

Working Code:

import httplib, urllib
conn = httplib.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
  urllib.urlencode({
    "token": "APP_TOKEN",
    "user": "USER_KEY",
    "message": "hello world",
  }), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()

Sample API

curl -s \
 --form-string "token=APP_TOKEN" \
 --form-string "user=USER_KEY" \
 --form-string "message=here is an image attachment" \
 -F "attachment=@/path/to/your/image.jpg" \
 https://api.pushover.net/1/messages.json

Solution

  • I have not tried urllib, but been successful with requests. I don't really know if you want to use that module. But here is the code anyways.

    import requests
    
    r = requests.post("https://api.pushover.net/1/messages.json", data={"token":"APP_TOKEN","user":"USER_KEY","message":"Got Image?"}, files={"attachment":open("PATH_TO_IMAGE","rb")})
    

    To break it down. You pass the requested parameters to be formencoded in the dict data. Then you pass the file in the dict files. The important thing is that the file is opened rb (read binary).