# Scripts（2.0 β）

ccfolia v2.0 preview ではカスタムスクリプトをルームに適用することができます。現状のカスタムスクリプトでは、発言を読み取って内容に応じてボットからの発言を返すことができます。例えば以下のような実装をすることができます。

* ランダム表
* キーワードに応じて情報を出す
* 完全に独自のダイスボット

カスタムスクリプトは EcmaScript で記述することができます。最もシンプルな例は、以下の通りです。onMessage は発言の度に発言者のクライアント内で呼び出されます。

```javascript
function onMessage(message) {
    return { messages: [{ text: "something" }] }
}
```

上記のスクリプトは、全ての発言に対して something という発言を追加します。引数や返り値については、以下の型定義を参考にしてください。（いくつか現状では利用されていないプロパティが含まれています）

```typescript
type Message = {
  to: string | null;
  toName: string;
  from: string;
  name: string;
  iconUrl: string | null;
  color: string;
  imageUrl: string | null;
  text: string;
  type: "text" | "note" | "system";
  extend: {
    roll?: {
      result: string;
      dices: { kind: string; value: number; faces: number }[];
      secret: boolean;
      success: boolean;
      failure: boolean;
      critical: boolean;
      fumble: boolean;
    };
  };
  removed: boolean;
  edited: boolean;
  channel: string;
  channelName: string;
  createdAt: Timestamp;
  updatedAt: Timestamp;
};

type ReturnValue = {
  messages: { text: string }[]
}

type onMessage = (message: Message) => ReturnValue;
```

## 例

### ランダム表

/rand とチャットで発言された時、選択肢の中からランダムで文字列を表示します。

```javascript
function onMessage(message) {
  if (message.text === "/rand") {
    const items = [
      "選択肢A",
      "選択肢B",
      "選択肢C",
      "選択肢D",
      "選択肢E",
      "選択肢F",
    ];
    const item = items[Math.floor(Math.random() * items.length)];
    return { messages: [{ text: item }] };
  }
}
```

### 外部API

/cat とチャットで発言された時、ランダムで猫の画像を表示します。\`getFromUrl\`はカスタムスクリプト上で提供される独自関数です。

```javascript
async function onMessage(message) {
  if (message.text === "/cat") {
    const res = await getFromUrl("https://aws.random.cat/meow");
    const data = JSON.parse(res);
    return {
      messages: [{ text: `<img src="${data.file}" alt="neko" />` }]
    }
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.ccfolia.com/developer-api/scripts-2.0-v.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
