Skip to content

Instantly share code, notes, and snippets.

@r0adkll
Last active December 15, 2015 14:41
Show Gist options
  • Save r0adkll/fa5053f4848e1169f50b to your computer and use it in GitHub Desktop.
Save r0adkll/fa5053f4848e1169f50b to your computer and use it in GitHub Desktop.
Slack Incoming Webhook script for lolcommits plugin "uploldz"
<?php
/***************************************************************************************************
*
* Step 1: Save the sent file locally on the server
*
*/
$file_name = basename($_FILES["file"]["name"]);
$target_file = "images/".basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// Pull the information from the POST request from 'uploldz' plugin
$repo = $_POST["repo"];
$message = $_POST["message"];
$author_name = $_POST["author_name"];
$author_email = $_POST["author_email"];
$sha = $_POST["sha"];
$key = $_POST["key"];
// Form URLs for the slack request
$imageUrl = "http://example.com/lolcommits/".$target_file;
$slackUrl = "https://hooks.slack.com/services/<SLACK_INCOMING_WEBHOOK_URL>";
/***************************************************************************************************
*
* Step 2: Build the Slack Payload
*
*/
// Build the message fields
$fieldRepo["title"] = "Repository";
$fieldRepo["value"] = $key;
$fieldRepo["short"] = true;
$fieldHash["title"] = "Commit";
$fieldHash["value"] = $sha;
$fieldHash["short"] = true;
$fields = array($fieldRepo, $fieldHash);
$attachment["fields"] = $fields;
// Build the basic metadata
$attachment["pretext"] = "New lolcommit from ".$author_name;
$attachment["text"] = $message;
$attachment["title"] = $file_name;
$attachment["color"] = "#52AADD";
$attachment["image_url"] = $imageUrl;
// Construct & Encode
$attachments = array($attachment);
$payload["attachments"] = $attachments;
$postdata = json_encode($payload);
/***************************************************************************************************
*
* Step 3: Begin the POST request to slack using cURL and Slack's Incoming Webhook api's
*
*/
// Get cURL resource
$ch = curl_init();
// Set url
curl_setopt($ch, CURLOPT_URL, $slackUrl);
// Set method
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set body
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
// Send the request & save response to $resp
$resp = curl_exec($ch);
if(!$resp) {
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
echo "Response HTTP Status Code : " . curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "\nResponse HTTP Body : " . $resp;
}
// Close request to clear up some resources
curl_close($ch);
} else {
echo "Sorry, there was an error uploading your file.";
}
?>
@lajlev
Copy link

lajlev commented Aug 19, 2015

Could you explain how I'll set it up?

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