> For the complete documentation index, see [llms.txt](https://docs.cuxial.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cuxial.com/scripts/police-and-medical/cuxial-diseases/developers.md).

# Exports & events

Public API of Cuxial Diseases: exports, hooks and events to infect, test, treat and cure from other resources.

Read the medical state of a character, change it and react to what happens to it from your own resources.

Every server export takes a `target` that can be a **server id** (number) or a **citizenid** (string). With a citizenid the export also works while the player is offline.

## Reading cases

| Export                                 | Returns                                                                                                                                                                    |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GetCatalog()`                         | `table<string, table>`. Summary of each disease: `id`, `label`, `category`, `icon`, `color`, `description`, `stages`, `testItem`, `treatmentItem`, `curable`, `cureSteps`. |
| `GetDiseaseDef(disease)`               | table \| nil. The full entry of `data/diseases.lua`.                                                                                                                       |
| `GetCases(target)`                     | `table[]`. Active cases of the character.                                                                                                                                  |
| `GetCase(target, disease)`             | table \| nil. One active case. Without `disease`, the most recent one.                                                                                                     |
| `IsInfected(target, disease)`          | `boolean`. Without `disease`, checks for any disease.                                                                                                                      |
| `IsImmune(target, disease)`            | `boolean`.                                                                                                                                                                 |
| `GetHistory(target, limit)`            | `table[]`. Cases of the character, cured ones included. `limit` is 50 by default, 200 at most.                                                                             |
| `GetLog(target, limit)`                | `table[]`. Log of the character: `caseId`, `event`, `detail`, `actor`, `at`. `limit` is 50 by default, 200 at most.                                                        |
| `GetActiveCases(limit, onlyDiagnosed)` | `table[]`. Active cases of the whole server. `limit` is 100 by default, 500 at most. `onlyDiagnosed = true` returns only diagnosed cases.                                  |

```lua
if exports.cuxial_diseases:IsInfected(source, 'gripe') then
    local case = exports.cuxial_diseases:GetCase(source, 'gripe')
    print(case.stageLabel, case.treatmentActive)
end
```

### Case

Shape of each case returned by the exports above. Dates are Unix timestamps in seconds.

| Field                                           | Type                    | Description                                                                                    |
| ----------------------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `id`                                            | number                  | Id of the case.                                                                                |
| `citizenid`                                     | string                  | Character.                                                                                     |
| `disease`, `label`, `category`, `icon`, `color` | string                  | Disease and how it is presented.                                                               |
| `stage`, `stageLabel`                           | string                  | Current stage.                                                                                 |
| `stageIndex`, `stageCount`                      | number                  | Position of the stage and number of stages.                                                    |
| `severity`                                      | string                  | `'mild'`, `'moderate'`, `'severe'` or `'critical'`.                                            |
| `lethal`                                        | boolean                 | Whether the current stage is lethal.                                                           |
| `status`                                        | string                  | `'active'`, `'controlled'` (a dose is active) or `'cured'`.                                    |
| `diagnosed`, `diagnosedAt`, `diagnosedBy`       | boolean, number, string | Diagnosis.                                                                                     |
| `infectedAt`, `infectedBy`                      | number, string          | When and from whom.                                                                            |
| `stageSince`, `progressesAt`                    | number                  | Start of the stage and when it changes.                                                        |
| `lastTreatment`, `treatmentUntil`               | number                  | Last dose and end of its effect.                                                               |
| `treatmentActive`                               | boolean                 | Whether a dose is in effect now.                                                               |
| `treatmentDoses`                                | number                  | Doses counted so far.                                                                          |
| `cureStep`, `cureSteps`                         | number, table           | Steps of the cure plan already done, and the plan.                                             |
| `cureStepAt`, `nextStepAt`                      | number                  | When the last step was done, and from when the next one can be done (`nil` if it has no wait). |
| `curedAt`, `curedBy`                            | number, string          | Cure.                                                                                          |
| `notes`                                         | string                  | Notes of the doctor.                                                                           |

## Changing cases

### Infect

Gives a disease to a character.

```lua
exports.cuxial_diseases:Infect(target, disease, infectedBy, opts)
```

| Parameter             | Type             | Description                                                                          |
| --------------------- | ---------------- | ------------------------------------------------------------------------------------ |
| `target`              | number \| string | Server id or citizenid.                                                              |
| `disease`             | string           | `id` from `data/diseases.lua`.                                                       |
| `infectedBy`          | string           | Origin, stored with the case. Optional.                                              |
| `opts.stage`          | string           | Stage to start in. The first one by default.                                         |
| `opts.ignoreImmunity` | boolean          | `true` infects even if the character is immune.                                      |
| `opts.actor`          | number \| string | Who did it, for the log.                                                             |
| `opts.deferStage`     | boolean          | `true` = if the character is offline, the stage starts counting at their next login. |

**Returns:** `boolean, string`. `true`, or `false` and a reason: `'invalid_target'`, `'unknown_disease'`, `'already_infected'`, `'immune'` or `'db_error'`.

```lua
-- Spoiled food
local ok, reason = exports.cuxial_diseases:Infect(source, 'gastroenteritis', 'bad_food')
```

### RollContagion

Rolls contagion between two characters when exactly one of them has the disease. Uses `contagion.sexual` from the catalog.

```lua
exports.cuxial_diseases:RollContagion(first, second, disease, mods)
```

| Parameter              | Type             | Description                                        |
| ---------------------- | ---------------- | -------------------------------------------------- |
| `first`, `second`      | number \| string | The two characters.                                |
| `disease`              | string           | Disease to roll.                                   |
| `mods.condomUsed`      | boolean          | Applies `condomProtection`.                        |
| `mods.condomSabotaged` | boolean          | Cancels the protection.                            |
| `mods.chanceOverride`  | number           | Percentage used instead of the one in the catalog. |

**Returns:** `boolean, string`. Whether someone was infected, and the reason: `'infected'`, `'no_roll'`, `'protected'`, `'none_infected'`, `'both_infected'`, `'immune'`, `'no_sexual_contagion'` or `'invalid_target'`.

```lua
local infected = exports.cuxial_diseases:RollContagion(srcA, srcB, 'vih', { condomUsed = true })
```

### RunTest

Tests a character for one disease. A positive result marks the case as diagnosed.

```lua
exports.cuxial_diseases:RunTest(target, disease, actor, opts)
```

| Parameter       | Type             | Description                                                                   |
| --------------- | ---------------- | ----------------------------------------------------------------------------- |
| `target`        | number \| string | Server id or citizenid.                                                       |
| `disease`       | string           | Disease to test for.                                                          |
| `actor`         | number \| string | Who runs the test, for the log. Optional.                                     |
| `opts.accuracy` | number           | From 0 to 100. Below 70 it adds a chance of an inconclusive result. Optional. |

**Returns:** `string`. `'negative'`, `'inconclusive'` or `'positive'`.

```lua
local result = exports.cuxial_diseases:RunTest(patient, 'neumonia', source)
```

### ApplyItem

Applies an item that was consumed: one dose for every active case it treats, and the vaccine if it is a `vaccine.item`. Use it when your own resource handles the use of the item.

```lua
exports.cuxial_diseases:ApplyItem(target, item, actor)
```

**Returns:** `table[]`. One entry per effect: `{ disease, label, effect }`, where `effect` is `'dose'`, `'cured'` or `'vaccine'`. Vaccines add `permanent` and `hours`. Empty when the item did nothing.

```lua
local effects = exports.cuxial_diseases:ApplyItem(source, 'paracetamol', source)
```

### Diagnose

Marks a case as diagnosed.

```lua
exports.cuxial_diseases:Diagnose(target, disease, actor)
```

**Returns:** `boolean, string`. `false, 'not_infected'` when there is no case.

```lua
exports.cuxial_diseases:Diagnose(patient, 'gripe', source)
```

### Treat

Applies one dose of the treatment of a disease.

```lua
exports.cuxial_diseases:Treat(target, disease, actor)
```

**Returns:** `boolean, string, boolean`. On success: `true`, the current stage, and whether that dose cured the disease. On failure: `false` and `'not_infected'`, `'no_treatment'`, `'too_soon'` or `'invalid_target'`.

```lua
local ok, stage, cured = exports.cuxial_diseases:Treat(patient, 'gripe', source)
```

### AdvanceCureStep

Completes the current step of the cure plan. The last step cures the patient.

```lua
exports.cuxial_diseases:AdvanceCureStep(target, disease, actor)
```

**Returns:** `boolean, string, boolean, number`. On success: `true`, the `id` of the step, and whether the patient is cured. On failure: `false` and `'not_infected'`, `'no_cure_plan'` or `'too_soon'`; with `'too_soon'` the fourth value is the seconds left.

```lua
local ok, step, cured, wait = exports.cuxial_diseases:AdvanceCureStep(citizenid, 'neumonia', source)
if not ok and step == 'too_soon' then
    print(('Next step in %d minutes'):format(math.ceil(wait / 60)))
end
```

{% hint style="info" %}
Remove the `item` of the step from the inventory in your resource before calling the export.
{% endhint %}

### Regress

Relapse: goes back one step in the cure plan and cancels the active treatment. Meant for a patient who misses an appointment.

```lua
exports.cuxial_diseases:Regress(target, disease, actor)
```

**Returns:** `boolean, number | string`. `true` and the step the plan is left at, or `false, 'not_infected'`.

```lua
exports.cuxial_diseases:Regress(citizenid, 'neumonia', 'no_show')
```

### Cure

Cures a disease and applies the immunity set in the catalog.

```lua
exports.cuxial_diseases:Cure(target, disease, actor, reason)
```

| Parameter | Type             | Description                                        |
| --------- | ---------------- | -------------------------------------------------- |
| `target`  | number \| string | Server id or citizenid.                            |
| `disease` | string           | Disease to cure. Without it, the most recent case. |
| `actor`   | number \| string | Who cures, for the log. Optional.                  |
| `reason`  | string           | Stored in the log. `'manual'` by default.          |

**Returns:** `boolean, string`. `false, 'not_infected'` when there is no case.

```lua
exports.cuxial_diseases:Cure(source, 'gripe', 'hospital_bed', 'bed_rest')
```

### GrantImmunity

Makes a character immune to a disease. It never shortens a longer immunity.

```lua
exports.cuxial_diseases:GrantImmunity(target, disease, hours, source)
```

| Parameter | Type             | Description                                               |
| --------- | ---------------- | --------------------------------------------------------- |
| `hours`   | number \| string | Hours of immunity, or `'permanent'`.                      |
| `source`  | string           | Origin, stored with the immunity. `'vaccine'` by default. |

**Returns:** `boolean`. `false` when the disease does not exist.

```lua
exports.cuxial_diseases:GrantImmunity(source, 'gripe', 72, 'event_reward')
```

### SetNotes

Saves the notes of the doctor on a case. Cut at 2000 characters.

```lua
exports.cuxial_diseases:SetNotes(target, disease, notes)
```

**Returns:** `boolean`.

## Hooks

Run your code when something happens to a case.

### onDisease

```lua
local handle = exports.cuxial_diseases:onDisease(event, fn)
```

**Returns:** `number`. A handle to remove the hook later.

### offDisease

```lua
exports.cuxial_diseases:offDisease(handle)
```

**Returns:** `boolean`.

```lua
local handle = exports.cuxial_diseases:onDisease('collapse', function(e)
    -- e.source is the server id of the patient
    if e.source then TriggerEvent('my_ambulance:knockDown', e.source) end
end)
```

Each hook is also sent as a server event named `cuxial_diseases:<event>`, with the same table:

```lua
AddEventHandler('cuxial_diseases:cure', function(e)
    print(e.citizenid, e.disease, e.reason)
end)
```

| Event                | When                             | Fields                                                      |
| -------------------- | -------------------------------- | ----------------------------------------------------------- |
| `infect`             | A case is created                | `caseId`, `citizenid`, `disease`, `stage`, `infectedBy`     |
| `progress`           | The stage changes                | `caseId`, `citizenid`, `disease`, `from`, `stage`, `lethal` |
| `diagnose`           | A case is diagnosed              | `caseId`, `citizenid`, `disease`, `stage`, `by`             |
| `treat`              | A dose is applied                | `caseId`, `citizenid`, `disease`, `stage`, `doses`          |
| `expire`             | The effect of a dose ends        | `caseId`, `citizenid`, `disease`, `stage`                   |
| `routine_reset`      | The dose count goes back to zero | `caseId`, `citizenid`, `disease`, `stage`, `doses`          |
| `step`               | A cure step is completed         | `caseId`, `citizenid`, `disease`, `step`, `total`, `stepId` |
| `regress`            | A relapse                        | `caseId`, `citizenid`, `disease`, `stage`, `step`           |
| `cure`               | A case is cured                  | `caseId`, `citizenid`, `disease`, `stage`, `reason`         |
| `collapse`           | A lethal stage collapses         | `caseId`, `citizenid`, `disease`, `stage`, `source`         |
| `vaccine`            | A vaccine is applied             | `citizenid`, `disease`, `permanent`                         |
| `conceive`           | A pregnancy starts               | `id`, `mother`, `father`                                    |
| `pregnancy_revealed` | A pregnancy becomes known        | `id`, `mother`                                              |
| `pregnancy_month`    | A new month starts               | `id`, `mother`, `month`                                     |
| `labor`              | Labour starts                    | `id`, `mother`, `father`                                    |
| `birth`              | Birth                            | `id`, `mother`, `father`, `reason`, `by`                    |
| `terminate`          | A pregnancy is ended             | `id`, `mother`, `reason`                                    |

## Pregnancy

| Export                                      | Returns                                                                                                                                                                                                                                                             |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GetPregnancy(target)`                      | table \| nil. Active pregnancy: `id`, `mother`, `father`, `status`, `revealed`, `conceivedAt`, `dueDate`, `month`, `months`, `monthLabel`, `week`, `trimester`, `trimesterLabel`, `daysToBirth`, `secondsToBirth`, `labor`, `laborSince`, `laborDeadline`, `notes`. |
| `IsPregnant(target)`                        | `boolean`.                                                                                                                                                                                                                                                          |
| `IsFertile(target)`                         | `boolean`. Whether the character is inside the fertile window today.                                                                                                                                                                                                |
| `GetPregnancyHistory(target, limit)`        | `table[]`. Pregnancies of the character, same shape. `limit` is 20 by default, 100 at most.                                                                                                                                                                         |
| `RollPregnancy(mother, father, stats)`      | boolean, number \| string. Rolls a pregnancy with the `fertility` rules. `stats` is optional: `recentCount`, `lastEncounterAt`, `encounterRef`. Returns `true` and the id, or `false` and `'already_pregnant'` or `'no_roll'`.                                      |
| `Conceive(mother, father, opts)`            | boolean, number \| string. Starts a pregnancy without rolling. `opts.encounterRef`, `opts.actor`. Fails with `'invalid_mother'` or `'already_pregnant'`.                                                                                                            |
| `SetPregnancyEncounter(mother, ref)`        | `boolean`. Stores a numeric reference of your own on the pregnancy.                                                                                                                                                                                                 |
| `PregnancyTest(target, actor)`              | `string`. `'positive'`, `'false_positive'` or `'negative'`. A positive marks the pregnancy as known.                                                                                                                                                                |
| `RevealPregnancy(target, actor)`            | `boolean`. Marks the pregnancy as known.                                                                                                                                                                                                                            |
| `StartLabor(target)`                        | `boolean`. Starts labour now.                                                                                                                                                                                                                                       |
| `DeliverBaby(target, actor, reason)`        | `boolean, string`. Records the birth. `false, 'not_pregnant'` when there is none.                                                                                                                                                                                   |
| `TerminatePregnancy(target, actor, reason)` | `boolean, string`. Ends the pregnancy.                                                                                                                                                                                                                              |
| `SetPregnancyNotes(target, notes)`          | `boolean`. Notes of the doctor.                                                                                                                                                                                                                                     |

```lua
local ok, id = exports.cuxial_diseases:RollPregnancy(motherSrc, fatherSrc, { recentCount = 2 })

local result = exports.cuxial_diseases:PregnancyTest(source, source)
if result == 'positive' then
    local info = exports.cuxial_diseases:GetPregnancy(source)
    print(info.week, info.daysToBirth)
end
```

{% hint style="info" %}
Your resource decides which character is the mother before calling `RollPregnancy` or `Conceive`.
{% endhint %}

## Client exports

### GetMyState

Returns the medical state of the local player, with the symptoms in effect right now.

```lua
local cases = exports.cuxial_diseases:GetMyState()
```

**Returns:** `table[]`. Each entry has `id`, `disease`, `label`, `icon`, `color`, `stage`, `stageLabel`, `severity`, `lethal`, `symptoms`, `treatmentActive`, `treatmentUntil` and `diagnosed`. `label` is `nil` while the patient does not know what they have. A pregnancy is one more entry, with `disease = 'pregnancy'`.

### IsSick

```lua
local sick = exports.cuxial_diseases:IsSick()
```

**Returns:** `boolean`. `true` when the state has at least one entry, a pregnancy included.

```lua
if exports.cuxial_diseases:IsSick() then
    -- slower stamina recovery, a HUD icon...
end
```

### GetPregnancyState

```lua
local pregnancy = exports.cuxial_diseases:GetPregnancyState()
```

**Returns:** `table | nil`. `month`, `months`, `week`, `belly` and `labor` of the local player's pregnancy.

## Client events

Both are local events: listen to them with `AddEventHandler` in a client script.

| Event                                    | Parameters      | When                                                                                                                   |
| ---------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `cuxial_diseases:client:StateChanged`    | `cases`         | The medical state of the player changes. Same table as `GetMyState`.                                                   |
| `cuxial_diseases:client:TestResultShown` | `item, results` | The player used a test item. `results` lists the non-negative results: `{ disease, label, result }`. Empty = negative. |

```lua
AddEventHandler('cuxial_diseases:client:StateChanged', function(cases)
    SendNUIMessage({ action = 'sick', value = #cases > 0 })
end)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.cuxial.com/scripts/police-and-medical/cuxial-diseases/developers.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
