Search code examples
c#botframeworkslack

How can a bot start a thread in Slack


I am trying to have my bot framework bot reply to a user by starting a thread. This way I can keep who the bot is talking to when in a channel with many people straight.

According to the slack documentation what I need to do is set the thread_ts property to the ts property sent to my bot. I have tried a few things and have been unable to accomplish this. This is the most concise example I have:

var reply = (Activity)activity;
reply = reply.CreateReply("reply");

reply.ChannelData = JObject.Parse($"{{thread_ts:'{ts}'}}");
await context.PostAsync(reply);

This is not working for me.


Solution

  • You will need to set the text in the ChannelData in order for your bot to reply in the thread. Right now you are setting it in your activity reply = reply.CreateReply("reply"); All you need to do is this:

    reply.ChannelData = JObject.Parse($"{{text:'reply', thread_ts:'{ts}'}}");
    

    here is a full working method from a dialog:

    public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
    {
        var activity = await argument;
        var ts = activity.ChannelData?.SlackMessage?.thread_ts
                 ?? activity.ChannelData?.SlackMessage?.ts
                 ?? activity.ChannelData?.SlackMessage["event"].thread_ts
                 ?? activity.ChannelData?.SlackMessage["event"].ts;
    
        var reply = (Activity)activity;
        reply = reply.CreateReply();
    
        reply.ChannelData = JObject.Parse($"{{text:'reply', thread_ts:'{ts}'}}");
        await context.PostAsync(reply);
    }