How to Message To DM Channel ID Using Slack API chatPostMessage

956 Views Asked by At

I created a slack app and as part of the OAuth flow while installing the app, if I select a public channel I receive a channel id starting with C03XXXXXXXX and if I select a person I received a channel id starting with D035XXXXXXX as shown below.

{
"ok": true,
"app_id": "XYZ1234",
"authed_user": {
    "id": "U0XXXXXXXXX"
},
"scope": "app_mentions:read,channels:join,groups:read,groups:write,chat:write,links:read,links:write,channels:manage,channels:read,chat:write.public,im:read,im:write,commands,users.profile:read,team:read,chat:write.customize,incoming-webhook",
"token_type": "bot",
"access_token": "xoxb-308XXX0XXX2XX-33XXXXX0XXXXX-XXXXXXXXXXX",
"bot_user_id": "U0XXXXXXXXX",
"team": {
    "id": "T032XXXXXXX",
    "name": "XXXXXXPersonal"
},
"enterprise": null,
"is_enterprise_install": false,
"incoming_webhook": {
    "channel": "@john201",
    "channel_id": "D035XXXXXXX",
    "configuration_url": "https:\/\/XXXXXXXgroup.slack.com\/services\/B03XXXXXXX",
    "url": "https:\/\/hooks.slack.com\/services\/T032XXXXXXX\/B03XXXXXXX\/VkVEnXXXXXXwr7ykts1odctk7"
}

}

I am able to send messages to channels using chat.postMessage using channelID C03XXXXXXXX(Which is channel by nature) but when i try to post a message to user using chat.postMessage by passing channelID starting with D035XXXXXXX . I get response saying channel_not_found.

However if i pass the @john201 as channel id in chat.postMessage , it successfully sends the message and its available under messages tab of App. But the use of username is deprecated as per slack documentation https://api.slack.com/methods/chat.postMessage

Passing a "username" as a channel value is deprecated, along with the whole concept of usernames on Slack. Please always use channel-like IDs instead to make sure your message gets to where it's going.

My Question is :

How do i send the messages to Channels starting with D like D035XXXXXXX using botToken and chat.postMessage method

1

There are 1 best solutions below

0
On

Channels that start with the letter D are direct messages between a user and another single entity, user or bot.

For that reason, your bot is only able to post messages via the chat.postMessage method in DMs that it is a part of. If your bot tries to send a message to a DM it is not a part of, since it doesn't have visibility into that channel, you'll receive the channel_not_found error.

Now if your end goal is to create a DM betwen your bot and a user, the best way to do this would be to call the conversations.open method and then use the channel ID from that response to call chat.postMessage.