1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-22 03:49:36 +00:00
Files
core/homeassistant/components/slack/utils.py
jsuar a2d76cac5a Fix Slack file upload (#135818)
* pgrade Slack integration to use AsyncWebClient and support files_upload_v2

- Replaced deprecated WebClient with AsyncWebClient throughout the integration.
- Removed the unsupported `run_async` parameter.
- Added a helper function to resolve channel names to channel IDs.
- Updated `_async_send_local_file_message` and `_async_send_remote_file_message` to handle Slack's new API requirements, including per-channel uploads.
- Updated dependency from slackclient==2.5.0 to slack-sdk>=3.0.0.
- Improved error handling and logging for channel resolution and file uploads.

* Fix test to use AsyncWebClient for Slack authentication flow

* Fix Slack authentication URL by removing the www subdomain

* Refactor Slack file upload functionality and add utility for file uploads
2025-01-19 21:09:04 +01:00

63 lines
2.2 KiB
Python

"""Utils for the Slack integration."""
import logging
import aiofiles
from slack_sdk.errors import SlackApiError
from slack_sdk.web.async_client import AsyncWebClient
_LOGGER = logging.getLogger(__name__)
async def upload_file_to_slack(
client: AsyncWebClient,
channel_ids: list[str | None],
file_content: bytes | str | None,
filename: str,
title: str | None,
message: str,
thread_ts: str | None,
file_path: str | None = None, # Allow passing a file path
) -> None:
"""Upload a file to Slack for the specified channel IDs.
Args:
client (AsyncWebClient): The Slack WebClient instance.
channel_ids (list[str | None]): List of channel IDs to upload the file to.
file_content (Union[bytes, str, None]): Content of the file (local or remote). If None, file_path is used.
filename (str): The file's name.
title (str | None): Title of the file in Slack.
message (str): Initial comment to accompany the file.
thread_ts (str | None): Thread timestamp for threading messages.
file_path (str | None): Path to the local file to be read if file_content is None.
Raises:
SlackApiError: If the Slack API call fails.
OSError: If there is an error reading the file.
"""
if file_content is None and file_path:
# Read file asynchronously if file_content is not provided
try:
async with aiofiles.open(file_path, "rb") as file:
file_content = await file.read()
except OSError as os_err:
_LOGGER.error("Error reading file %s: %r", file_path, os_err)
return
for channel_id in channel_ids:
try:
await client.files_upload_v2(
channel=channel_id,
file=file_content,
filename=filename,
title=title or filename,
initial_comment=message,
thread_ts=thread_ts or "",
)
_LOGGER.info("Successfully uploaded file to channel %s", channel_id)
except SlackApiError as err:
_LOGGER.error(
"Error while uploading file to channel %s: %r", channel_id, err
)