> 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/interfaz/cuxial-chat/developers.md).

# Exports y eventos

API pública de Cuxial Chat: exports y eventos para enviar mensajes desde otros recursos.

Envía mensajes al chat, ábrelo o consulta sus canales desde tus propios recursos. Los recursos escritos para el chat estándar no necesitan cambios.

## Exports de servidor

### message

Envía un mensaje a un jugador, a varios o a todos.

```lua
exports.cuxial_chat:message(target, data)
```

| Parámetro       | Tipo                       | Descripción                                                                                                 |
| --------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `target`        | number \| number\[] \| nil | Un id de servidor, una lista de ids, o `-1` / `nil` para todos.                                             |
| `data.text`     | string                     | Texto del mensaje. Obligatorio. Se corta a 600 caracteres.                                                  |
| `data.channel`  | string                     | `id` de un canal de `data/channels.lua`. Si falta o no existe = `system`.                                   |
| `data.author`   | string                     | Nombre que sale como autor.                                                                                 |
| `data.authorId` | number                     | Id de servidor del autor. En un canal con burbujas, el mensaje sale también sobre la cabeza de ese jugador. |
| `data.to`       | string                     | Nombre del destinatario, que se muestra junto al autor.                                                     |
| `data.tags`     | table                      | Lista de etiquetas: `{ { label = 'Texto', color = '#rrggbb' } }`.                                           |
| `data.image`    | string                     | URL de una imagen que se muestra con el mensaje. No se comprueba contra `images.hosts`.                     |
| `data.system`   | boolean                    | Marca el mensaje como de sistema. Por defecto `true` cuando no hay `author`.                                |

**Devuelve:** `boolean`. `true` si el mensaje se envió; `false` si los datos no son válidos o no había ningún id válido.

```lua
exports.cuxial_chat:message(source, {
    channel = 'sancion',
    text = 'Has recibido un aviso: *respeta la zona segura*.',
    tags = { { label = 'Aviso', color = '#f59e0b' } },
})
```

### system

Atajo para un mensaje de sistema.

```lua
exports.cuxial_chat:system(target, text)
```

| Parámetro | Tipo                       | Descripción                                                     |
| --------- | -------------------------- | --------------------------------------------------------------- |
| `target`  | number \| number\[] \| nil | Un id de servidor, una lista de ids, o `-1` / `nil` para todos. |
| `text`    | string                     | Texto del mensaje.                                              |

**Devuelve:** `boolean`.

```lua
exports.cuxial_chat:system(-1, 'Reinicio del servidor en 10 minutos.')
```

### getChannels

Devuelve la lista de canales con los nombres ya traducidos.

```lua
local channels = exports.cuxial_chat:getChannels()
```

**Devuelve:** `table[]`. Cada entrada trae los campos de `data/channels.lua` (`id`, `label`, `voice`, `color`, `tab`, `order`, `icon`, `command`...).

```lua
for _, channel in ipairs(exports.cuxial_chat:getChannels()) do
    print(channel.id, channel.label, channel.color)
end
```

## Exports de cliente

### addMessage

Muestra un mensaje de sistema al jugador local.

```lua
exports.cuxial_chat:addMessage(text, channel)
```

| Parámetro | Tipo   | Descripción                                     |
| --------- | ------ | ----------------------------------------------- |
| `text`    | string | Texto del mensaje.                              |
| `channel` | string | `id` del canal. Opcional; `system` por defecto. |

```lua
exports.cuxial_chat:addMessage('Vehículo guardado.')
```

### open

Abre el chat, si quieres en un canal concreto. No hace nada si el chat ya está abierto.

```lua
exports.cuxial_chat:open(channel)
```

| Parámetro | Tipo   | Descripción               |
| --------- | ------ | ------------------------- |
| `channel` | string | `id` del canal. Opcional. |

```lua
exports.cuxial_chat:open('ooc')
```

### close

Cierra el chat.

```lua
exports.cuxial_chat:close()
```

### isOpen

Indica si el chat está abierto.

```lua
local open = exports.cuxial_chat:isOpen()
```

**Devuelve:** `boolean`.

```lua
if exports.cuxial_chat:isOpen() then return end
```

### refreshMask

Vuelve a comprobar si el jugador lleva máscara. El chat ya lo comprueba cada vez que se abre. Llama a este export desde tu recurso de ropa después de cambiar la máscara para que el nombre anónimo se actualice al momento.

```lua
exports.cuxial_chat:refreshMask()
```

{% hint style="info" %}
El resultado se publica en el state bag del jugador `chatMasked` (`boolean`), que otros recursos pueden leer. Solo se publica con `anonymous.enabled = true`.
{% endhint %}

## Compatibilidad con el chat estándar

Cuxial Chat ocupa el lugar del recurso `chat`, así que el código escrito para el chat por defecto sigue funcionando. Estos mensajes salen en el canal `system`.

### exports.chat:addMessage

{% tabs %}
{% tab title="Cliente" %}

```lua
exports.chat:addMessage({
    color = { 255, 200, 0 },
    args = { 'Garaje', 'Vehículo guardado.' },
})
```

{% endtab %}

{% tab title="Servidor" %}

```lua
exports.chat:addMessage(source, {
    args = { 'Garaje', 'Vehículo guardado.' },
})
```

{% endtab %}
{% endtabs %}

Formas de mensaje aceptadas:

| Forma                         | Resultado                                                                                     |
| ----------------------------- | --------------------------------------------------------------------------------------------- |
| Una cadena de texto           | Se muestra como texto.                                                                        |
| `args = { 'Autor', 'Texto' }` | Autor y texto.                                                                                |
| `args = { 'Texto' }`          | Solo texto.                                                                                   |
| `template`                    | Solo se usa cuando `args` no trae texto. Se muestra como texto plano, sin las etiquetas HTML. |
| `color = { r, g, b }`         | Añade una etiqueta de color al mensaje.                                                       |

### Eventos de cliente

| Evento                  | Parámetros              | Qué hace                                                             |
| ----------------------- | ----------------------- | -------------------------------------------------------------------- |
| `chat:addMessage`       | `message`               | Añade un mensaje. Mismas formas que el export.                       |
| `chatMessage`           | `author, color, text`   | Añade un mensaje con el formato antiguo.                             |
| `chat:clear`            | ninguno                 | Limpia el chat.                                                      |
| `chat:show`             | ninguno                 | Abre el chat.                                                        |
| `chat:addSuggestion`    | `command, help, params` | Añade un comando al autocompletado.                                  |
| `chat:addSuggestions`   | `list`                  | Añade varios comandos. Cada entrada lleva `name`, `help` y `params`. |
| `chat:removeSuggestion` | `command`               | Quita un comando de la lista.                                        |

```lua
TriggerClientEvent('chat:addSuggestion', -1, '/reparar', 'Repara el vehículo', {
    { name = 'id', help = 'Id del jugador' },
})
```

### Evento de servidor: chatMessage

Se dispara en el servidor antes de entregar un mensaje escrito sin comando. Cancélalo para bloquear el mensaje.

| Parámetro | Tipo   | Descripción               |
| --------- | ------ | ------------------------- |
| `source`  | number | Id de servidor del autor. |
| `name`    | string | Nombre del personaje.     |
| `text`    | string | Texto del mensaje.        |

```lua
AddEventHandler('chatMessage', function(source, name, text)
    if text:find('prohibido') then
        CancelEvent()
    end
end)
```

{% hint style="info" %}
Los mensajes enviados con un comando (`/me`, `/do`, `/pm`...) no disparan este evento.
{% endhint %}


---

# 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/interfaz/cuxial-chat/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.
