# Dialog System

The dialog system lets you create branching conversations with NPCs. Dialogs are JSON files and support three node types, conditions, **actions** that need no commands, repeat rules, commands and texts in several languages. Since Core 2.9.0 you can also build them in game with the [dialog editor](https://wiki.kyuubisoft.com/hytale/citizens/admin-windows/#dialog-editor).

## How Dialogs Work

When a player presses **F** on an NPC, the system follows this priority chain:

1. **Quest NPC Profile** -- If the Quest mod has a profile for this citizen, the quest dialog system takes over.
2. **Citizen Dialogs** -- The `dialogs` array in the citizen config is checked. The first dialog whose condition matches is opened.
3. **Messages** -- If no dialog matches, simple chat messages are sent.
4. **Shop / Commands** -- If no dialog or messages exist, the shop or command actions are executed.

:::info
Quest NPC Profiles always take priority. If a citizen has both a quest profile and legacy dialogs, only the quest profile dialog is shown. Do not mix both on the same NPC.
:::

## The Dialog Window

Since Core 2.8.0 the dialog window sits at the bottom of the screen, so the world stays visible.

- The speaker stands on a live 3D stage that players can turn with the mouse. NPCs with a player skin are built from their skin parts; without a skin the speaker's initial is shown.
- Up to **4 numbered answers**, each with an optional tag such as "Opens shop".
- **"Continue"** and **"Show all"**, and a **conversation history**.
- **Typewriter:** while the text is still typing, answers are dimmed and not accepted; clicking the text shows it all.
- **"Step back"** only shows earlier text again. Once a player has stepped back, the rest of that conversation runs no commands, shops or rewards; the dialog still counts as completed once.
- An answer step with no visible answer shows "Close", so players are never locked in.
- **Greyed-out answers:** an answer that takes an item or coins the player does not have, or gives items that do not fit, is shown greyed out with the reason, and none of its actions run.

## Dialog File Structure

Dialog files live in `mods/kyuubisoft_core/dialogs/` as individual JSON files. They load in file-name order; if two files use the same ID, the first one wins, and the check and the log name both files. Dialogs are saved atomically, and unsafe or Windows-reserved IDs (`con`, `nul`, `com1` ...) are refused.

```json
{
  "id": "example_dialog",
  "speakerName": "dialog.example.speaker",
  "speakerRole": "Village Elder",
  "startNode": "greeting",
  "nodes": [
    {
      "nodeId": "greeting",
      "type": "TEXT",
      "lines": ["dialog.example.greeting.line1", "dialog.example.greeting.line2"],
      "next": "ask_help"
    },
    {
      "nodeId": "ask_help",
      "type": "CHOICE",
      "lines": ["dialog.example.ask_help"],
      "choices": [
        { "text": "dialog.example.choice.yes", "next": "accepted" },
        { "text": "dialog.example.choice.no", "next": "declined" },
        { "text": "dialog.example.choice.later", "next": null }
      ]
    },
    {
      "nodeId": "accepted",
      "type": "TEXT",
      "lines": ["dialog.example.accepted.line1"],
      "next": null
    },
    {
      "nodeId": "declined",
      "type": "TEXT",
      "lines": ["dialog.example.declined.line1"],
      "next": null
    }
  ]
}
```

### Top-Level Fields

| Field | Required | Description |
|-------|----------|-------------|
| `id` | Yes | Unique dialog ID. Referenced from the citizen config. |
| `speakerName` | No | Name of the speaker: an i18n key, plain text or one text per language. Falls back to the citizen's name. |
| `speakerRole` | No | A short role line under the speaker's name. |
| `startNode` | Yes | ID of the first node. The start node's own `condition` is checked too. |
| `nodes` | Yes | Array of dialog nodes. |

## Node Types

### TEXT Node

Displays one or more lines of text. The player clicks to advance to the next node.

```json
{
  "nodeId": "greeting",
  "type": "TEXT",
  "lines": ["Hello, {player}!", "Welcome to our village."],
  "next": "ask_help"
}
```

- `lines` -- Array of texts (1-4 lines recommended).
- `next` -- ID of the next node. `null` ends the dialog.
- `typewriterEffect` -- `true` (default) types the text letter by letter.
- `condition` -- Optional condition for showing this node.
- `macro` -- Optional actions and commands that run when the node is reached.

### CHOICE Node

Displays text with 1 to 4 answers.

```json
{
  "nodeId": "ask_help",
  "type": "CHOICE",
  "lines": ["Can you help me gather some herbs?"],
  "choices": [
    { "text": "Sure, I will help!", "next": "accepted", "tag": "Starts quest" },
    { "text": "Not right now.", "next": null }
  ]
}
```

Each choice has:
- `text` -- Display text, i18n key or one text per language.
- `next` -- Node to jump to. `null` closes the dialog.
- `condition` -- Optional condition to show or hide this choice (see below).
- `tag` -- Optional short label shown on the answer, for example "Opens shop".
- `macro` -- Optional actions and commands that run when this choice is selected.

### INPUT Node

Asks the player to type an answer.

```json
{
  "nodeId": "name_input",
  "type": "INPUT",
  "lines": ["What is your name, adventurer?"],
  "inputPlaceholder": "Your name",
  "next": "response"
},
{
  "nodeId": "response",
  "type": "TEXT",
  "lines": ["Nice to meet you, {input}!"],
  "next": null
}
```

- The answer is remembered per player. Use `{input}` (last answer in this dialog) or `{input:<nodeId>}` (the answer of a specific node) in later texts.
- Answers are cleaned, limited to 24 characters and **never passed into commands**.
- `inputPlaceholder` -- Optional hint text in the empty input field.

## Texts and Languages

Every text (`speakerName`, `lines`, `choices[].text`) can be:

- **plain text**, shown as written;
- an **i18n key** from Core's localization files (if the key is not found, the text is shown as written);
- **one text per language** directly in the dialog file (since 2.9.0, written by the dialog editor):

```json
"speakerName": { "en-US": "Tamsin", "de-DE": "Tamsin" },
"lines": [ { "en-US": "Welcome!", "de-DE": "Willkommen!" }, "dialog.example.greeting.line2" ],
"choices": [ { "text": { "en-US": "Show me your wares.", "de-DE": "Zeig mir deine Waren." } } ]
```

Old files without per-language texts load unchanged. The dialog editor shows old key-based texts read-only until you press "Convert".

Text placeholders: `{player}` (player name), `{npc}` (NPC name), `{input}` and `{input:<nodeId>}`. The old forms `{citizen}`, `{PlayerName}` and `{citizenname}` keep working.

## Conditions

Conditions control which dialogs, nodes or choices are available.

### On Citizens (Conditional Dialogs)

The citizen's `dialogs` array supports conditions to select which dialog opens:

```json
{
  "dialogs": [
    {
      "dialogId": "quest_complete_dialog",
      "condition": { "type": "quest_completed", "value": "intro_quest" }
    },
    {
      "dialogId": "quest_active_dialog",
      "condition": { "type": "quest_active", "value": "intro_quest" }
    },
    {
      "dialogId": "default_greeting"
    }
  ]
}
```

The system checks conditions top to bottom. The first matching dialog opens. An entry without a condition acts as a fallback. In the dialog editor these are the "NPC assignments" in the dialog settings.

### On Choices

```json
{
  "choices": [
    {
      "text": "I have completed the trial.",
      "next": "reward",
      "condition": { "type": "quest_ready", "value": "trial_quest" }
    },
    {
      "text": "Tell me about the trial.",
      "next": "explain"
    }
  ]
}
```

### Available Condition Types

| Type | Value | Description |
|------|-------|-------------|
| `permission` | Permission string | Player has the permission. |
| `has_item` | `Item_Id` or `Item_Id x 3` | Player has the item (and amount) in the inventory. Works since 2.9.0. |
| `fact` | `name`, `name = value` or `name != value` | A fact set by the `set_fact` action. `name` alone means "set and not `false`/`0`". Values are compared ignoring case. |
| `quest_active` | Quest ID | Quest is active (Quests mod). |
| `quest_completed` | Quest ID | Quest is completed (Quests mod). |
| `quest_available` | Quest ID | Quest can be started (Quests mod). |
| `quest_ready` | Quest ID | Quest is active and all its objectives are done, ready to turn in (Quests mod, Core 2.9.1). |
| `achievement_unlocked` | Achievement ID | Achievement is unlocked (Achievements mod). |
| `achievement_count` | Number | Player has at least this many achievements (Achievements mod). |

All conditions support `"negate": true` to invert the result. Other mods can add their own condition types; the dialog editor lists them.

While a player's dialog state is still loading or could not be read, `fact` conditions count as not met.

## Actions

Actions do common things **without commands**, so they need no console permission. They sit in the `actions` list of a node's or choice's `macro`:

```json
{
  "text": "I will buy two pies.",
  "next": "thanks",
  "macro": {
    "actions": [
      { "type": "take_coins", "value": "50" },
      { "type": "give_item", "value": "Food_Pie_Apple x 2", "repeat": "once" },
      { "type": "set_fact", "value": "bought_pies = true" }
    ]
  }
}
```

| Type | Value | Description |
|------|-------|-------------|
| `give_item` | `Item_Id`, `Item_Id x 2` or `2 x Item_Id` (1-9999) | Give an item |
| `take_item` | same as `give_item` | Take an item |
| `give_coins` | `100` or `100 <currency>` | Give coins through the Core economy (needs an economy plugin) |
| `take_coins` | same as `give_coins` | Take coins |
| `start_quest` | Quest ID | Start a quest (Quests mod) |
| `open_shop` | Shop ID | Open a Core NPC shop |
| `open_window` | Window ID | Open a window: `settings` or `language` (Core); `questbook` or `questbook.settings` (Quests mod) |
| `teleport` | `x y z` | Teleport the player in their world |
| `play_sound` | Sound ID | Play a sound for the player |
| `set_fact` | `name = value` or `name` | Remember a fact for this player (with the Quests mod, facts are stored in Quests) |

Values are strict: an action only runs when its value can be read, so a typo never becomes a different item, amount or position.

**All or nothing:** if an answer takes items or coins the player does not have, or gives items that do not fit, the answer is greyed out with the reason and none of its actions run.

**Shops and windows at the end:** `open_shop`, `open_window` and commands on the last answer that open a window (such as the Quest Book) run when the conversation is over. The dialog window stays until they have run (at most 5 seconds) and only closes if nothing replaced it, so the new shop or window reacts to clicks right away.

### Repeat Rules

Each action has a repeat rule (`repeat`):

| Value | Meaning |
|---|---|
| `always` (default) | Every time |
| `once` | Once per player |
| `hour` | Once per hour per player |
| `day` | Once per day per player |
| `week` | Once per week per player |

The time counts from the last run. The state is stored per player in the table `dialog_actions` (MySQL or files) and is included in `/ksadmin migrate-storage`. Actions with a repeat limit wait until the player's state is known.

## Commands (Macros)

Macros can also run commands when a node is reached or a choice is selected:

```json
{
  "nodeId": "reward_node",
  "type": "TEXT",
  "lines": ["Here is your reward!"],
  "next": null,
  "macro": {
    "commands": [
      "give {player} Food_Pie_Apple 2"
    ],
    "runAsServer": true
  }
}
```

| Field | Default | Description |
|-------|---------|-------------|
| `commands` | -- | List of commands to execute. |
| `runAsServer` | `false` | `true` = run as server console, `false` = run as the player. |
| `actions` | -- | Actions, see above. |

**Command placeholders:** `{player}`, `{player_uuid}`, `{npc}` (NPC name), `{npc_id}`, `{world}`. The old `{citizen}` (= NPC ID), `{PlayerName}` and `{citizenname}` keep working. Values are escaped, so a player name can never change the shape of a command. `{input}` is never filled into commands.

:::caution[Console commands]
Adding, changing, removing, copying or deleting dialog commands that run as the console (`runAsServer: true`) in the dialog editor needs `ks.core.admin.dialog.console`. Prefer actions where possible: they need no console permission.
:::

:::warning
Commands in macros use the `ks`-prefixed command names (e.g. `ksquestadmin`, `ksachievementadmin`). Dialogs that run `ksnpcshop open` are tagged as opening a shop.
:::

## Localization (i18n)

i18n keys used in dialogs are defined in Core's localization files:

```json
{
  "dialog.example.speaker": "Elder Willowbark",
  "dialog.example.greeting.line1": "Greetings, young adventurer.",
  "dialog.example.greeting.line2": "The forest whispers of your arrival.",
  "dialog.example.choice.yes": "I am ready to help!",
  "dialog.example.choice.no": "Maybe later."
}
```

If a key is not found, the raw text is displayed as-is, so plain text works without a translation file. For new dialogs, per-language texts in the dialog file (see [Texts and Languages](#texts-and-languages)) are easier.

## Linking Dialogs to Quest NPC Profiles

For quest NPCs, the Quest mod's NPC Profile system is the recommended approach. It provides dialogs for quest offer, active and complete states. Core dialogs can also start quests (`start_quest`), check `quest_ready` and share facts with Quests.

See [NPC Quest Profiles](https://wiki.kyuubisoft.com/hytale/quest-system/npc-quest-profiles/) for details.