Want to upload a file to slack (files.upload api)

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
eradicatore
Posts: 52
Joined: Thu Apr 20, 2017 9:19 pm

Want to upload a file to slack (files.upload api)

Post by eradicatore » Fri Nov 17, 2017 8:31 pm

Hi,
So in normal python, I'm able to upload a file just fine to slack. here is the code:

Code: Select all

my_file = {
  'file' : ('/tmp/myfile.pdf', open('/tmp/myfile.pdf', 'rb'), 'pdf')
}

payload={
  "filename":"myfile.pdf", 
  "token":token, 
  "channels":['#random'], 
}

r = requests.post("https://slack.com/api/files.upload", params=payload, files=my_file)

But urequests.py doesn't support the "files" parameter. Is there any hope of using the slack files.upload api with micropython on my nodemcu?

https://api.slack.com/methods/files.upload
https://stackoverflow.com/questions/434 ... d-requests

I don't think I could use the "content" header parameter for the files.upload api because I'll run out of ram on the nodemcu trying to put the file contents into a ram variable.

SpotlightKid
Posts: 463
Joined: Wed Apr 08, 2015 5:19 am

Re: Want to upload a file to slack (files.upload api)

Post by SpotlightKid » Tue Nov 21, 2017 9:51 am

According to the documentation of the slack API you linked to, instead of sending the file contents as a multipart/form-data body, you can also upload the content of the file as the content POST parameter.

I described how use urequest for POST requests with application/x-www-form-urlencoded params here:

viewtopic.php?p=22941#p22941

And here's a GIST with a handy wrapper function for doing these requests and a stripped down version of urllib.parse, which just contains the necessary parts to encode form params:

https://gist.github.com/SpotlightKid/ec ... 635f62ab73

You would use it like so:

Code: Select all

from upost import post

url = 'https://slack.com/api/files.upload'
data = dict(token="XXXXXX", filename="test.txt", content="This is a test")
resp = post(url, data=data)
if resp.status_code == 200:
    print(resp.json())
else:
    print("Request failed:", resp.status_code, resp.reason)
I couldn't test this properly, since I don't have a slack account, but the request generally works and returns an authentication failure:

Code: Select all

{'error': 'invalid_auth', 'ok': False}
Chris

Post Reply