使用 Laravel 9.0 建立 LINE Bot 聊天機器人

做法

建立專案。

1
2
laravel new line-bot-laravel
cd line-bot-laravel

安裝 LINE Bot SDK 套件。

1
composer require linecorp/line-bot-sdk:^7.6

安裝 laravel-dump-server 測試工具。

1
composer require --dev beyondcode/laravel-dump-server

修改 .env 檔。

1
2
LINE_CHANNEL_ACCESS_TOKEN=line-channel-access-token
LINE_CHANNEL_SECRET=line-channel-secret

建立控制器。

1
artisan make:controller WebhookController

修改 WebhookController.php 檔。

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
namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use LINE\LINEBot;
use LINE\LINEBot\Constant\HTTPHeader;
use LINE\LINEBot\Event\MessageEvent\TextMessage;
use LINE\LINEBot\HTTPClient\CurlHTTPClient;
use Symfony\Component\HttpFoundation\Response;

class WebhookController extends Controller
{
function handleEvents(Request $request) {
$channelToken = env('LINE_CHANNEL_ACCESS_TOKEN');
$channelSecret = env('LINE_CHANNEL_SECRET');

$httpClient = new CurlHTTPClient($channelToken);
$bot = new LINEBot($httpClient, ['channelSecret' => $channelSecret]);

$signature = $request->header(HTTPHeader::LINE_SIGNATURE);
if (!$signature) {
return response()->json(null, Response::HTTP_BAD_REQUEST);
}

try {
$events = $bot->parseEventRequest($request->getContent(), $signature);
} catch (Exception) {
return response()->json(null, Response::HTTP_BAD_REQUEST);
}

collect($events)
->filter(fn ($event) => $event instanceof TextMessage)
->each(function ($event) use ($bot) {
$replyText = $event->getText();
try {
$bot->replyText($event->getReplyToken(), $replyText);
} catch (Exception) {
response()->json(null, Response::HTTP_INTERNAL_SERVER_ERROR);
}
});

return response()->json([], Response::HTTP_OK);
}
}

修改 routes/api.php 檔。

1
2
3
4
use App\Http\Controllers\WebhookController;
use Illuminate\Support\Facades\Route;

Route::post('/webhook', [WebhookController::class, 'handleEvents']);

啟動日誌工具。

1
artisan dump-server

啟動本地伺服器。

1
artisan server

啟動代理伺服器。

1
ngrok http 8000

在 LINE 平台上,修改 Webhook URL:https://xxx.jp.ngrok.io/api/webhook

認證 Webhook URL,並使用手機測試訊息。

程式碼

參考資料