Skip to content

Instantly share code, notes, and snippets.

@matishsiao
Forked from uberswe/slack.php
Created February 24, 2017 08:21
Show Gist options
  • Save matishsiao/d4a98492c6c9bc13bff5713c9498b174 to your computer and use it in GitHub Desktop.
Save matishsiao/d4a98492c6c9bc13bff5713c9498b174 to your computer and use it in GitHub Desktop.
Post updates to Slack with PHP
$message = "Hello this is a test!"; // The message you would like to send
$parameters = array(
'channel' => 'testing', // Simply type your channel name, make sure your bot is invited
'text' => html_entity_decode($message), // Good idea to decode
'as_user' => 'true');
// Use groups.list if you run into channel_not_found issues with private channels, make sure your bot is invited
$url = "https://slack.com/api/"."chat.postMessage"; // chat.postMessage is the method
$parameters['token'] = "MY-API-TOKEN"; // replace MY-API-TOKEN with the API Token for your bot
if (function_exists('curl_version')){
// Use curl if we have it installed
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
$result = curl_exec($ch);
curl_close($ch);
} else {
// If we don't have curl we use file_get_contents
$post_data = http_build_query($parameters);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'content' => $post_data,
'method' => 'POST',
'protocol_version' => 1.1,
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Content-length: " . strlen($post_data) . "\r\n" .
"Connection: close\r\n"
),
)));
}
// Echo our result, this is returned as a json encoded string. Use json_decode($result, true) to turn it into an array
echo $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment