> 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/es/policia-y-medico/cuxial-medical/developers.md).

# Exports y eventos

API pública de Cuxial Medical: exports, hooks, state bags y eventos para usar desde otros recursos.

Lee el estado médico de un jugador, reanímalo, cúralo o hiérelo, y reacciona a lo que ocurre desde tus propios recursos. Todos los exports se llaman como `exports.cuxial_medical:Nombre(...)`.

## Valores comunes

| Valor           | Opciones                                                                                              |
| --------------- | ----------------------------------------------------------------------------------------------------- |
| Estado          | `'alive'`, `'laststand'`, `'dead'`                                                                    |
| Zona del cuerpo | `head`, `neck`, `spine`, `upper_body`, `lower_body`, `left_arm`, `right_arm`, `left_leg`, `right_leg` |
| Tipo de herida  | `shot`, `stabbed`, `beat`, `burned`                                                                   |
| Nivel           | Del 1 al 4                                                                                            |
| Modo de RCP     | `'fast'`, `'full'`                                                                                    |

Los exports que actúan en nombre de un médico devuelven `ok, reason`. Motivos posibles:

| Motivo                 | Significado                                            |
| ---------------------- | ------------------------------------------------------ |
| `no_ems_duty`          | El médico no es EMS de servicio.                       |
| `no_target`            | El objetivo no existe.                                 |
| `not_dead`             | El objetivo no está caído.                             |
| `is_down`              | El objetivo está caído.                                |
| `too_far`              | Médico y objetivo están demasiado lejos.               |
| `cooldown`             | El médico actuó hace muy poco.                         |
| `rate_limit`           | Demasiadas peticiones.                                 |
| `no_item`              | Al médico le falta el ítem exigido.                    |
| `no_injury`            | No hay nada que tratar.                                |
| `no_config`, `no_zone` | Falta el bloque de configuración o la zona del cuerpo. |

## Exports de servidor

### Estado

| Export                      | Devuelve                                                                                            |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
| `IsPlayerDead(src)`         | `false`, `'laststand'` o `'dead'`.                                                                  |
| `GetPlayerPhase(src)`       | `0` si está vivo; si no, el número de fase.                                                         |
| `GetPlayerDeathInjury(src)` | `{ injury, location, name }` del golpe que tumbó al jugador, o `nil`. `name` es el nombre del arma. |
| `GetMedicalState(src)`      | `{ isDead, phase, deathInjury, injuries }`.                                                         |
| `GetAllDeadPlayers()`       | `{ [src] = estado }` de todos los jugadores caídos.                                                 |
| `GetAllMedicalStates()`     | `{ [src] = { state, phase, deathInjury, injuries } }` de todos los jugadores caídos.                |

```lua
if exports.cuxial_medical:IsPlayerDead(source) then
    return -- el jugador está caído
end
```

### KillPlayer

Tumba a un jugador. Si ya está caído, lo pasa a la fase siguiente.

```lua
exports.cuxial_medical:KillPlayer(target)
```

**Devuelve:** `boolean`. `false` cuando el jugador no existe.

### RevivePlayer

Reanima a un jugador, le quita las heridas y restablece hambre, sed y estrés. Funciona con cualquier jugador, sin ítem y sin comprobar la distancia.

```lua
exports.cuxial_medical:RevivePlayer(target, options)
```

| Parámetro      | Tipo                   | Descripción                                                                                                                               |
| -------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `target`       | number                 | Id de servidor del jugador.                                                                                                               |
| `options`      | table \| number \| nil | Una tabla `{ anim, hp, by }`, o el id de servidor de quien reanima.                                                                       |
| `options.anim` | boolean                | `true` reproduce la animación de levantarse. Con una tabla está desactivada salvo que se indique; con un número o sin nada está activada. |
| `options.hp`   | number                 | Vida final, hasta 200. Vida completa si se omite.                                                                                         |
| `options.by`   | number                 | Id de servidor de quien reanima, para el registro.                                                                                        |

**Devuelve:** `boolean`.

```lua
exports.cuxial_medical:RevivePlayer(target, { anim = true, by = source })
```

### RevivePlayerWithHP

Reanima a un jugador sin animación y con una vida exacta.

```lua
exports.cuxial_medical:RevivePlayerWithHP(target, hp)
```

| Parámetro | Tipo   | Descripción                                                           |
| --------- | ------ | --------------------------------------------------------------------- |
| `target`  | number | Id de servidor del jugador.                                           |
| `hp`      | number | Vida final, de 1 a 200. El jugador nunca se levanta con menos de 101. |

**Devuelve:** `boolean`.

### HealPlayer

Cura a un jugador, le quita las heridas y restablece hambre, sed y estrés. A un jugador caído primero lo reanima, sin animación.

```lua
exports.cuxial_medical:HealPlayer(target, full, quiet)
```

| Parámetro | Tipo    | Descripción                                   |
| --------- | ------- | --------------------------------------------- |
| `target`  | number  | Id de servidor del jugador.                   |
| `full`    | boolean | `true` devuelve toda la vida. Si no, suma 25. |
| `quiet`   | boolean | `true` oculta la notificación.                |

**Devuelve:** `boolean`.

```lua
exports.cuxial_medical:HealPlayer(source, true, true)
```

### Otros exports de tratamiento

| Export                         | Qué hace                                                                     | Devuelve  |
| ------------------------------ | ---------------------------------------------------------------------------- | --------- |
| `HealPlayerBy(target, amount)` | Suma `amount` de vida, hasta 200. No toca las heridas.                       | `boolean` |
| `SedatePlayer(target)`         | Seda al jugador durante `items.sedate.duration`. Falla con un jugador caído. | `boolean` |
| `ResetPlayerNeeds(src)`        | Pone hambre y sed a 100 y estrés a 0.                                        | nada      |

### Actuar como médico

Estos exports aplican las mismas reglas que las acciones del propio médico: EMS de servicio, distancia, espera e ítems.

| Export                                    | Qué hace                                                                   | Devuelve                  |
| ----------------------------------------- | -------------------------------------------------------------------------- | ------------------------- |
| `GetPatientReport(medic, target)`         | Informe completo de un paciente.                                           | `report`, o `nil, reason` |
| `CanResuscitate(medic, target, mode)`     | Comprueba si el médico puede reanimar al paciente.                         | `ok, reason`              |
| `ResuscitatePatient(medic, target, mode)` | Reanima al paciente y consume el ítem del modo de RCP.                     | `ok, reason`              |
| `TreatZone(medic, target, bodyZone)`      | Venda una zona: quita esa herida y devuelve vida. Usa `treatment.bandage`. | `ok, reason`              |

El informe contiene `targetId`, `firstname`, `lastname`, `fullName`, `citizenid`, `isDead`, `state`, `phase`, `phaseKey`, `phaseLabel`, `health`, `maxHealth`, `hpPercent`, `deathInjury`, `injuries`, `maxSeverity`, `totalBleed` y `timestamp`. Cada entrada de `injuries` va indexada por zona del cuerpo y tiene `injury`, `level`, `bleed`, `label` e `injuryLabel`.

```lua
local ok, reason = exports.cuxial_medical:ResuscitatePatient(source, target, 'fast')
if not ok then print(reason) end
```

### EMS

| Export             | Devuelve                   |
| ------------------ | -------------------------- |
| `GetEMSCount()`    | Número de EMS de servicio. |
| `IsEMSOnDuty(src)` | `boolean`.                 |

### Heridas

| Export                                            | Qué hace                                                      | Devuelve                                                                          |
| ------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `InjurePlayer(src, bodyZone, type, level, bleed)` | Añade o sustituye la herida de una zona. `bleed` va de 0 a 4. | `boolean`                                                                         |
| `ClearInjury(src, bodyZone)`                      | Quita la herida de una zona.                                  | nada                                                                              |
| `ClearInjuryType(src, type)`                      | Quita todas las heridas de un tipo.                           | nada                                                                              |
| `ClearPlayerInjuries(src)`                        | Quita todas las heridas.                                      | nada                                                                              |
| `GetPlayerInjuries(src)`                          |                                                               | `{ [zona] = { bodyPart, injury, level, bleed } }`                                 |
| `GetInjuryAt(src, bodyZone)`                      |                                                               | La herida de esa zona, o `nil`.                                                   |
| `HasInjury(src, bodyZone)`                        | Sin `bodyZone`, comprueba si hay alguna herida.               | `boolean`                                                                         |
| `GetMaxSeverity(src)`                             |                                                               | Nivel más alto, `0` sin heridas.                                                  |
| `GetTotalBleed(src)`                              |                                                               | Suma del sangrado de todas las heridas.                                           |
| `DiagnosePlayer(src)`                             |                                                               | `{ injuries, maxSeverity, totalBleed, deathInjury }`, con los nombres traducidos. |
| `GetAllInjuredPlayers()`                          |                                                               | `{ [src] = { count, maxSeverity, totalBleed } }`                                  |

```lua
exports.cuxial_medical:InjurePlayer(source, 'left_leg', 'stabbed', 2, 1)
```

### Historial médico

Se guarda en `cuxial_medical_logs`. Con `logs.persistence = false` no se escribe.

| Export                                                       | Qué hace                                                                                                                          | Devuelve                                                                                  |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `LogMedicalEvent(patientSrc, eventType, doctorSrc, payload)` | Guarda un evento. `eventType` es `death`, `revive`, `treat`, `diagnose` o `heal`. `doctorSrc` y `payload` (tabla) son opcionales. | nada                                                                                      |
| `GetMedicalHistory(citizenid, limit)`                        | Últimos eventos de un personaje. `limit` es 25 por defecto, 100 como máximo.                                                      | Filas con `id`, `event_type`, `doctor_citizenid`, `doctor_name`, `payload`, `created_at`. |
| `GetDoctorMedicalStats(doctorCitizenid, since)`              | Cuenta las acciones de un médico. `since` es una marca de tiempo en milisegundos.                                                 | `{ revives, treats, diagnoses, heals }`                                                   |

```lua
local history = exports.cuxial_medical:GetMedicalHistory(citizenid, 10)
```

### getSetting

Devuelve el valor en vivo de una sección de ajustes.

```lua
local phases = exports.cuxial_medical:getSetting('config.death').phases
```

Identificadores válidos: `config.jobs`, `config.death`, `config.respawn`, `config.injury`, `config.treatment`, `config.items`, `config.stretcher`, `config.finisher`, `config.extras`, `config.dispatch`, `config.logs` y `data.hospitals`. Cualquier otro devuelve `nil`.

## Hooks de servidor

Registra una función que se ejecuta cuando ocurre algo. Cada export `on…` devuelve la función, para pasarla al export `off…` correspondiente.

```lua
exports.cuxial_medical:onTreatment('revive', function(medic, target, data)
    print(('%s reanimó a %s (%s)'):format(medic, target, data.mode))
end)
```

| Export                         | Evento                       | Argumentos                                                                          |
| ------------------------------ | ---------------------------- | ----------------------------------------------------------------------------------- |
| `onTreatment` / `offTreatment` | `revive`                     | `medic, target, { health, injury, mode }`. Solo reanimaciones hechas por un médico. |
|                                | `heal`                       | `medic, target`                                                                     |
|                                | `treatStart`, `treatEnd`     | `medic, target, woundType`                                                          |
|                                | `diagnose`                   | `medic, target`                                                                     |
| `onFinisher` / `offFinisher`   | `finished`                   | `attacker, victim`                                                                  |
| `onHospital` / `offHospital`   | `bedReserved`, `bedReleased` | `src, hospitalId, bedIndex`                                                         |
|                                | `charged`                    | `src, account, cost, hospitalId`                                                    |
| `onStretcher` / `offStretcher` | `add`, `remove`              | `{ netId, owner }`                                                                  |
|                                | `seat`                       | `{ netId, target, medic, pose }`                                                    |
|                                | `unseat`                     | `{ netId, target, reason }`                                                         |
| `onDispatch` / `offDispatch`   | `requestAdded`               | `src, name`                                                                         |
|                                | `requestRemoved`             | `src`                                                                               |

## Exports de cliente

### Estado

| Export                                            | Devuelve                                                                                   |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `isPlayerDead(serverId)`                          | `false`, `'laststand'` o `'dead'`. Sin `serverId`, el jugador local.                       |
| `getDeathPhase()`                                 | Fase del jugador local, `0` si está vivo.                                                  |
| `getDeathPhaseKey()`                              | `id` de la fase actual, o `nil`.                                                           |
| `getMedicalState()`                               | `{ isDead, phase, phaseKey, injury, location, weapon }`                                    |
| `isZoomActive()`                                  | `boolean`                                                                                  |
| `pauseDeathAnimation()`, `resumeDeathAnimation()` | Detienen y reanudan la animación de caído, para reproducir la tuya sobre un jugador caído. |

```lua
if exports.cuxial_medical:isPlayerDead() then return end
```

### Heridas

Todos actúan sobre el jugador local.

| Export                                                                 | Devuelve                                     |
| ---------------------------------------------------------------------- | -------------------------------------------- |
| `GetPlayerInjuries()`                                                  | `{ [zona] = herida }`                        |
| `GetInjuryAt(bodyZone)`                                                | La herida, o `nil`.                          |
| `HasInjury(bodyZone)`                                                  | `boolean`. Sin `bodyZone`, cualquier herida. |
| `IsInjured()`, `IsLimping()`, `IsBleeding()`                           | `boolean`                                    |
| `GetMaxSeverity()`, `GetTotalBleed()`                                  | `number`                                     |
| `AddInjury(bodyZone, type, level, bleed)`                              | `boolean`                                    |
| `ClearInjury(bodyZone)`, `ClearInjuryType(type)`, `ClearAllInjuries()` | nada                                         |

### Hospital

| Export                             | Qué hace                                                                                                                                                    | Devuelve        |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
| `requestCheckIn(hospitalId)`       | Registro con las reglas de la recepción: hospital activo, jugador en pie, dentro del radio y con los médicos permitiéndolo. Avisa al jugador si se rechaza. | `boolean`       |
| `attemptCheckIn(hospitalId)`       | Inicia el registro sin esas reglas.                                                                                                                         | `boolean`       |
| `layOnBed(hospitalId, bedIndex)`   | Tumba al jugador en una cama.                                                                                                                               | `boolean`       |
| `getUpFromBed()`                   | Levanta al jugador.                                                                                                                                         | nada            |
| `resolveBed(hospitalId, bedIndex)` | Posición, orientación y animaciones de una cama.                                                                                                            | `table` o `nil` |

`hospitalId` es opcional en los dos exports de registro: se usa el hospital activo más cercano. Esperan hasta que termina el tratamiento.

```lua
exports.cuxial_medical:requestCheckIn()
```

### Acciones de médico

Para menús y ruedas radiales. Actúan sobre el jugador más cercano, necesitan EMS de servicio y siguen las reglas de los ítems.

| Export                    | Qué hace                                                                       | Devuelve             |
| ------------------------- | ------------------------------------------------------------------------------ | -------------------- |
| `reviveTarget(options)`   | RCP sobre el jugador caído más cercano. `options.mode` es `'fast'` o `'full'`. | `boolean`            |
| `healTarget()`            | Cura al jugador más cercano, o a ti mismo.                                     | `boolean`            |
| `useSedative()`           | Seda al jugador más cercano.                                                   | `boolean`            |
| `treatPatient(woundType)` | Trata un tipo de herida.                                                       | `boolean`            |
| `diagnosePlayer()`        | Diagnostica al jugador más cercano y muestra el resultado.                     | `report` o `nil`     |
| `ToggleDuty()`            | Cambia el servicio de EMS.                                                     | `ok, onduty`         |
| `GetDistressRequests()`   | Avisos de auxilio abiertos.                                                    | `{ [src] = nombre }` |
| `PlaceInVehicle()`        | Sube al jugador caído o sedado más cercano al vehículo más cercano.            | `boolean`            |
| `RemoveFromVehicle()`     | Hace salir a los ocupantes del vehículo más cercano.                           | `boolean`            |
| `IntoVehicle()`           | Mete al jugador local en un asiento libre del vehículo más cercano.            | `boolean`            |
| `RemoveWeapons()`         | Quita todas las armas del jugador local.                                       | nada                 |

```lua
exports.cuxial_medical:reviveTarget({ mode = 'full' })
```

### Animación de RCP

| Export                             | Qué hace                                                                                                        | Devuelve                  |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------- |
| `ReviveAnimation(target, options)` | Reproduce la animación de RCP en médico y paciente. `options`: `mode`, `lockCamera`, `unarmTarget`. No reanima. | `true` cuando se completa |
| `CancelReviveAnimation(target)`    | La cancela.                                                                                                     | `boolean`                 |
| `IsReviveInProgress()`             |                                                                                                                 | `busy, target, mode`      |
| `GetReviveAnimDuration(mode)`      |                                                                                                                 | Milisegundos              |

### Camilla

| Export                          | Qué hace                                                                               |
| ------------------------------- | -------------------------------------------------------------------------------------- |
| `toggleStretcher()`             | Igual que `/stretcher`.                                                                |
| `spawnStretcher()`              | Coloca una camilla. Devuelve `entity, netId`.                                          |
| `pickupStretcher()`             | Recoge la camilla que haya a menos de 3 metros. Devuelve `boolean`.                    |
| `deleteStretcher()`             | Elimina la camilla que haya a menos de 5 metros.                                       |
| `placeNearestOnStretcher(pose)` | Sube al jugador caído o sedado más cercano a la camilla más cercana.                   |
| `removeFromStretcher()`         | Baja al paciente de la camilla más cercana.                                            |
| `toggleStretcherExtra(name)`    | Activa o quita un accesorio: `headrest`, `backboard`, `monitor`, `redbag` o `bluebag`. |
| `isPlayerUsingStretcher()`      | `true` cuando el jugador local está tumbado en una camilla.                            |

Posturas: `lie_back` (por defecto), `lie_left`, `lie_prone`, `sit_up`, `sit_end`, `sit_left`, `sit_right`, `cpr`.

```lua
exports.cuxial_medical:placeNearestOnStretcher('sit_up')
```

### Remate y nocaut

| Export                       | Qué hace                                                            |
| ---------------------------- | ------------------------------------------------------------------- |
| `performFinisher(victimPed)` | Inicia el remate sobre ese ped. Devuelve `boolean`.                 |
| `isFinisherBusy()`           | `boolean`                                                           |
| `manuallyKnockout()`         | Noquea al jugador local. Necesita `extras.knockout.enabled = true`. |
| `disableKnockoutLoop(state)` | `true` bloquea los nocauts, `false` los vuelve a permitir.          |

## Hooks de cliente

Mismo patrón que los hooks de servidor.

```lua
exports.cuxial_medical:onDeath('playerDeath', function(data)
    print(data.state, data.injury, data.bodyPart)
end)
```

| Export                           | Evento                                | Argumentos                                                                    |
| -------------------------------- | ------------------------------------- | ----------------------------------------------------------------------------- |
| `onDamage` / `offDamage`         | `damaged`                             | `{ ped, weapon, bone, healthDiff, armourDiff, currentHealth, currentArmour }` |
|                                  | `died`                                | `{ ped, weapon, bone, cause, via }`                                           |
| `onInjury` / `offInjury`         | `applied`                             | `{ bodyPart, injury, level, bleed, weapon }`                                  |
|                                  | `cleared`                             | `{ bodyPart }`                                                                |
|                                  | `allCleared`, `limpStart`, `limpStop` | ninguno                                                                       |
|                                  | `blackout`                            | `{ bodyPart, level, duration }`                                               |
| `onDeath` / `offDeath`           | `playerDeath`                         | `{ state, injury, bodyPart, weapon }`                                         |
|                                  | `phaseChange`, `resume`               | `phaseIndex, phaseId`                                                         |
|                                  | `playerSpawn`                         | ninguno                                                                       |
| `onReviveAnim` / `offReviveAnim` | `started`, `complete`, `cancelled`    | `target, mode`                                                                |

## State bags

Los escribe el servidor. Léelos, no los escribas.

| State bag                | Ámbito  | Valor                                                                            |
| ------------------------ | ------- | -------------------------------------------------------------------------------- |
| `cuxial:state`           | Jugador | `'alive'`, `'laststand'` o `'dead'`                                              |
| `cuxial:phase`           | Jugador | Número de fase, `0` si está vivo                                                 |
| `cuxial:injuries`        | Jugador | `{ [zona] = { bodyPart, injury, level, bleed } }`, o `nil`                       |
| `isDead`                 | Jugador | `boolean`                                                                        |
| `qbx_medical:deathState` | Jugador | `1` vivo, `2` último aliento, `3` muerto. Con `compat.qbxMedicalStateBag = true` |
| `cuxialEmsOnline`        | Global  | EMS de servicio                                                                  |

```lua
local downed = Player(source).state['cuxial:state'] ~= 'alive'
local medics = GlobalState.cuxialEmsOnline or 0
```

Los metadatos del jugador `isdead` e `inlaststand` también se mantienen al día.

### Excluir a un jugador

Pon el state bag de jugador `inDuel` o `inEvent` a cualquier valor y Cuxial Medical ignora el daño y la muerte de ese jugador. Vuelve a ponerlo a `nil` para dejarlo como antes.

```lua
Player(source).state:set('inEvent', true, true)
```

## Eventos

### Aviso de auxilio

Envía un aviso de auxilio del jugador, esté caído o no. Úsalo desde un teléfono o un botón del pánico.

```lua
TriggerServerEvent('cuxial_medical:server:Dispatch', { street = 'Alta Street' })
```

`street` es opcional. La posición se toma del jugador en el servidor. Se aplica la espera de `dispatch.cooldownMs`.

### Eventos de compatibilidad

Los recursos escritos para el trabajo de ambulancia de QBCore siguen funcionando con estos eventos:

| Evento                           | Lado     | Qué hace                                                                                             |
| -------------------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
| `hospital:client:Revive`         | Cliente  | Pide reanimarse a uno mismo. Solo se acepta para el staff y para jugadores con `inDuel` o `inEvent`. |
| `hospital:client:RevivePlayer`   | Cliente  | El médico reanima al jugador más cercano.                                                            |
| `hospital:client:TreatWounds`    | Cliente  | El médico cura al jugador más cercano.                                                               |
| `hospital:client:CheckStatus`    | Cliente  | El médico diagnostica al jugador más cercano.                                                        |
| `hospital:server:emergencyAlert` | Servidor | Envía un aviso de auxilio.                                                                           |

Con `compat.qbxMedicalEvents = true` el script dispara además `qbx_medical:client:onPlayerDied`, `qbx_medical:client:onPlayerLaststand` y `qbx_medical:client:playerRevived` en el jugador.


---

# 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/es/policia-y-medico/cuxial-medical/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.
