Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| code:slack_report_delivery [2024/12/06 03:31] – created optrix | code:slack_report_delivery [2025/12/18 22:50] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====Slack Report Delivery==== | ||
| + | {{slackdelivery.png|250}} | ||
| + | |||
| + | 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. | ||
| + | |||
| + | <code python> | ||
| + | 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[' | ||
| + | |||
| + | #Gather the files to send | ||
| + | fileset = {} | ||
| + | for n in details[' | ||
| + | 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[' | ||
| + | channel_id = d[' | ||
| + | for att in d[' | ||
| + | try: | ||
| + | # Call the files.upload method using the WebClient | ||
| + | # Uploading files requires the `files: | ||
| + | print(" | ||
| + | | ||
| + | result = client.files_upload_v2( | ||
| + | title=att[1], | ||
| + | file=att[0] | ||
| + | ) | ||
| + | | ||
| + | file_url = result.get(" | ||
| + | new_message = client.chat_postMessage( | ||
| + | channel=channel_id, | ||
| + | text=f" | ||
| + | ) | ||
| + | |||
| + | except SlackApiError as e: | ||
| + | | ||
| + | failedfiles.append(att[1]) | ||
| + | failreason = str(e) | ||
| + | | ||
| + | if len(failedfiles) > 0: | ||
| + | print(" | ||
| + | print(failreason) | ||
| + | else: | ||
| + | print(" | ||
| + | print(" | ||
| + | | ||
| + | |||
| + | </ | ||