Search code examples
botsslackslack-api

Slack bot can share file but not post message while not in channel


I am especially new to slack web api and bots. My question is what is the reason stands behind the inability of bot users to post messages into a channel, until they are implicitly invited, despite the fact that on behalf of a bot we can upload a file to it. Below are couple of code snippets

i've requested the following scopes chat:write:user bot files:write:user

when I upload a file with a bot token obtained via OAuth2 the file is present in a channel with a bot icon and name

.token(BOT_TOKEN)
            .title("title")
            .content("content")
            .channels(Collections.singletonList("#channel"))
            .build();

but when I using the same approach trying to post a message to the same channel I get an error not_in_channel

.token(BOT_TOKEN)
            .channel("#channel")
            .text("text")
            .asUser(true)

i know it is working without passing as user true however it sets the default application icon and name not the bots one.

Is there a way to publish messages/upload files to a channel without users interaction after the authentication with a bot.


Solution

  • The issue here seams to be that the icon and username are different when first posting a message to a channel as bot and later uploading a file as bot. This seams to be a known issue for Slack. This is what is said in the documentation for chat.postMessage for as_user is false:

    Note: In the Slack App cases above, it would certainly make more sense for your application's name to be the default username associated with your app. This inconsistent behavior will be corrected. Of course, you can still name your bot "bot," if that is your bot's name.

    But there is a workaround to get the same username and icon. Just set them manually when sending the message, e.g.:

    curl -F token=BOT_TOKEN -F channel=CHANNEL -F text=Hello -F username=NAME_OF_BOT -F icon_url=ICON_URL https://slack.com/api/chat.postMessage