I'm trying to post on behalf of a user to slack. Created a slack app and are redirecting to:
That all goes well. When I fetch a bearer token and use that for posting to a specific slack channel it's not posted as the user but as my slack app.
$res = Http::asForm()->withToken('xoxe.xoxb-1-MS0yLTE2NjE1MzEyMDk5LTU1ODIyODc2ODU4NTctNTU5MzgwNjgxNjU5Mi01NTY5OTg1ODg2NjQzLTIzYzg2MzM1YTVmNGQwMDMyMjNkY2ExOTA5M2QzOIwZmU5YTk1ZjY4M2FjNjg4ZDA1NzBjNTI3MmI2Y2I')
->withHeaders([
'Content-type' => 'application/x-www-form-urlencoded;charset=utf-8'
])->post('https://slack.com/api/chat.postMessage', [
'channel' => 'C5GS2B67Q',
'text' => 'Hello world',
]);
Why is this the case and how can I make sure it's posted by the user.
According to chatGPT:
Based on the code snippet you provided, it appears that you are using an access token ('xoxe.xoxb-1-...') associated with an app instead of a user token. When you use an app token, the message will be posted as the app itself rather than as a user.
To post messages as a user, you need to obtain a user token instead of an app token. User tokens are specific to individual users and allow your application to act on their behalf.
To obtain a user token, you typically need to follow an authentication process such as the OAuth flow provided by Slack. Once you have the user token, you can use it in your code snippet to post messages as that user.
Here's an example of how you can obtain a user token using the OAuth flow:
Redirect the user to Slack's OAuth authorization page, specifying the necessary scopes (chat:write.user) for posting messages as a user. After the user authorizes your application, Slack will redirect back to your specified redirect URL with a temporary authorization code. Exchange the authorization code for a user token by making a request to Slack's token API (https://slack.com/api/oauth.v2.access), providing the code, client ID, client secret, and redirect URL. Once you have the user token, you can use it in your code snippet to post messages as a user in Slack.
But there is no chat:write.user
scope?
There are two ways to post on behalf of a user on the Slack platform, and one of them is more of a "mock user" than the user itself.
Instead of using your bot token, for each user you want to post on behalf of, send the user through the OAuth installation flow and ask for chat:write:user
as a user_scope
. Store these tokens separate from your bot/app tokens. Use this token when posting on behalf of the user instead of your bot token.
During the installation flow, ask for the scope
of chat:write.customize
to be added to your bot token. You can then use additional arguments to chat.postMessage
to set the display name and avatar of the message being posted. Your bot user is still the user posting the message, it's just customized to look like another user.