Skip to content

Instantly share code, notes, and snippets.

@wgroenewold
Last active August 7, 2018 06:44
Show Gist options
  • Save wgroenewold/04c15c3a89455a55371f74bceef4e9a0 to your computer and use it in GitHub Desktop.
Save wgroenewold/04c15c3a89455a55371f74bceef4e9a0 to your computer and use it in GitHub Desktop.
Topicus Keyhub webhooks to Slack
<?php
/**
* Class keyhub. Houses everything to bind to Keyhub.
*/
class glue_keyhub{
private $slack_appurl;
/**
* glue_keyhub constructor.
*/
public function __construct(){
$this->slack_appurl = 'https://hooks.slack.com/services/xxxx';
}
public function keyhub_to_slack($data){
$formatted = $this->format_webhook($data);
$response = $this->send_to_slack($formatted);
//@todo mention users in Slack.
//@todo Make interactive to right Keyhub page
//@todo admin lookup in Keyhub for notification
echo $response;
}
public function format_webhook($data){
$formatted = array();
if(isset($data['type']) && $data['type']){
if(isset($data['account']['name']) && $data['account']['name']){
$formatted['name'] = ucfirst($data['account']['name']);
}
if(isset($data['group']['name']) && $data['group']['name']){
$formatted['group'] = $data['group']['name'];
}
if(isset($data['byParty']['name']) && $data['byParty']['name']){
$formatted['by'] = ucfirst($data['byParty']['name']);
}
if(isset($data['parameter1']) && $data['parameter1']){
$formatted['param1'] = $data['parameter1'];
}
switch($data['type']){
case 'ACCOUNT_CREATED':
$text = 'Hoezee, ook %s speelt mee!';
$formatted['text'] = sprintf($text, $formatted['name']);
break;
case 'JOIN_GROUP_REQUESTED':
$text = '%s wil in %s. Kan iemand dat regelen?';
$formatted['text'] = sprintf($text, $formatted['name'], $formatted['group']);
break;
case 'JOIN_GROUP_ACCEPTED':
$text = '%s mag nu in %s omdat %s "%s" een goede reden vond.';
$formatted['text'] = sprintf($text, $formatted['name'], $formatted['group'], $formatted['by'], $formatted['param1']);
break;
case 'JOIN_GROUP_DECLINED':
$text = 'Het verzoek van %s om in %s te mogen is afgewezen door %s om "%s"';
$formatted['text'] = sprintf($text, $formatted['name'], $formatted['group'], $formatted['by'], $formatted['param1']);
break;
default: $formatted = false;
}
}
return $formatted;
}
public function send_to_slack($data){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $this->slack_appurl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return "cURL Error #:" . $err;
} else {
return $response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment