Skip to content

Commit 2285caa

Browse files
committed
make slack api safer and update to file_upload_v2
origonal file upload deprecated
1 parent 6d2b995 commit 2285caa

File tree

1 file changed

+37
-9
lines changed

1 file changed

+37
-9
lines changed

robusta_krr/core/runner.py

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -127,15 +127,43 @@ def _process_result(self, result: Result) -> None:
127127
console = Console(file=target_file, width=settings.width)
128128
console.print(formatted)
129129
if settings.slack_output:
130-
client = WebClient(os.environ["SLACK_BOT_TOKEN"])
131-
warnings.filterwarnings("ignore", category=UserWarning)
132-
client.files_upload(
133-
channels=f"#{settings.slack_output}",
134-
title="KRR Report",
135-
file=f"./{file_name}",
136-
initial_comment=f'Kubernetes Resource Report for {(" ".join(settings.namespaces))}',
137-
)
138-
os.remove(file_name)
130+
try:
131+
slack_token = os.environ.get("SLACK_BOT_TOKEN")
132+
if not slack_token:
133+
raise ValueError("SLACK_BOT_TOKEN is missing from environment variables.")
134+
135+
client = WebClient(slack_token)
136+
137+
# Validate slack_output format
138+
channel_name = settings.slack_output.strip()
139+
if not channel_name.startswith("#"):
140+
channel_name = f"#{channel_name}"
141+
142+
# Send a message and get the channel ID
143+
resp = client.chat_postMessage(
144+
channel=channel_name,
145+
text=f'Kubernetes Resource Report for {(" ".join(settings.namespaces))}'
146+
)
147+
148+
channel_id = resp.get("channel")
149+
if not channel_id:
150+
raise ValueError(f"Failed to retrieve channel ID for {channel_name}")
151+
152+
warnings.filterwarnings("ignore", category=UserWarning)
153+
154+
# Upload the file it no longer takes the channel plain text name
155+
client.files_upload_v2(
156+
channels=channel_id,
157+
title="KRR Report",
158+
file=f"./{file_name}",
159+
)
160+
161+
# Safely remove the file
162+
if os.path.exists(file_name):
163+
os.remove(file_name)
164+
165+
except Exception as e:
166+
logger.info(f"Unexpected error: {e}")
139167

140168
def __get_resource_minimal(self, resource: ResourceType) -> float:
141169
if resource == ResourceType.CPU:

0 commit comments

Comments
 (0)