Slack Report Delivery
The code below delivers reports to a Slack server
Note that you need to…
- Have created a Slack Bot Token,
- Added the token to your report settings, in an option named slacktoken,
- Added the bot to the destination channel,
- Installed the slack_sdk package in Python on the ReportList server.
import time import sys import requests import datetime import os import json import traceback from slack_sdk import WebClient from slack_sdk.errors import SlackApiError f = open(sys.argv[1]) content = f.read() f.close() details = json.loads(content) # WebClient instantiates a client that can call API methods # When using Bolt, you can use either `app.client` or the `client` passed to listeners. client = WebClient(token=details['options']['slacktoken']) #Gather the files to send fileset = {} for n in details['files']: fileset[n[1]] = n[0] failedfiles = [] #If there are any files, send 'em. if len(fileset) > 0: # ID of channel that you want to upload file to for d in details['destinations']: channel_id = d['name'] for att in d['attachments']: try: # Call the files.upload method using the WebClient # Uploading files requires the `files:write` scope print("Pushing To " + channel_id) result = client.files_upload_v2( title=att[1], file=att[0] ) file_url = result.get("file").get("permalink") new_message = client.chat_postMessage( channel=channel_id, text=f"{att[1]}: {file_url}", ) except SlackApiError as e: failedfiles.append(att[1]) failreason = str(e) if len(failedfiles) > 0: print("-----") print(failreason) else: print("-----") print("SUCCESS")