I had written a code in python to fetch the huge set (80 lines) of data from DB, now I would like to post that data in slack through webhook. I tried posting the data directly,but its not working for me, so I decided to save the data in txt/.png file and post it in slack
I tried below code in python after saving my data in report.txt file, but its not helping me
headers = {
'Content-type': 'application/json',
}
data = open('\\results\report.txt')
response = requests.post('https://jjjjjjj.slack.com/services/mywebhook', headers=headers, data=data)
Please share me the Curl command which will fit in python script to post the attachment in slack or please suggest me any better approach to post more than 50 lines for data to slack
I would suggest to upload long text as text file. That way Slack will automatically format it with a preview and users can click on it to see the whole content.
To upload a file you need to use files_upload
API method. With it you can also include an initial message with your upload.
Here is an example using the standard Slack library. Here I am reading the data from a file, but you would of course use your data instead:
import slack
import os
# init slack client with access token
slack_token = os.environ['SLACK_TOKEN']
client = slack.WebClient(token=slack_token)
# fetch demo text from file
with open('long.txt', 'r', encoding='utf-8') as f:
text = f.read()
# upload data as file
response = client.files_upload(
content=text,
channels='general',
filename='long.txt',
title='Very long text',
initial_comment='Here is the very long text as requested:'
)
assert response['ok']
The trick is to use content
not file
to pass the data. If you use file
the API will try to load a file from your filesystem.