I used to have a working python function to fetch files from a specific Slack channel, but that stopped working a few months ago.
I tested the same request to the slack API (files.list) using Postman which does give me an array with a number of files.
The following code used to work but no longer does:
import requests
import json
apiBase = "https://slack.com/api/"
accesToken = "Bearer xoxb-<secret>"
requestData = { "channel": "<obscured>" }
r = requests.post(apiBase + "files.list", headers={'Authorization': accesToken, 'Content-Type': 'application/json; charset=utf-8'}, data=requestData)
try:
response = json.loads(r.text)
except:
print("Read error")
isError = True
if(not 'files' in response):
if('error' in response):
print(response['error'])
if('warning' in response):
print(response['warning'])
isError = True
files = response['files']
files.sort(key=lambda x:x['timestamp'])
count = len(files)
print(str(r))
print(str(r.request.body))
print(str(r.request.headers['Content-Type']))
print(str(r.text))
The result is:
<Response [200]>
channel=<secret>
application/json; charset=utf-8
{"ok":true,"files":[],"paging":{"count":100,"total":0,"page":1,"pages":0}}
Process finished with exit code 0
Postman also returns a 200 OK, but the array contains 3 files for this channel. So why is Python not getting the 3 files...?
I know that an app needs to be given access to the channel in Slack which is the case here. (The channel and credentials are identical in both scenario's (Python and Postman).
Please advise me ...
I think it has something to do with the content-type you send with the requests.post
Have you tried using
json=requestData
instead of
data=requestData
Even though the content-type is correctly set in your headers the requests.post might still send "data" as a dictionary, this is maybe why the slack api is ignoring your data.
The solution was to put the requestData into the url as a parameter, this can be elegantly done using the "params" argument of the requests.post() function like so:
requestData = { "channel": channel_id }
requests.post(params=requestData)
This is the way the Slack api expects the data.