-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlack.php
More file actions
83 lines (72 loc) · 2.67 KB
/
Slack.php
File metadata and controls
83 lines (72 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace OpenSource;
/*
This was coded by Lewis Brindley under the VGDevelopment Organisation.
By the MIT License, you can do whatever you want with this file with no restrictions unless implied in the License.
You cannot however remove this commented in citation of the authorship of the file. You must add this to any file using code from this file.
*/
class Slack {
const URL = "Put your URL here";
const HEADER = "Content-Type: application/x-www-form-urlencoded";
const DEFAULT_CHANNEL = "bot";
private static function convertStringToSlackJSON(string $string): string {
$replace = [
'"' => "\""
];
$slackjson = strtr($string, $replace);
return $slackjson;
}
/**
* Sends text messages to a slack channel. Default parameter for $channel is set to self::DEFAULT_CHANNEL .
*
* @param string $text
* @param string $channel
* @return boolean
*/
public static function sendTextMessage(string $text, string $channel = self::DEFAULT_CHANNEL): bool {
$post = '"text": "' . $text . '"';
$string = self::convertStringToSlackJSON($post);
$config = self::makeConfig($string, $channel);
return self::sendCURLRequest($config);
}
private static function makeConfig(string $post, string $channel): array {
return [
"URL" => self::URL,
"Header" => self::HEADER,
"Channel" => self::convertStringToSlackJSON('"channel": "' . $channel . '"'),
"Post" => $post
];
}
private static function sendCURLRequest(array $config): bool {
$format = self::formatEOL([$config["Post"], "---", $config["Channel"]]);
$package = self::makeJSONPackage($format);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $config["URL"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, $package);
curl_setopt($curl, CURLOPT_HTTPHEADER, [$config["Header"]]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
$r = curl_exec($curl);
if (curl_errno($curl)) {
var_dump("Error:" . curl_error($curl) . "\n");
}
curl_close($curl);
if ($r === "ok") {
return true;
}
return false;
}
private static function makeJSONPackage(string $convert): string {
return "{
" . $convert .
"}";
}
private static function formatEOL(array $los): string {
$string = implode($los);
$eol = [
"---" => ",
"
];
return strtr($string, $eol);
}
}