# Live Chat และเรียลไทม์สำหรับ Astro

> อินทิเกรชันของ Astro: เพิ่มบรรทัดเดียวใน astro.config ทุกหน้าก็มี Hibira Live Chat และสคริปต์ในหน้าได้รับอีเวนต์ presence และคำตอบ LLM แบบสตรีมผ่านการเชื่อมต่อเดียวที่ใช้ร่วมกัน รองรับ Astro 4 ถึง 7

Source: https://hibira.io/th/guides/astro

อินทิเกรชันของ Astro: เพิ่มบรรทัดเดียวใน astro.config ทุกหน้าก็มี Hibira Live Chat และสคริปต์ในหน้าได้รับอีเวนต์ presence และคำตอบ LLM แบบสตรีมผ่านการเชื่อมต่อเดียวที่ใช้ร่วมกัน รองรับ Astro 4 ถึง 7

Package: @hibira-io/astro

- แชทโหลดครั้งเดียวและยังเปิดอยู่ระหว่าง view transitions ส่วน <LiveChatButton> และลิงก์ไปที่ #hibira-live-chat ใช้เปิดแชทได้
- <LiveChatUser> ลงชื่อเข้าใช้ให้ผู้เข้าชมบนเซิร์ฟเวอร์ด้วยรหัสลับระบุตัวตนของคุณ กล่องข้อความจึงแสดงว่าเป็นใคร และบทสนทนาตามไปทุกอุปกรณ์
- ใช้ onEvent, onPresence และ onStream ใน <script> หรือ island ใดก็ได้ ใช้ channelAuth() เป็น API route และ streamToChannel() สำหรับคำตอบจาก LLM

## 1. ติดตั้ง

```shell
npx astro add @hibira-io/astro
npm install pusher-js
```

## 2. ตั้งค่า

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import hibira from '@hibira-io/astro';

export default defineConfig({
  integrations: [
    hibira({
      liveChat: 'ws_YOUR_WORKSPACE', // or PUBLIC_HIBIRA_LIVECHAT_WORKSPACE
      realtime: {
        key: import.meta.env.PUBLIC_HIBIRA_KEY,
        options: {
          wsHost: 'ws.hibira.io',
          channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
        },
      },
    }),
  ],
});
```

## 3. ใช้งาน

```xml
---
import { LiveChatUser, LiveChatButton } from '@hibira-io/astro/components';
const user = Astro.locals.user;
---
<LiveChatUser user={user && { id: user.id, name: user.name, email: user.email }} />
<LiveChatButton topic="sales">Talk to sales</LiveChatButton>
<p><span id="online">0</span> online</p>

<script>
  import { onEvent, onPresence } from '@hibira-io/astro/realtime';

  onEvent('orders', 'order.created', (order) => console.log(order));
  onPresence('presence-dashboard', ({ count }) => (document.getElementById('online').textContent = String(count)));
</script>
```

## ก่อนเริ่ม

- ดู workspace ID ในคอนโซล Live Chat และสร้างรหัสลับระบุตัวตนในการตั้งค่า > ผู้เข้าชมที่ยืนยันแล้ว ใส่ไว้ใน HIBIRA_LIVECHAT_IDENTITY_SECRET ซึ่งอยู่บนเซิร์ฟเวอร์ของคุณเท่านั้น
- ในแพ็กเกจ Free ให้ใส่ทุก origin ที่หน้าเว็บโหลดมาใน Origin ที่อนุญาตของแอป (http://localhost:3000 ระหว่างพัฒนา แล้วตามด้วยโดเมนของคุณ) ส่วน "*" ต้องใช้แพ็กเกจแบบชำระเงิน
- แชนเนล private และ presence ต้องมี auth endpoint บนแบ็กเอนด์ที่ลงนามการสมัครรับด้วยซีเคร็ตของแอป เหมือนกับ pusher-js
- ถ้าใช้ Astro 5.14 ขึ้นไปหลังพร็อกซี ให้ใส่โดเมนใน security.allowedDomains ไม่เช่นนั้น Astro จะปฏิเสธคำขอยืนยันสิทธิ์ด้วย 403

- [npm](https://www.npmjs.com/package/@hibira-io/astro)
- [GitHub](https://github.com/hibira-io/astro)
