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

# 通知頻道 - Laravel Bluesky

> 說明如何以 Laravel Notification 頻道向 Bluesky 發送貼文與 DM。

## 概觀

`laravel-bluesky` 可整合至 Laravel 的 Notification 系統。透過 `BlueskyChannel` 發送一般貼文，`BlueskyPrivateChannel` 則可發送私訊（DM）。

```mermaid theme={null}
flowchart LR
    A["Laravel Notification"] --> B{"選擇頻道"}
    B -->|"BlueskyChannel"| C["Bluesky 一般貼文"]
    B -->|"BlueskyPrivateChannel"| D["Bluesky DM 發送"]
```

## 可用的頻道

| 頻道                      | 用途              |
| ----------------------- | --------------- |
| `BlueskyChannel`        | 以一般公開貼文形式進行通知   |
| `BlueskyPrivateChannel` | 以 DM（私訊）形式通知收件者 |

## Notification 類別

### BlueskyChannel

在 `via()` 中指定 `BlueskyChannel::class`，並在 `toBluesky()` 回傳發送內容。

```php theme={null}
use Illuminate\Notifications\Notification;
use Revolution\Bluesky\Notifications\BlueskyChannel;
use Revolution\Bluesky\Record\Post;
use Revolution\Bluesky\RichText\TextBuilder;
use Revolution\Bluesky\Embed\External;

class TestNotification extends Notification
{
    public function via(object $notifiable): array
    {
        return [
            BlueskyChannel::class
        ];
    }

    public function toBluesky(object $notifiable): Post
    {
        $external = External::create(title: 'Title', description: 'test', uri: 'https://');

        return Post::build(function (TextBuilder $builder) {
                   $builder->text('test')
                           ->newLine()
                           ->tag('#Laravel');
        })->embed($external);
    }
}
```

`Post` 的用法與 [Basic client](/zh-TW/packages/laravel-bluesky/basic-client) 相同。TextBuilder、Embed 等也可以同樣使用。

### BlueskyPrivateChannel

`BlueskyPrivateMessage` 幾乎與 `Post` 相同，但僅支援 text、facets、embed。embed 僅支援 `QuoteRecord`。

```php theme={null}
use Illuminate\Notifications\Notification;
use Revolution\Bluesky\Notifications\BlueskyPrivateChannel;
use Revolution\Bluesky\Notifications\BlueskyPrivateMessage;
use Revolution\Bluesky\RichText\TextBuilder;
use Revolution\Bluesky\Embed\QuoteRecord;
use Revolution\Bluesky\Types\StrongRef;

class TestNotification extends Notification
{
    public function via(object $notifiable): array
    {
        return [
            BlueskyPrivateChannel::class
        ];
    }

    public function toBlueskyPrivate(object $notifiable): BlueskyPrivateMessage
    {
        $quote = QuoteRecord::create(StrongRef::to(uri: 'at://', cid: 'cid'));

        return BlueskyPrivateMessage::build(function (TextBuilder $builder) {
                   $builder->text('test')
                           ->newLine()
                           ->tag('#Laravel');
        })->embed($quote);
    }
}
```

## 隨選通知

若不使用模型，而是當場指定通知對象，可使用 `Notification::route()`。

### BlueskyChannel

```php theme={null}
use Illuminate\Support\Facades\Notification;
use Revolution\Bluesky\Notifications\BlueskyRoute;
use Revolution\Bluesky\Session\OAuthSession;
use App\Models\User;

// App password
Notification::route('bluesky', BlueskyRoute::to(identifier: config('bluesky.identifier'), password: config('bluesky.password')))
            ->notify(new TestNotification());

// OAuth
$user = User::find(1);
$session = OAuthSession::create([
    'did' => $user->did,
    'iss' => $user->iss,
    'refresh_token' => $user->refresh_token,
]);
Notification::route('bluesky', BlueskyRoute::to(oauth: $session))
            ->notify(new TestNotification());
```

### BlueskyPrivateChannel

DM 必須指定 `receiver`（收件者的 DID 或 handle）。同時，接收方也需啟用 DM 接收。

* 使用 App password 時需具備 DM 發送權限。
* 使用 OAuth 時需具備 `transition:chat.bsky` scope。

```php theme={null}
use Illuminate\Support\Facades\Notification;
use Revolution\Bluesky\Notifications\BlueskyRoute;
use Revolution\Bluesky\Session\OAuthSession;
use App\Models\User;

// App password
Notification::route('bluesky-private', BlueskyRoute::to(identifier: config('bluesky.identifier'), password: config('bluesky.password'), receiver: 'did or handle'))
            ->notify(new TestNotification());

// OAuth
$user = User::find(1);
$session = OAuthSession::create([
    'did' => $user->did,
    'iss' => $user->iss,
    'refresh_token' => $user->refresh_token,
]);
Notification::route('bluesky-private', BlueskyRoute::to(oauth: $session, receiver: 'did or handle'))
            ->notify(new TestNotification());
```

<Info>
  Bluesky 中無法對自己發送 DM。若要對自己發送通知，請另備一個帳號用於發送。
</Info>

```php theme={null}
// 對自己發送 DM

use Illuminate\Support\Facades\Notification;
use Revolution\Bluesky\Notifications\BlueskyRoute;

Notification::route('bluesky-private', BlueskyRoute::to(identifier: 'sender identifier', password: 'sender password', receiver: 'your did or handle'))
            ->notify(new TestNotification());
```

若為個人用途等常固定同一發送者與接收者的情境，可透過 `.env` 設定。請建立發送專用的帳號。

```dotenv theme={null}
BLUESKY_SENDER_IDENTIFIER=sender did or handle
BLUESKY_SENDER_APP_PASSWORD=sender password
BLUESKY_RECEIVER=your did or handle
```

```php theme={null}
Notification::route('bluesky-private', BlueskyRoute::to(
    identifier: config('bluesky.notification.private.sender.identifier'),
    password: config('bluesky.notification.private.sender.password'),
    receiver: config('bluesky.notification.private.receiver'),
))->notify(new TestNotification());
```

## 使用者通知

在使用 `Notifiable` trait 的模型上定義通知路由。

### BlueskyChannel

```php theme={null}
use Illuminate\Notifications\Notifiable;
use Revolution\Bluesky\Notifications\BlueskyRoute;
use Revolution\Bluesky\Session\OAuthSession;

class User
{
    use Notifiable;

    public function routeNotificationForBluesky($notification): BlueskyRoute
    {
        // App password
        return BlueskyRoute::to(identifier: $this->bluesky_identifier, password: $this->bluesky_password);

        // OAuth
        $session = OAuthSession::create([
            'did' => $this->did,
            'iss' => $this->iss,
            'refresh_token' => $this->refresh_token,
        ]);
        return BlueskyRoute::to(oauth: $session);
    }
}

$user->notify(new TestNotification());
```

### BlueskyPrivateChannel

```php theme={null}
use Illuminate\Notifications\Notifiable;
use Revolution\Bluesky\Notifications\BlueskyRoute;
use Revolution\Bluesky\Session\OAuthSession;

class User
{
    use Notifiable;

    public function routeNotificationForBlueskyPrivate($notification): BlueskyRoute
    {
        // App password
        return BlueskyRoute::to(identifier: $this->bluesky_identifier, password: $this->bluesky_password, receiver: $this->receiver);

        // OAuth
        $session = OAuthSession::create([
            'did' => $this->did,
            'iss' => $this->iss,
            'refresh_token' => $this->refresh_token,
        ]);
        return BlueskyRoute::to(oauth: $session, receiver: $this->receiver);
    }
}

$user->notify(new TestNotification());
```

也可以將使用者自己設為接收者。

```php theme={null}
public function routeNotificationForBlueskyPrivate($notification): BlueskyRoute
{
    // App password
    return BlueskyRoute::to(identifier: 'sender identifier', password: 'sender password', receiver: $this->did);
}
```

## BlueskyRoute

根據認證方式（App password 或 OAuth）指定方法不同。建議使用具名參數。

```php theme={null}
use Revolution\Bluesky\Notifications\BlueskyRoute;
use Revolution\Bluesky\Session\OAuthSession;

// App password
BlueskyRoute::to(identifier: config('bluesky.identifier'), password: config('bluesky.password'))

// OAuth
$session = OAuthSession::create([
    'did' => '...',
    'iss' => '...',
    'refresh_token' => '...',
]);
BlueskyRoute::to(oauth: $session);
```

<Tip>
  若僅是對自己的帳號發送通知，使用 **App password** 最為簡單。無需考量 refresh\_token 的更新，只要設定 `.env` 即可使用。

  ```dotenv theme={null}
  BLUESKY_IDENTIFIER=
  BLUESKY_APP_PASSWORD=
  ```
</Tip>

## 確認通知結果

與一般 Laravel 相同，可透過 `NotificationSent` 事件確認通知後的回應。

```php theme={null}
use Illuminate\Notifications\Events\NotificationSent;
use Illuminate\Http\Client\Response;

class Listener
{
    public function handle(NotificationSent $event): void
    {
        // $event->channel  BlueskyChannel
        // $event->notifiable
        // $event->notification
        // $event->response  null|Response
    }
}
```

<Info>
  Source：[docs/notification.md](https://github.com/invokable/laravel-bluesky/blob/main/docs/notification.md)
</Info>


## Related topics

- [Laravel Bluesky](/zh-TW/packages/laravel-bluesky/index.md)
- [Bot 教學 - Laravel Bluesky](/zh-TW/packages/laravel-bluesky/bot-tutorial.md)
- [認證方式比較 - Laravel Bluesky](/zh-TW/packages/laravel-bluesky/authentication.md)
- [教學 - Laravel Console Starter](/zh-TW/packages/laravel-console-starter/tutorial.md)
- [Laravel Console Starter](/zh-TW/packages/laravel-console-starter/index.md)
