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

做法

建立專案。

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

安裝 LINE Bot SDK 套件。

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

修改 .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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use LINE\Clients\MessagingApi\Api\MessagingApiApi;
use LINE\Clients\MessagingApi\Configuration;
use LINE\Clients\MessagingApi\Model\ReplyMessageRequest;
use LINE\Clients\MessagingApi\Model\TextMessage;
use LINE\Constants\HTTPHeader;
use LINE\Constants\MessageType;
use LINE\Parser\EventRequestParser;
use LINE\Parser\Exception\InvalidEventRequestException;
use LINE\Parser\Exception\InvalidSignatureException;
use LINE\Webhook\Model\MessageEvent;
use LINE\Webhook\Model\TextMessageContent;
use Symfony\Component\HttpFoundation\Response;

class WebhookController extends Controller
{
public function __invoke(Request $request)
{
$config = new Configuration();
$config->setAccessToken(env('LINE_CHANNEL_ACCESS_TOKEN'));
$client = new MessagingApiApi(new Client(), $config);

$signature = $request->header(HTTPHeader::LINE_SIGNATURE);
if (!$signature) {
abort(Response::HTTP_BAD_REQUEST);
}

try {
$secret = env('LINE_CHANNEL_SECRET');
$parsedEvents = EventRequestParser::parseEventRequest($request->getContent(), $secret, $signature);
} catch (InvalidSignatureException) {
abort(Response::HTTP_BAD_REQUEST);
} catch (InvalidEventRequestException) {
abort(Response::HTTP_BAD_REQUEST);
}

collect($parsedEvents->getEvents())
->filter(fn ($event) => $event instanceof MessageEvent)
->filter(fn ($event) => $event->getMessage() instanceof TextMessageContent)
->each(function ($event) use ($client) {
$replyText = $event->getMessage()->getText();

$client->replyMessage(new ReplyMessageRequest([
'replyToken' => $event->getReplyToken(),
'messages' => [
new TextMessage([
'type' => MessageType::TEXT,
'text' => $replyText,
]),
],
]));
});

return response()->json(null);
}
}

修改 routes/api.php 檔。

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

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

啟動本地伺服器。

1
artisan server

啟動代理伺服器。

1
ngrok http 8000

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

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

程式碼

參考資料