-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLINEWebhook.php
More file actions
117 lines (105 loc) · 3.37 KB
/
LINEWebhook.php
File metadata and controls
117 lines (105 loc) · 3.37 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/*!
* @file LINEWebhook.php
* @author Sensu Development Team
* @date 2018/02/24
* @brief LINE用Sensuクライアント
*/
require_once __DIR__.'/Config.php';
require_once __DIR__.'/SensuClient.php';
require __DIR__.'/vendor/autoload.php';
class LINEWebhook
{
/*!
* @brief SensuプラットフォームAPIクライアント
*/
private $sensu;
/*!
* @brief LINE APIクライアント
*/
private $line;
/*!
* @brief コンストラクタ
*/
public function __construct()
{
$this->sensu = new \SensuDevelopmentTeam\SensuClient(Config::SENSU_PLATFORM_API_KEY);
$http_client = new \LINE\LINEBot\HTTPClient\CurlHTTPClient(Config::LINE_API_CHANNEL_ACCESS_TOKEN);
$this->line = new \LINE\LINEBot($http_client, ['channelSecret' => Config::LINE_API_CHANNEL_SECRET]);
}
/*!
* @brief フック
*/
public function hook()
{
// 受信したデータをパース
$request = file_get_contents('php://input');
// ヘッダを検査
if (!isset(getallheaders()['X-Line-Signature']))
{
return;
}
$events = $this->line->parseEventRequest($request, getallheaders()['X-Line-Signature']);
foreach ($events as $event)
{
if (!($event instanceof \LINE\LINEBot\Event\MessageEvent))
{
continue;
}
if (!($event instanceof \LINE\LINEBot\Event\MessageEvent\TextMessage))
{
continue;
}
// 接頭辞
$prefix = './';
// 本文の先頭が接頭辞でなければ中止
if (strncmp($event->getText(), $prefix, strlen($prefix)))
{
return;
}
// 接頭辞を削除
$command = substr($event->getText(), strlen($prefix), strlen($event->getText()) - strlen($prefix));
// 命令を分解
$command = self::getCommandFromText($command);
// 投げ銭コマンド(無効)
if (isset($command[0]) && strcasecmp($command[0], 'tip') == 0)
{
if (isset($command[3]))
{
$command[3] = '';
}
}
// 命令を送信
$result = $this->sensu->command($event->getUserId(), $command);
// 表示用メッセージが設定されていなければ内部エラー
if (!isset($result->message))
{
$this->line->replyText($event->getReplyToken(), "内部エラーが発生しました。\nAn internal error occurred.");
return;
}
// 返信
$this->line->replyText($event->getReplyToken(), $result->message);
}
}
/*!
* @brief 本文より命令を取得
* @param $test 本文
* @return 命令
*/
private static function getCommandFromText($text)
{
$command = htmlspecialchars_decode($text, ENT_NOQUOTES);
$result = preg_split('/[ \n](?=(?:[^\\"]*\\"[^\\"]*\\")*(?![^\\"]*\\"))/', $command, -1, PREG_SPLIT_NO_EMPTY);
$result = str_replace('"', '', $result);
return $result;
}
}
try
{
$webhook = new LINEWebhook();
$webhook->hook();
}
catch (Exception $e)
{
// Webhook再リクエスト防止の為何もしない
}