環境
- 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の説明を簡単に探してみましたが、見つかりませんでした。