[PHP]LineBot應聲蟲

一隻很簡單的Line對話機器人,來試試吧!
程式碼:
<?php
//你的LINE Messaging API Channel access token
$channelAccessToken = 'Your Channel access token';

$bodyMsg = file_get_contents('php://input');
$obj = json_decode($bodyMsg, true);

//接收事件與回復
foreach ($obj['events'] as &$event) {
    //判斷發生的事件
    switch($event['type']){
        case 'follow': //加好友時
                $message = '您好!我是學人精!';
        break;
        case 'message'; //有訊息時
            $message = $event['message'];
            $message = strtolower($message['text']); //回傳接收到的文字,或是改成要回復的文字
        break;
    }

    //發送訊息
    $PostData = [
        'replyToken' => $event['replyToken'],
        'messages' => [
            [
                'type' => 'text',
                'text' => $message
            ]
        ]
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/reply');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($PostData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $channelAccessToken
    ]);
    $result = curl_exec($ch);
    curl_close($ch);
} 
?>

加入好友跟他聊兩句,看看效果。