LINE Bot
先來個 LINE BOT 吧
申請帳號
先到官網後台 https://developers.line.me/channels/
(因為只有限量10000個,很可能已經被搶光囉。)
依照下面指示動作
LINE Business Center
建立商業帳號
輸入名稱與使用照片
BOT API Trial Account
開始
使用
設定
點選 Edit
輸入 Callback URL (一定要https)
例如: https://www.example.com/line_bot.php (參考Https架設)
保存 SAVE
line_bot.php
開一個新的 .php 文件 (line_bot.php)
<?php
/* 輸入申請的Line Developers 資料 */
$channel_id = ""; // 由 LINE Bot 頁面取得
$channel_secret = ""; // 由 LINE Bot 頁面取得
$mid = ""; // 由 LINE Bot 頁面取得
// 取得資料
$receive = json_decode(file_get_contents("php://input"));
$text = $receive->result{0}->content->text; // 傳來文字
$from = $receive->result[0]->content->from; // 傳送者
$content_type = $receive->result[0]->content->contentType; //內容類型 1.文字 2.照片 3.影片 ....
$header = ["Content-Type: application/json; charser=UTF-8", "X-Line-ChannelID:" . $channel_id, "X-Line-ChannelSecret:" . $channel_secret, "X-Line-Trusted-User-With-ACL:" . $mid];
if($content_type!=''){
// 防止攻擊function,可先忽略
// include_once('remove_xss.php');
// $RemoveXSS=new RemoveXSS();
// $text=$RemoveXSS->RemoveXSS($text);
// 回覆文字
$message = getContentType($content_type,$text);
// 送出
sendMessage($header, $from, $message);
}
//這裡幾乎都是照官方的 "toChannel" => 1383378250, "eventType" => "138311608800106203" 都不需更改
//需要注意的只有: "to"給誰 、 "contentType"內容類別 跟 "text" (因為contentType=1)
function sendMessage($header, $to, $message) {
$url = "https://trialbot-api.line.me/v1/events";
$data = ["to" => [$to], "toChannel" => 1383378250, "eventType" => "138311608800106203", "content" => ["contentType" => 1, "toType" => 1, "text" => $message]];
$context = stream_context_create(array(
"http" => array("method" => "POST", "header" => implode(PHP_EOL, $header), "content" => json_encode($data), "ignore_errors" => true)
));
// 送出
file_get_contents($url, false, $context);
}
// 這裡可以做很多事
function getContentType($value,$text) {
switch($value) {
case 1 :
$content_type = $text."是吧 好的 "; // 回應: "(你說的文字)是吧 好的"
break;
default:
$content_type = "你說甚麼我聽不懂"; // 回應: "你說甚麼我聽不懂"
break;
}
return $content_type;
}
驗證
回到 https://developers.line.me/channels/
按下 VERIFY 出現 success 就成功好了
超簡單啊