1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Slack: `files_upload_v2`でアップロードしたファイルに対してスレッドで返信する

Posted at

環境

  • Python 3.12.4
  • slack_sdk 3.32.0

内容

Slackでスレッドに返信する場合、タイムスタンプ(ts)を取得して、それをchat_postMessageの引数に渡します。

sample1.py
from slack_sdk import WebClient
import os
client = WebClient(token=os.environ['SLACK_API_TOKEN'])
channel_id = "YOUR_CHANNEL_ID"

response = client.chat_postMessage(channel=channel_id, text="parent message")

thread_ts = response["ts"]
print(f"{thread_ts=}")

client.chat_postMessage(channel=channel_id, text="thread message", thread_ts=thread_ts)
$ python sample1.py
thread_ts='1726125065.150719'

files_upload_v2メソッドでファイルをアップロードして、それに対してスレッドを返信する場合は、以下のようにtsを取得する必要があります。

sample2.py
from slack_sdk import WebClient
import os
client = WebClient(token=os.environ['SLACK_API_TOKEN'])
channel_id = "YOUR_CHANNEL_ID"

response = client.files_upload_v2(channel=channel_id, file="hello.txt")
thread_ts = response["file"]["shares"]["public"][channel_id][0]["ts"]
print(f"{response["file"]["shares"]=}")

client.chat_postMessage(channel=channel_id, text="thread message", thread_ts=thread_ts)
$ python sample2.py
response["file"]["shares"]={'public': {'YOUR_CHANNEL_ID': [{'reply_users': [], 'reply_users_count': 0, 'reply_count': 0, 'ts': '1726125462.396909', 'channel_name': 'YOUR_CHANNEL_NAME', 'team_id': 'TEAM_ID', 'share_user_id': 'SHARE_USER_ID', 'source': 'UNKNOWN'}]}}

なお、files_upload_v2メソッドのレスポンスは https://api.slack.com/methods/files.completeUploadExternal APIのレスポンスになります。

分からなかったこと

files_upload_v2メソッドのレスポンスに対して、response["file"]["shares"]の結果が空dictのときがありました。
再現条件が分からなかったため、原因は不明です。
response["file"]["shares"] APIの説明を簡単に探してみましたが、見つかりませんでした。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?