简体   繁体   中英

Replying to a Thread using Slack Python Webhook API

I'm creating a Python script to send messages to a slack channel. The message itself gets delivered fine, however when I try to start a thread and send replies to the thread, I am unable to get it working. The thread replies appear as a new parent message.

I'm using the slack-python-webhook module found at https://github.com/satoshi03/slack-python-webhook

import slackweb
import json
slack = slackweb.Slack(
    url="https://hooks.slack.com/services/XXXX/XXXX/XXXXXX")


attachment = [{"text": "This is TEXT",
              "ts": "1564629129"
              }]


print(json.dumps(attachment))
slack.notify(attachments=attachment)

attachment = [{"text": "This is Thread REPLY",
              "thread_ts": "1564629129",
              "thread_ts": "1564629130"
              }]

print(json.dumps(attachment))
slack.notify(attachments=attachment)

I'd like to know what needs to be changed on the above code snippet so the second message will appear as a thread reply.

Your code won't work, because webhooks do not support threads. If you want to reply to threads you need to use the API methods for posting message (eg chat.postMessage ).

That means you probably also need to use a different library, since the one mentioned in your question appears to only support webhooks.

Also your syntax is not correct. thread_ts is not a property of an attachment, but a parameter of a API method like channel .

I would recommend to check out the slackclient . It's the official Python library from Slack and has full support for all API methods incl. threads.

Here is how to reply to a thread with slackclient:

import slack
import os

# init slack client with access token
client = slack.WebClient(token=os.environ['SLACK_TOKEN'])

# reply to a thread
response = client.chat_postMessage(
    channel="general",
    text="This is a reply",
    thread_ts="1561764011.015500"
)
assert response["ok"]
print(response)

See also this official guide about threads and this answer about webhooks and threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM