Skip to content

Instantly share code, notes, and snippets.

@alexstone
Created March 3, 2014 06:54
Show Gist options
  • Save alexstone/9319715 to your computer and use it in GitHub Desktop.
Save alexstone/9319715 to your computer and use it in GitHub Desktop.
Fire a Slack Notification via CURL
<?php
// (string) $message - message to be passed to Slack
// (string) $room - room in which to write the message, too
// (string) $icon - You can set up custom emoji icons to use with each message
public static function slack($message, $room = "engineering", $icon = ":longbox:") {
$room = ($room) ? $room : "engineering";
$data = "payload=" . json_encode(array(
"channel" => "#{$room}",
"text" => $message,
"icon_emoji" => $icon
));
// You can get your webhook endpoint from your Slack settings
$ch = curl_init("WEBHOOK ENDPOINT GOES HERE");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
// Laravel-specific log writing method
// Log::info("Sent to Slack: " . $message, array('context' => 'Notifications'));
return $result;
}
@bstrackany
Copy link

You can also pass "username" (e.g. "superbot", "stevebot", monkeybot"), which will show as who the message is from.

@jaggedsoft
Copy link

You're awesome for this, thank you.

@pugwonk
Copy link

pugwonk commented Mar 26, 2015

This is superb! Might be worth mentioning that Slack returned "ok" if the message posted successfully, and an error string if it didn't. Also there's a minor bug in this, whereby if $message contains and characters not permitted in POST data (&, @, etc) then the JSON data will be corrupted, so it should be urlencoded. It's a tiny change but, anyway, it's here: https://gist.github.com/pugwonk/fe1c7f849fd9e8049758

@yvonnel098
Copy link

Thank you for the post. Just a note, I ran into SSL Certification error using this script. I get pass it by setting CURLOPT_SSL_VERIFYPEER to false. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

@nadar
Copy link

nadar commented Jun 12, 2015

here is another solution via the slack api:

https://gist.github.com/nadar/68a347d2d1de586e4393

@pugwonk
Copy link

pugwonk commented Jul 7, 2015

I found a way to avoid URL encoding issues with the payload - curl also allows you to pass an associative array for the post parameters rather than a GET-style &-delimited string. If you're getting 'Payload was not valid JSON' messages back from Slack because you have odd characters in your text, you might want to try passing the POST data this way instead. Gist at https://gist.github.com/pugwonk/f2cdd9d83d964627c335

@Kurosar
Copy link

Kurosar commented Sep 29, 2015

How would you add an attachment to that ? I can't figure it out.

@johnny-y-wang
Copy link

Thanks a lot!

@gberthalon
Copy link

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
you save my night yvonnel098

@viacreativedev
Copy link

Thanks for this!

@4foot30
Copy link

4foot30 commented Nov 20, 2016

@pugwonk Hello - I'm having similar URL-encoding issues. I tried your suggestion of curl_setopt($ch, CURLOPT_POSTFIELDS, array('payload' => $data)); which let me pass just about any character through without causing the Slack invalid_payload error - brilliant! :)

But the actual message came through to Slack in url-encoded form instead of readable text :( I think Slack have changed how they handle this since your post.

I'm doing $message = urlencode($message); - if I don't then I can't get proper formatting in the Slack message (it displays \n instead of actually putting in a line-break for example).

Has anyone else spotted anything like this?

Here's my code (roughly!):

            $message = urlencode($message); // Contains things like 'This is the message to the channel:\n\nHere is the second line with some *bold text* hopefully!'

            $channel = '#the-channel-to-post-to';
            $data = 'payload=' . json_encode(array(
                    'channel'  => $channel,
                    'text'     => $message,
            ));

            $url = 'MY_WEBHOOK_URL';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            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);
            if ($result === false) {
                echo 'Curl error: ' . curl_error($ch);
            }

            curl_close($ch);

Thanks :)

@4foot30
Copy link

4foot30 commented Nov 23, 2016

If it helps anyone, I got around most of the encoding problems by passing the parts of my $message through this function:

function htmlReplace($string) {
    // https://api.slack.com/docs/message-formatting#how_to_escape_characters
    // Also use backslashes to escape double quotes/backslashes themselves,
    // that would otherwise break the JSON.
    // (deal with the slashes before the quotes otherwise the escaped quotes would be re-escaped!)
    return str_replace(array('&', '<', '>', '\\', '"'), array('&amp;', '&lt;', '&gt;', '\\\\', '\"'), $string);
}

@jdc-cunningham
Copy link

Thank you

@repsher
Copy link

repsher commented Feb 26, 2017

Thank you!

@barrasme
Copy link

Top job exactly what I was looking for.

@InternetMedicineMan
Copy link

How are you able to set the channel? When I'm giving permission for my app to use the Incoming Webhook, I get a unique URL for every single Channel. I can send the channel all day long, but it's the URL that defines which channel it goes to. Is there a generic URL that I can't find? Or is there a permission I need to create that I am overlooking?

@mosin771098
Copy link

mosin771098 commented Jun 21, 2017

hello
i want to use slack rest api in curl to create a channel not with webhook but that is not working plz help me

@netEmmanuel
Copy link

Those this still work i am getting an error missing_text_or_fallback_or_attachments

@raholiarivelo
Copy link

thanks, it's help me so mush :)

in symfony nexylan / slack-bundle, we use "withIcon" to change the icon but here how to do it ?

@dani3l3
Copy link

dani3l3 commented Jan 31, 2021

Brilliant, thanks. emoji icons aren't working for me but, besides that, it's a very useful function!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment