Slack recommends migrating from files_upload()
to files_upload_v2()
for stability relating to large files. However, this change means that you can no longer use something like client.files_upload_v2(channel='@user.name', file=file)
. You can only send to a channel referenced by a channel ID. Is there a way to use the v2 function to send files as a DM (which would appear in the bot’s Messages channel)? The details on v2 are explained here.
from slack_sdk import WebClient
token = MY_TOKEN
client = WebClient(token=token)
# works
response = client.files_upload(channels="@user.name", file="myfile.csv")
# fails
response = client.files_upload_v2(channels="@user.name", file="myfile.csv")
Error:
SlackApiError: The request to the Slack API failed. (url: https://www.slack.com/api/files.completeUploadExternal)
The server responded with: {'ok': False, 'error': 'invalid_arguments', 'response_metadata': {'messages': ['[ERROR] input must match regex pattern: ^[CGD][A-Z0-9]{8,}$ [json-pointer:/channel_id]']}}
you’re not calling the username correctly, try <@{username}>
1
I was doing a similar thing and the Conversation API helped my case.
Using conversations.open API call with “users” field set, gives you the Channel ID for the Messages tab. I haven’t seen it covered by the Python SDK, but making an HTTP request should work.
The response contains the Channel ID you can use:
{
"ok": true,
"no_op": true,
"already_open": true,
"channel": {
"id": "D069C7QFK",
"created": 1460147748,
"is_im": true,
"is_org_shared": false,
"user": "U069C7QF3",
"last_read": "0000000000.000000",
"latest": null,
"unread_count": 0,
"unread_count_display": 0,
"is_open": true,
"priority": 0
}
}
Keep in mind, you need correct scopes AND “Messages” tab needs to be explicitly enabled in the Slack App’s settings.
One option is to use the Python SDK to call conversations_list
to retrieve channel info. With that, create a map to decode the channel name to channel id for the files_upload_v2()
call:
rez = client.conversations_list()
channel_name_to_id_map = {x['name']: x['id'] for x in rez['channels']}
Here is a link to the Slack documentation on conversations_list:
https://api.slack.com/methods/conversations.list
1