skip to Main Content

We post a message to a slack channel every time a customer does a specific task. We want to change the bot Icon based on what is being posted in the channel.

Is this possible?

public static function send_to_slack($message,$title = null){

    $body = array();
    $body['text'] = '';
    $body['icon_url'] = '';
    if(!empty($title)) $body['text'] .= "*$title*n";
    $body['text'] .= $message;

    $iconURL = "https://img.icons8.com/emoji/96/000000/penguin--v2.png";

    $body['icon_url'] .= $iconURL;

    $json = json_encode($body);
    
    //Test Slack Channel
    $slack = "SLACKURL"

    $response = wp_remote_post( $slack, array(
        'method' => 'POST',
        'body' => $json,
        )
    );

    if ( is_wp_error( $response ) ) {
        return true;
    } else {
        return true;
    }

}

2

Answers


  1. Chosen as BEST ANSWER

    Found the correct way. Make sure you enable chat:write.customize in Slack oAuth Scope.

     public static function send_to_slack($message,$title = null){
    
        $ch = curl_init("https://slack.com/api/chat.postMessage");
        $data = http_build_query([
            "token" => "BOT-TOKEN",
            "channel" => "CHANNELID", //"#mychannel",
            "text" => $message, //"Hello, Foo-Bar channel message.",
            "username" => "MySlackBot",
            "icon_url" => $iconURL
        ]);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
    
        return $result;
    
    }
    

  2. From Slack:
    You cannot override the default channel (chosen by the user who installed your app), username, or icon when you’re using Incoming Webhooks to post messages. Instead, these values will always inherit from the associated Slack app configuration.

    *** UPDATE
    I just ran into this situation. My old app was using the old web hooks. I had to create a new integration and ran into this issue. The simple solution is to install the slack app called "Incoming Webhooks". It’s made by slack. It will allow you to generate an older style webhook that will allow you to post to any channel.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search