Search code examples
phpapipermissionsslackslack-api

Using a bot to post a message to Slack


I have a slack instance where I'm the only user (so far). I'm attempting to post a simple "hello world" message using the bot account so the message does not show up as coming from my account.

$url = "https://slack.com/api/chat.postMessage?token=xoxb-XXXXXX&channel=general&text=hello%20world";
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, TRUE); 
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$head = curl_exec($ch); 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
curl_close($ch); 

When I post using the xoxp-XXXX oAuth token it works great, except that it comes from my account. When I post using the xoxb-XXXX token, I receive a "error": "not_in_channel" reply. And I've received chat:write:user user scope error - though I've granted all 50 permissions to my app.

How do I set my slack application to allow this write to occur from the bot account on the application rather than from my account?


Solution

  • The solution is simple.

    1. Your bot needs the bot scope as a bot user.
    2. Ensure you are using the bot access token
    3. Invite the bot to join the channel