Skip to content

Instantly share code, notes, and snippets.

@ronnywang
Last active November 27, 2019 15:57
Show Gist options
  • Save ronnywang/08d07a68b9ad2204a0fb77e12a9b0557 to your computer and use it in GitHub Desktop.
Save ronnywang/08d07a68b9ad2204a0fb77e12a9b0557 to your computer and use it in GitHub Desktop.
<?php
// 1. 到 https://developers.line.biz/console/channel/new?type=messaging-api 新增 Messaging API Channel
// 2. 建立完 Channel 後,到 Messaging API 的分頁,往下拉到 Channel access token,按下 Issue 按鈕產生 token,並將產生的 token 存到下面的 「___token放這裡___」
// 2. 往上拉到 Webhook URL,輸入一個對外可連的到的網址,該網址是用這隻程式跑起來的(必須要是 https 的)
$access_token = '___token放這裡___';
$data = json_decode(file_get_contents('php://input'));
// 把 line server 丟給我的內容丟進 debug 檔中,以方便之後 debug
file_put_contents("debug", json_encode(array(
'post' => $_POST,
'data' => $data,
'time' => time(),
), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
// 回傳一個空白的 json 資訊,讓 line 至少知道這是成功的連線
echo json_encode(array(
));
// 處理 line 傳過來的 event
foreach ($data->events as $event) {
// 用 error_log 把 line 傳過來的事件先完整印出來
error_log("got : " . json_encode($event, JSON_UNESCAPED_UNICODE));
// 只處理 type=message 的
if ($event->type != 'message') {
continue;
}
$message = $event->message;
$replies = array();
// 如果傳來的是 message->type = location 表示傳地理資訊
if ($message->type == 'location') {
$replies[] = array(
"type" => 'text',
'text' => "你的地點在 {$message->title} ({$message->latitude}, {$message->longitude})",
);
// 如果傳來的是 message->type = text 表示傳純文字
} elseif ($message->type == 'text') {
$replies[] = array(
"type" => 'text',
'text' => "你剛丟給我 {$message->text}",
'quickReply' => array(
'items' => array(
// 一般按鈕
array('type' => 'action', 'action' => array('type' => 'message', 'label' => '選項1', 'text' => '哇哈哈')),
// 要求使用者回傳地理位置的按鈕
array('type' => 'action', 'action' => array('type' => 'location', 'label' => '你在哪')),
// 讓使用者選擇生日的按鈕
array('type' => 'action', 'action' => array('type' => 'datetimepicker', 'label' => '給我你的生日', 'mode' => 'date', 'data' => 'birth')),
// 跟使用者要求照片的按鈕
array('type' => 'action', 'action' => array('type' => 'camera', 'label' => '給我照片')),
),
),
);
// 其他情況
} else {
$replies[] = array(
"type" => 'text',
'text' => '你好,我是機器人,我不知道我要回你什麼,因為轉型正義教育黑客松的夥伴們還在幫我想我要回你們什麼',
);
}
// 把上面收集的要回應給使用者的動作丟給使用者
$curl = curl_init('https://api.line.me/v2/bot/message/reply');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $access_token,
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(array(
'replyToken' => $event->replyToken,
'messages' => $replies,
)));
$content = curl_exec($curl);
error_log($content);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment