Skip to content

Commit ab21691

Browse files
author
Matthias
committed
Changelog fragment
1 parent d71a6e8 commit ab21691

File tree

2 files changed

+43
-33
lines changed

2 files changed

+43
-33
lines changed

changelogs/fragments/slack.yml

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
minor_changes:
2+
- Slack upload file - feature added support for uploading files to Slack (https://github.com/ansible-collections/community.general/pull/9472).

plugins/modules/slack.py

+41-33
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,8 @@
148148
type: dict
149149
description:
150150
- Specify details to upload a file to Slack. The file can include metadata such as an initial comment, alt text, snipped and title.
151-
- See Slack's file upload API for details at U(https://api.slack.com/methods/files.getUploadURLExternal) and U(https://api.slack.com/methods/files.completeUploadExternal).
151+
- See Slack's file upload API for details at U(https://api.slack.com/methods/files.getUploadURLExternal).
152+
- See Slack's file upload API for details at U(https://api.slack.com/methods/files.completeUploadExternal).
152153
suboptions:
153154
path:
154155
type: str
@@ -171,6 +172,10 @@
171172
type: str
172173
description:
173174
- Optional title for the uploaded file.
175+
thread_ts:
176+
type: str
177+
description:
178+
- Optional timestamp of parent message to thread this message, see U(https://api.slack.com/docs/message-threading).
174179
"""
175180

176181
EXAMPLES = r"""
@@ -293,6 +298,7 @@
293298
alt_text: ''
294299
snippet_type: ''
295300
title: ''
301+
thread_ts: ''
296302
"""
297303

298304
import re
@@ -476,7 +482,7 @@ def do_notify_slack(module, domain, token, payload):
476482

477483
def get_channel_id(module, token, channel_name):
478484
url = SLACK_CONVERSATIONS_LIST_WEBAPI
479-
headers = {"Authorization": f"Bearer {token}"}
485+
headers = {"Authorization": "Bearer " + token}
480486
params = {
481487
"types": "public_channel,private_channel,mpim,im",
482488
"limit": 1000,
@@ -487,22 +493,22 @@ def get_channel_id(module, token, channel_name):
487493
if cursor:
488494
params["cursor"] = cursor
489495
query = urlencode(params)
490-
full_url = f"{url}?{query}"
496+
full_url = "%s?%s" % (url, query)
491497
response, info = fetch_url(module, full_url, headers=headers, method="GET")
492498
status = info.get("status")
493499
if status != 200:
494500
error_msg = info.get("msg", "Unknown error")
495501
module.fail_json(
496-
msg=f"Failed to retrieve channels: {error_msg} (HTTP {status})"
502+
msg="Failed to retrieve channels: %s (HTTP %s)" % (error_msg, status)
497503
)
498504
try:
499505
response_body = response.read().decode("utf-8") if response else ""
500506
data = json.loads(response_body)
501-
except json.JSONDecodeError as e:
502-
module.fail_json(msg=f"JSON decode error: {e}")
507+
except ValueError as e:
508+
module.fail_json(msg="JSON decode error: %s" % str(e))
503509
if not data.get("ok"):
504510
error = data.get("error", "Unknown error")
505-
module.fail_json(msg=f"Slack API error: {error}")
511+
module.fail_json(msg="Slack API error: %s" % error)
506512
channels = data.get("channels", [])
507513
for channel in channels:
508514
if channel.get("name") == channel_name:
@@ -511,18 +517,18 @@ def get_channel_id(module, token, channel_name):
511517
cursor = data.get("response_metadata", {}).get("next_cursor")
512518
if not cursor:
513519
break
514-
module.fail_json(msg=f"Channel named '{channel_name}' not found.")
520+
module.fail_json(msg="Channel named '%s' not found." % channel_name)
515521

516522

517523
def upload_file_to_slack(module, token, channel, file_upload):
518524
try:
519525
file_path = file_upload["path"]
520526
if not os.path.exists(file_path):
521-
module.fail_json(msg=f"File not found: {file_path}")
527+
module.fail_json(msg="File not found: %s" % file_path)
522528
# Step 1: Get upload URL
523529
url = SLACK_GET_UPLOAD_URL_EXTERNAL
524530
headers = {
525-
"Authorization": f"Bearer {token}",
531+
"Authorization": "Bearer " + token,
526532
"Content-Type": "application/x-www-form-urlencoded",
527533
}
528534
params = urlencode(
@@ -542,21 +548,21 @@ def upload_file_to_slack(module, token, channel, file_upload):
542548
}
543549
)
544550
response, info = fetch_url(
545-
module, f"{url}?{params}", headers=headers, method="GET"
551+
module, "%s?%s" % (url, params), headers=headers, method="GET"
546552
)
547553
if info["status"] != 200:
548554
module.fail_json(
549-
msg=f"Error retrieving upload URL: {info['msg']} (HTTP {info['status']})"
555+
msg="Error retrieving upload URL: %s (HTTP %s)" % (info['msg'], info['status'])
550556
)
551557
try:
552558
upload_url_data = json.load(response)
553-
except json.JSONDecodeError:
559+
except ValueError:
554560
module.fail_json(
555-
msg=f"The Slack API response is not valid JSON: {response.read()}"
561+
msg="The Slack API response is not valid JSON: %s" % response.read()
556562
)
557563
if not upload_url_data.get("ok"):
558564
module.fail_json(
559-
msg=f"Failed to retrieve upload URL: {upload_url_data.get('error')}"
565+
msg="Failed to retrieve upload URL: %s" % upload_url_data.get('error')
560566
)
561567
upload_url = upload_url_data["upload_url"]
562568
file_id = upload_url_data["file_id"]
@@ -573,10 +579,10 @@ def upload_file_to_slack(module, token, channel, file_upload):
573579
)
574580
if info["status"] != 200:
575581
module.fail_json(
576-
msg=f"Error during file upload: {info['msg']} (HTTP {info['status']})"
582+
msg="Error during file upload: %s (HTTP %s)" % (info['msg'], info['status'])
577583
)
578-
except FileNotFoundError:
579-
module.fail_json(msg=f"The file {file_path} is not found.")
584+
except IOError:
585+
module.fail_json(msg="The file %s is not found." % file_path)
580586
# Step 3: Complete upload
581587
complete_url = SLACK_COMPLETE_UPLOAD_EXTERNAL
582588
files_data = json.dumps(
@@ -605,7 +611,7 @@ def upload_file_to_slack(module, token, channel, file_upload):
605611
}
606612
)
607613
headers = {
608-
"Authorization": f"Bearer {token}",
614+
"Authorization": "Bearer " + token,
609615
"Content-Type": "application/json",
610616
}
611617
try:
@@ -614,18 +620,18 @@ def upload_file_to_slack(module, token, channel, file_upload):
614620
)
615621
if info["status"] != 200:
616622
module.fail_json(
617-
msg=f"Error during upload completion: {info['msg']} (HTTP {info['status']})"
623+
msg="Error during upload completion: %s (HTTP %s)" % (info['msg'], info['status'])
618624
)
619625
upload_url_data = json.load(response)
620-
except json.JSONDecodeError:
626+
except ValueError:
621627
module.fail_json(
622-
msg=f"The Slack API response is not valid JSON: {response.read()}"
628+
msg="The Slack API response is not valid JSON: %s" % response.read()
623629
)
624630
if not upload_url_data.get("ok"):
625-
module.fail_json(msg=f"Failed to complete the upload: {upload_url_data}")
631+
module.fail_json(msg="Failed to complete the upload: %s" % upload_url_data)
626632
return upload_url_data
627633
except Exception as e:
628-
module.fail_json(msg=f"Error uploading file: {str(e)}")
634+
module.fail_json(msg="Error uploading file: %s" % str(e))
629635

630636

631637
def main():
@@ -647,14 +653,16 @@ def main():
647653
blocks=dict(type='list', elements='dict'),
648654
message_id=dict(type='str'),
649655
prepend_hash=dict(type='str', choices=['always', 'never', 'auto']),
650-
upload_file=dict(type="dict", options=dict(
651-
path=dict(type="str", required=True),
652-
alt_text=dict(type="str"),
653-
snippet_type=dict(type="str"),
654-
initial_comment=dict(type="str"),
655-
thread_ts=dict(type="str"),
656-
title=dict(type="str")
657-
)
656+
upload_file=dict(
657+
type="dict",
658+
options=dict(
659+
path=dict(type="str", required=True),
660+
alt_text=dict(type="str"),
661+
snippet_type=dict(type="str"),
662+
initial_comment=dict(type="str"),
663+
thread_ts=dict(type="str"),
664+
title=dict(type="str"),
665+
)
658666
),
659667
),
660668
supports_check_mode=True,
@@ -688,7 +696,7 @@ def main():
688696
upload_response=upload_response,
689697
)
690698
except Exception as e:
691-
module.fail_json(msg=f"Failed to upload file: {str(e)}")
699+
module.fail_json(msg="Failed to upload file: %s" % str(e))
692700

693701
if prepend_hash is None:
694702
module.deprecate(

0 commit comments

Comments
 (0)