> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhook / Bot - LINE SDK for Laravel

> 通过 Webhook 控制器与 Bot Facade 使用 LINE Messaging API 收发消息。

## Webhook

该包提供了 Webhook 路由与控制器。

```mermaid theme={null}
flowchart TD
    A["用户发送消息"] --> B["LINE 通过 Webhook 发送"]
    B --> C["由 line.webhook 路由接收"]
    C --> D["ValidateSignature 中间件验证"]
    D --> E["WebhookController"]
    E --> F["由 WebhookEventDispatcher<br>分发 Laravel 事件"]
    F --> G["由事件监听器进行回复"]
```

### Webhook URL

默认 Webhook URL 如下：

```
https://example.com/line/webhook
```

可在 `.env` 中修改路径。

```dotenv theme={null}
LINE_BOT_WEBHOOK_PATH=webhook
```

### 与 Laravel 事件系统的集成

收到 Webhook 事件后会分发 Laravel 事件。事件发现（event discovery）默认已启用。

<Info>
  在生产环境中请执行 `php artisan event:cache`。
</Info>

### 发布默认 Listener

```shell theme={null}
php artisan vendor:publish --tag=line-listeners
```

会在 `app/Listeners/Line/` 中生成 `MessageListener`。

```php theme={null}
namespace App\Listeners\Line;

use LINE\Clients\MessagingApi\ApiException;
use LINE\Webhook\Model\MessageEvent;
use LINE\Webhook\Model\StickerMessageContent;
use LINE\Webhook\Model\TextMessageContent;
use Revolution\Line\Facades\Bot;

class MessageListener
{
    protected string $token;

    public function handle(MessageEvent $event): void
    {
        $message = $event->getMessage();
        $this->token = $event->getReplyToken();

        match ($message::class) {
            TextMessageContent::class => $this->text($message),
            StickerMessageContent::class => $this->sticker($message),
        };
    }

    protected function text(TextMessageContent $message): void
    {
        Bot::reply($this->token)->text($message->getText());
    }

    protected function sticker(StickerMessageContent $message): void
    {
        Bot::reply($this->token)->sticker(
            $message->getPackageId(),
            $message->getStickerId()
        );
    }
}
```

## Bot Facade

`Revolution\Line\Facades\Bot` 会将调用委派给官方 SDK 的 `MessagingApiApi` 类的所有方法。

```php theme={null}
use Revolution\Line\Facades\Bot;

Bot::replyMessage();
Bot::pushMessage();
```

### reply 方法

使用 `Bot::reply()` 时，你可以传入 reply token 来回复消息。

<Info>
  通过 `Bot::pushMessage()` 进行的推送发送会根据套餐存在条数限制。而针对用户消息的回复（`Bot::reply()`）没有条数限制，可以免费使用。
</Info>

```php theme={null}
use Revolution\Line\Facades\Bot;

// 回复文本
Bot::reply($token)->text('text');

// 更换发送者名称并回复多条文本
Bot::reply($token)->withSender('alt-name')->text('text1', 'text2');

// 回复贴图
Bot::reply($token)->sticker(package: 1, sticker: 1);
```

## 自定义

### Bot Macro

`Bot` 实现了 `Macroable`，因此可以自由添加方法。

在 `AppServiceProvider@boot` 中进行注册。

```php theme={null}
use Revolution\Line\Facades\Bot;

public function boot(): void
{
    Bot::macro('foo', function () {
        return $this->bot()->...;
    });
}
```

```php theme={null}
$foo = Bot::foo();
```

### 替换 MessagingApiApi 实例

`Bot::bot()` 会返回 `MessagingApiApi` 实例。可通过 `Bot::botUsing()` 替换该实例。

```php theme={null}
$bot = new MyBot();

Bot::botUsing($bot);
```

也支持 Callable。

```php theme={null}
Bot::botUsing(function () {
    return new MyBot();
});
```

### 替换 WebhookHandler

如果你不想使用 Laravel 事件系统，而希望自行编写 Webhook 处理逻辑，可以实现 `WebhookHandler` 接口并进行替换。

创建 `app/Actions/LineWebhook.php`：

```php theme={null}
<?php

namespace App\Actions;

use Illuminate\Http\Request;
use LINE\Webhook\Model\MessageEvent;
use Revolution\Line\Contracts\WebhookHandler;
use Revolution\Line\Facades\Bot;

class LineWebhook implements WebhookHandler
{
    public function __invoke(Request $request): mixed
    {
        Bot::parseEvent($request)->each(function ($event) {
            if ($event instanceof MessageEvent) {
                //
            }
        });

        return response('OK');
    }
}
```

在 `AppServiceProvider@register` 中注册：

```php theme={null}
use App\Actions\LineWebhook;
use Revolution\Line\Contracts\WebhookHandler;

public function register(): void
{
    $this->app->scoped(WebhookHandler::class, LineWebhook::class);
}
```

### 默认路由的中间件

默认启用了 `throttle` 中间件。可通过 `.env` 修改。

```dotenv theme={null}
# 禁用
LINE_BOT_WEBHOOK_MIDDLEWARE=null

# 修改 throttle 配置
LINE_BOT_WEBHOOK_MIDDLEWARE=throttle:120,1
```

### Http::line()

该包对 `Http` 类进行了扩展，因此你也可以不通过 `Bot` Facade，而直接发送 API 请求。

```php theme={null}
use Illuminate\Support\Facades\Http;

$response = Http::line()->post('/v2/bot/channel/webhook/test', [
    'endpoint' => '',
]);
```

<Info>
  更多最新信息请参见 [GitHub 仓库](https://github.com/invokable/laravel-line-sdk)。
</Info>


## Related topics

- [LINE SDK for Laravel](/zh/packages/laravel-line-sdk/index.md)
- [通知 Channel - LINE SDK for Laravel](/zh/packages/laravel-line-sdk/notification.md)
- [Socialite（LINE Login）- LINE SDK for Laravel](/zh/packages/laravel-line-sdk/socialite.md)
- [Laravel Notification for Discord(Webhook)](/zh/packages/laravel-notification-discord-webhook.md)
- [Bot 教程 - Laravel Bluesky](/zh/packages/laravel-bluesky/bot-tutorial.md)
