Owncast Plugin APIs
El tiempo de ejecución del complemento de Owncast expone un único global, owncast, con las funciones anfitrionas que tu complemento puede llamar. Most methods require the matching permission in your manifest. A call without it never reaches Owncast: the host logs the denial and the call does nothing. What your plugin sees depends on the method. Mutating calls that report an outcome raise an error (moderation, users.register, auth.grantSession, kv.set, videoConfig.write, actions.add, actions.clear, and every sql method), readers return an empty or zero value, and calls that return nothing become silent no-ops. fs.write, fs.delete, and storage.upload are the exceptions: they report failure in their return value rather than raising. A few methods are ambient and need no permission: logging, timers, reading bundled assets, and owncast.config.get.
Plugins require Owncast 0.3.0 or later.
Las llamadas se muestran para ambos SDK, elige tu lenguaje con las pestañas. Consulta JavaScript o Python para la configuración. (Los nombres de métodos de JavaScript son camelCase, Python usa snake_case, así que sendAction se convierte en send_action, y así sucesivamente).
Logging
owncast.log.info(message), .warning(message), and .error(message)
Write an operator-visible entry to Owncast's server log. Owncast records the calling plugin's slug and the matching info, warning, or error severity. It replaces control characters with spaces so each entry stays on one line, then truncates messages longer than 4 KiB.
- JavaScript
- Python
owncast.log.info('sync started');
owncast.log.warning('provider response is incomplete');
owncast.log.error('sync failed');
owncast.log.info("sync started")
owncast.log.warning("provider response is incomplete")
owncast.log.error("sync failed")
Ambient: no se requiere permiso. See the paired chat-logger examples for JavaScript and Python.
Chat
¿Construyendo un bot de chat, herramienta de moderación o filtro? Comienza con Complementos de Chat.
owncast.chat.send(text)
Publica un mensaje de chat. Enviado como la identidad de bot de tu complemento (nombre para mostrar de bot.displayName o name en tu manifiesto).
- JavaScript
- Python
owncast.chat.send('hello chat');
owncast.chat.send("hello chat")
Requiere chat.send.
owncast.chat.sendAction(text)
Publica un mensaje de tipo acción ("/me").
- JavaScript
- Python
owncast.chat.sendAction('is now live');
owncast.chat.send_action("is now live")
Requiere chat.send.
owncast.chat.system(body)
Publica un mensaje de anuncio del servidor. Sin identidad de bot adjunta. El cuerpo se renderiza en línea como HTML, así que usa esto para avisos cortos atribuidos al servidor como "la transmisión comenzará en 5 minutos". Trata el cuerpo como salida HTML no confiable: no interpoles la entrada del usuario en él sin escapar.
Requires chat.send.
owncast.chat.sendTo(clientId, text)
Envía un mensaje privado a un solo cliente conectado.
Requires chat.send.
owncast.chat.replyTo(msg, text)
Susurra una respuesta a quien envió un mensaje de chat. Pasa el mensaje de chat de onChatMessage/filterChatMessage (o un ID de cliente simple). Devuelve false si la conexión del remitente es desconocida (sin ID de cliente), por lo que puedes volver a un send público. Azúcar sobre sendTo(clientId, text).
- JavaScript
- Python
onChatMessage(msg) {
if (!owncast.chat.replyTo(msg, "got it")) {
owncast.chat.send("got it");
}
}
@plugin.on_chat_message
def handle(msg):
if not owncast.chat.reply_to(msg, "got it"):
owncast.chat.send("got it")
Requiere chat.send.
owncast.chat.history(limit?)
Devuelve los mensajes de chat más recientes, cada uno con id, user, body y timestamp. limit tiene un valor predeterminado de 50.
Requiere chat.history.
owncast.chat.clients()
Return the list of currently-connected chat clients, each with id, userId?, displayName?, connectedAt?, userAgent?, ipAddress?, and messageCount. id es el ID de cliente por conexión utilizado por chat.kick.
Requiere chat.history.
owncast.chat.deleteMessage(messageId)
Oculta un mensaje de chat de los espectadores.
Requires chat.moderate.
owncast.chat.kick(clientId)
Desconecta a un cliente de chat.
Requires chat.moderate.
Identidad de chat
Cada complemento tiene exactamente una identidad de chat, el bot que Owncast proporciona cuando tu complemento está instalado. El nombre para mostrar es el bot.displayName de tu manifiesto si está configurado, de lo contrario, es su name, con IsBot: true. Tanto send como sendAction publican como esta identidad, a través del canal de chat normal de Owncast (filtros, límites de tasa, moderación). Los complementos no pueden publicar bajo nombres arbitrarios ni suplantar a usuarios reales.
El usuario bot se basa en el slug del complemento, por lo que la identidad sobrevive a las ediciones del manifiesto de name o bot.displayName. Si necesitas múltiples personas de chat, envía múltiples complementos.
Usuarios
owncast.users.list() y owncast.users.get(id)
Lee la lista de usuarios de chat o el registro de un solo usuario.
- JavaScript
- Python
const users = owncast.users.list();
const alice = owncast.users.get('u-alice');
users = owncast.users.list()
alice = owncast.users.get("u-alice")
Requiere users.read.
owncast.users.setEnabled(id, enabled, reason?)
Habilita o deshabilita un usuario de chat.
- JavaScript
- Python
owncast.users.setEnabled('u-spammer', false, 'spam');
owncast.users.set_enabled("u-spammer", False, "spam")
Requiere users.moderate.
owncast.users.banIP(ip)
Prohíbe una IP de unirse al chat.
- JavaScript
- Python
owncast.users.banIP('203.0.113.42');
owncast.users.ban_ip("203.0.113.42")
Requiere users.moderate.
owncast.users.register({ authId, displayName?, scopes?, profileUrl?, handle?, public? })
Find or create an authenticated Owncast user for an external identity and return { userId }. Pass the provider's stable authId without adding your plugin slug. The host stores the slug separately as the identity provider, so plugins cannot collide with or spoof each other's users. displayName seeds a new user's name and is optional: omit it, or pass null, and Owncast generates a display name the same way it does for anonymous viewers. Non-empty scopes such as ["MODERATOR"] are applied on each call.
The optional profileUrl, handle, and public fields describe a verified external identity. profileUrl must be empty or an absolute HTTP(S) URL. handle is the provider's verified label, such as a GitHub login or fediverse handle. Set public to true only after the viewer opts into public display. It defaults to false. These profile fields are captured when the identity is first registered. Later calls with the same authId return the existing user but do not change the stored profile fields.
- JavaScript
- Python
const { userId } = owncast.users.register({
authId: 'github:583231',
displayName: 'octocat',
profileUrl: 'https://github.com/octocat',
handle: 'octocat',
public: false, // Set true only after the viewer opts in.
});
result = owncast.users.register(
"github:583231",
display_name="octocat",
profile_url="https://github.com/octocat",
handle="octocat",
public=False, # Set true only after the viewer opts in.
)
user_id = result.user_id
Requiere users.register.
Autenticación
Estos impulsan un puerta de autenticación de espectadores. grantSession y endSession solo funcionan dentro de un controlador onHttpRequest, porque el anfitrión adjunta la cookie de sesión a la respuesta HTTP en vuelo.
owncast.auth.grantSession({ userId, ttl? })
Emite una sesión firmada para un usuario ya registrado (el userId de owncast.users.register). El anfitrión emite, firma y adjunta la cookie de sesión a la respuesta actual; tu complemento nunca ve el token, por lo que no puede falsificarlo o filtrarlo. ttl es una duración opcional en segundos (0/omitido usa el valor predeterminado del anfitrión de 24 horas).
- JavaScript
- Python
const { userId } = owncast.users.register({ authId: 'shared', displayName: 'Guest' });
owncast.auth.grantSession({ userId });
return { status: 302, headers: { Location: returnTo } };
result = owncast.users.register("shared", display_name="Guest")
owncast.auth.grant_session(result.user_id)
return {"status": 302, "headers": {"Location": return_to}}
Requiere auth.gate.
owncast.auth.endSession()
Limpia la cookie de sesión del visualizador actual en esta respuesta para cerrar sesión. Tu complemento aún controla la redirección (y puede redirigir al propio cierre de sesión del proveedor).
- JavaScript
- Python
owncast.auth.endSession();
return { status: 302, headers: { Location: '/' } };
owncast.auth.end_session()
return {"status": 302, "headers": {"Location": "/"}}
Requiere auth.gate.
Almacenamiento
owncast.kv.get(key) y owncast.kv.set(key, value)
Almacenamiento clave/valor por complemento, nombrado por el slug de tu complemento. Los valores son cadenas.
Para tipos más ricos, usa los ayudantes de JSON (getJSON / setJSON, get_json / set_json en Python) en lugar de analizar y serializar tú mismo. El getter JSON devuelve el valor de respaldo cuando la clave no está configurada o contiene JSON inválido. Los complementos no pueden leer las claves de otros complementos.
- JavaScript
- Python
owncast.kv.set('count', '1');
const n = Number(owncast.kv.get('count') ?? '0');
owncast.kv.setJSON('prefs', { theme: 'dark' });
const prefs = owncast.kv.getJSON('prefs', {});
owncast.kv.set("count", "1")
n = int(owncast.kv.get("count") or "0")
owncast.kv.set_json("prefs", {"theme": "dark"})
prefs = owncast.kv.get_json("prefs", {})
Requiere storage.kv.
owncast.storage.upload(name, data)
Sube un archivo al área de archivos pública de Owncast. JavaScript accepts a Uint8Array or string. Python accepts bytes or str. Raw bytes are preserved, while strings are encoded as UTF-8. JavaScript returns { url } or null. Python returns a dict accessed as result["url"], or None.
Requiere storage.upload.
owncast.fs.*
A private, sandboxed filesystem at data/plugin-storage/\<your-slug>/files/. A diferencia de owncast.storage.upload, estos archivos permanecen en el servidor: nunca se sirven a través de HTTP. Las rutas son relativas a la raíz de tu espacio aislado. El anfitrión restringe cada ruta a tu propio directorio (un complemento no puede leer los archivos de otro complemento, y ../ o rutas absolutas vuelven a colapsar dentro del espacio aislado). Los directorios principales se crean según sea necesario al escribir.
| JavaScript | Python | Devuelve |
|---|---|---|
fs.read(path) | fs.read(path) | Uint8Array / bytes, or null / None if missing |
fs.readText(path) | fs.read_text(path) | UTF-8 string / str, or null / None if missing |
fs.write(path, data) | fs.write(path, data) | { error? } |
fs.list(dir) | fs.list(dir) | nombres de entrada (un directorio faltante está vacío) |
fs.delete(path) | fs.delete(path) | { error? } for a file or empty directory |
fs.exists(path) | fs.exists(path) | booleano |
fs.read preserves the original bytes. fs.readText and fs.read_text decode UTF-8. Python replaces malformed byte sequences when decoding. fs.write preserves a JavaScript Uint8Array or Python bytes, and UTF-8 encodes strings. fs.write and fs.delete return {} on success. If the host rejects the operation, they return { error } with the reason.
- JavaScript
- Python
owncast.fs.write('notes/log.txt', 'hello');
const text = owncast.fs.readText('notes/log.txt');
const data = new Uint8Array([0xff, 0x00, 0x80]);
owncast.fs.write('cache/data.bin', data);
const stored = owncast.fs.read('cache/data.bin');
if (stored) owncast.storage.upload('data.bin', stored);
owncast.fs.write("notes/log.txt", "hello")
text = owncast.fs.read_text("notes/log.txt")
data = bytes((0xFF, 0x00, 0x80))
owncast.fs.write("cache/data.bin", data)
stored = owncast.fs.read("cache/data.bin")
if stored is not None:
owncast.storage.upload("data.bin", stored)
Requiere storage.fs.
owncast.sql.*
One private SQLite database per plugin, at data/plugin-storage/\<your-slug>/db/plugin.db, separate from Owncast's own database and from the storage.fs sandbox. The sandbox is rooted at files/, so db/ is not a path owncast.fs.* refuses but one it cannot express, and the filesystem quota walk covers files/ only, so the two quotas stay independent. Reach for this over storage.kv when you need to sort, filter, or aggregate rather than just remember a value.
| Method | Returns |
|---|---|
sql.exec(sql, params?) | { rowsAffected, lastInsertId } |
sql.query(sql, params?) | rows as objects keyed by column name |
sql.queryRow(sql, params?) | the first row object, or null when nothing matched |
In Python queryRow is query_row, rows come back as dicts, and query_row returns None when nothing matched. An error throws in JavaScript and raises RuntimeError in Python. Parameters are null/None, booleans, numbers, or strings. Anything else is refused.
- JavaScript
- Python
owncast.sql.exec(`CREATE TABLE IF NOT EXISTS chatters (
user_id TEXT PRIMARY KEY,
messages INTEGER NOT NULL DEFAULT 0
)`);
owncast.sql.exec(
`INSERT INTO chatters (user_id, messages) VALUES (?, 1)
ON CONFLICT (user_id) DO UPDATE SET messages = messages + 1`,
[msg.user.id],
);
const top = owncast.sql.query(
'SELECT user_id, messages FROM chatters ORDER BY messages DESC LIMIT ?',
[5],
);
const mine = owncast.sql.queryRow('SELECT messages FROM chatters WHERE user_id = ?', [msg.user.id]);
owncast.sql.exec("""
CREATE TABLE IF NOT EXISTS chatters (
user_id TEXT PRIMARY KEY,
messages INTEGER NOT NULL DEFAULT 0
)
""")
owncast.sql.exec(
"""
INSERT INTO chatters (user_id, messages) VALUES (?, 1)
ON CONFLICT (user_id) DO UPDATE SET messages = messages + 1
""",
[msg.user.id],
)
top = owncast.sql.query(
"SELECT user_id, messages FROM chatters ORDER BY messages DESC LIMIT ?",
[5],
)
mine = owncast.sql.query_row("SELECT messages FROM chatters WHERE user_id = ?", [msg.user.id])
Each exec call runs as one host-owned transaction. A multi-statement batch commits whole or leaves the database untouched, so a schema migration can't half-apply. A plugin cannot leave a transaction open across calls, so there's nothing to clean up either.
query never hands back a silently short result. A query that overruns the row cap or the result budget is an error telling you to add a LIMIT, so write the bound you actually want when a table grows with your audience. queryRow reads a single row, which keeps it cheap on a table query is too big for.
| Limit | Value |
|---|---|
| Encoded request | 64 KiB total JSON |
| Bound parameters | 64 per call |
| Returned column value | 1 MiB |
| Encoded query result | 1 MiB |
| Rows returned | 10000 |
| Call duration | 2 seconds |
| Database size | 128 MiB |
Ordinary SQL is unaffected: DDL, DML, indexes, views, triggers, ORDER BY, recursive CTEs, subqueries, UNION, and the json1 functions all work. Refused in every host: ATTACH, DETACH, every PRAGMA (reads included), temporary-schema DDL both as keywords (CREATE TEMP TABLE / INDEX / TRIGGER / VIEW) and schema-qualified (CREATE TABLE temp.x), load_extension(), VACUUM and VACUUM INTO, and transaction controls (BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, and RELEASE). exec already owns the transaction around the whole batch.
Parameters and results cross the host boundary as JSON. Python can bind and read exact 64-bit SQLite integers. JavaScript loses unsafe integers before JSON.stringify on writes and during JSON.parse on reads. Store values above Number.MAX_SAFE_INTEGER (2^53 - 1) as TEXT when a JavaScript plugin needs them to remain exact.
Requires storage.sql. For a worked example, the chat-leaderboard plugin covers schema creation in one atomic exec, an ON CONFLICT upsert, a bounded ranked query, and a single-row read, in both JavaScript and Python. It contrasts with message-counter, which keeps the same counts in storage.kv and cannot rank.
Configuración
owncast.config.get(key, fallback?)
Lee uno de los manifiestos declarados config de tu plugin. Devuelve el valor establecido por el administrador cuando está presente, de lo contrario el valor predeterminado declarado, ya analizado a su tipo declarado. Para una clave desconocida (o una sin valor) devuelve fallback.
- JavaScript
- Python
const cooldownMs = owncast.config.get('cooldownMs', 2000);
cooldown_ms = owncast.config.get("cooldownMs", 2000)
Ambient: no permission required. Prefiere esto sobre construir una página de configuración personalizada y tuberías de clave/valor para ajustes simples. (La clave de configuración es lo que tú llamaste en el manifiesto, y no se traduce por idioma.)
Red
owncast.http.fetch(url, opts?)
Solicitud HTTP saliente sincrónica. opts lleva method, headers y body. El resultado es { status, headers, body }. Solo se pueden alcanzar los hosts enumerados en network.allowedHosts de tu manifiesto. Todo lo demás devuelve un error.
- JavaScript
- Python
const res = owncast.http.fetch('https://api.example.com/status');
if (res.status === 200) {
const data = JSON.parse(res.body);
}
import json
res = owncast.http.fetch("https://api.example.com/status")
if res.status == 200:
data = json.loads(res.body)
Requiere network.fetch y una entrada coincidente en network.allowedHosts. Usa esto para HTTP saliente en lugar del cliente HTTP propio de tu lenguaje (en Python, no uses requests: no se compilará dentro de un plugin).
Consulta la referencia del manifiesto: red para la sintaxis de la lista de permitidos.
Eventos entre plugins
owncast.events.emit(eventType, payload)
Emit to a custom hook owned by another plugin. eventType is the fully
qualified \<recipient-slug>.\<hook> target. The host dispatches that exact name
and does not add the emitter's slug. The receiving plugin declares only its
local hook name. See the
handlers reference.
- JavaScript
- Python
owncast.events.emit('announcer.announcement.broadcast', { text: 'We are live' });
owncast.events.emit("announcer.announcement.broadcast", {"text": "We are live"})
Requiere events.emit.
Estado del flujo y del servidor
owncast.stream.current()
El estado actual de la transmisión en vivo: { online, title?, summary?, viewers, startedAt?, latencyLevel? }`.
Requires server.read.
owncast.stream.broadcaster()
Telemetría de codificación de entrada para la conexión actual: { remoteAddr?, codecs?, resolution?, framerate?, bitrates? }`. Solo lectura, y con valor cero cuando no hay transmisión conectada. Para cambiar la salida de video, consulta el grupo de configuración de video abajo.
Requiere server.read.
owncast.server.info()
Información estática del servidor: { name?, url?, summary?, welcomeMessage?, version? }`.
- JavaScript
- Python
const name = owncast.server.info().name;
name = owncast.server.info().name
Requiere server.read.
owncast.server.socials()
The streamer's configured social links, each { platform, url, icon? }.
Requires server.read.
owncast.server.emotes()
Los emoticonos personalizados del servidor: el mismo conjunto que ofrece el punto final público /api/emoji, cada uno { name, url }. Útil para renderizar o filtrar emoticonos :code: del lado del servidor.
Requiere server.read.
owncast.server.federation()
Whether fediverse federation is enabled and under what handle: { enabled, username?, isPrivate? }. username is omitted when unset, and isPrivate is present only when true.
Requiere server.read.
owncast.server.tags()
Las etiquetas configuradas del transmisor, como una lista de cadenas.
Requiere server.read.
Configuración de video y transcoding
owncast.videoConfig.read()
Returns the current VideoConfig.
| Field | Type | Values |
|---|---|---|
latencyLevel | number | 0 through 4 |
codec | string | Configured ffmpeg encoder name |
autoplay | string | off, always, or sound-only |
variants | StreamVariant[] | Configured output renditions |
codec reads can report a legacy value or an encoder added by a newer host. Writes accept libx264, h264_omx, h264_vaapi, h264_qsv, h264_nvenc, h264_v4l2m2m, or h264_videotoolbox. Hardware codecs require the matching encoder in the host's ffmpeg build.
Autoplay off requires the viewer to press play. always starts automatically and may fall back to muted playback. sound-only starts automatically only when the browser allows sound.
Each StreamVariant has these fields:
| Field | Type | Description |
|---|---|---|
width | number | Scaled output width |
height | number | Scaled output height |
framerate | number | Output frames per second |
videoBitrate | number | Video bitrate in kbps |
cpuUsageLevel | number | Processing usage from 0 (lowest) through 4 (highest) |
isPassthrough | boolean | Pass video through without transcoding |
Audio settings are not exposed to plugins. Owncast preserves the existing audio configuration for each variant a plugin updates.
- JavaScript
- Python
const cfg = owncast.videoConfig.read();
cfg = owncast.video_config.read()
Requiere videoconfig.read.
owncast.videoConfig.write(partial)
Update any of the VideoConfig fields above. Pasa un objeto parcial. Solo los campos que incluyas se modifican. Los cambios se aplican en el próximo inicio de transmisión: el anfitrión no reinicia una transmisión activa.
- JavaScript
- Python
owncast.videoConfig.write({ latencyLevel: 2, autoplay: "sound-only" });
owncast.video_config.write({"latencyLevel": 2, "autoplay": "sound-only"})
Requiere videoconfig.write. Esto es de alta confianza. Los administradores deben concederlo con parquedad.
Notificaciones
owncast.notifications.discord(text)
Envía una notificación de Discord a través del webhook configurado del transmisor.
Requiere notifications.send.
owncast.notifications.browserPush({ title, body, url? })
Push a navegadores suscritos.
- JavaScript
- Python
owncast.notifications.browserPush({ title: 'Live now', body: 'Come say hi', url: '/' });
owncast.notifications.browser_push({"title": "Live now", "body": "Come say hi", "url": "/"})
Requiere notifications.send.
owncast.notifications.fediverse({ type, body, image?, link? })
Envía una notificación formateada para fediverso (renderizada como una publicación para seguidores).
Requiere notifications.send.
Fediverse
owncast.fediverse.post(text)
Haz una publicación pública en el fediverso desde la cuenta de Owncast.
Returns { url } on success (currently with an empty url: Owncast publishes the note but does not yet return its URL), or null when the host rejects the call.
Requiere fediverse.post. Alta confianza: una publicación en el fediverso se envía bajo el nombre del transmisor y no se puede revocar en silencio. Los administradores deben concederlo con parquedad.
Botones de acción (tiempo de ejecución)
owncast.actions.add(button | buttons[])
Agrega uno o más botones de acción al conjunto de manifiestos de tu plugin sin recarga. Cada botón toma los mismos campos que una entrada manifest.actions (title, más url/openExternally o html en línea). El anfitrión valida cada entrada con las mismas reglas que manifest.actions y persiste el resultado para que las adiciones sobrevivan a una recarga. A rejected entry throws an error naming the entry and the rule it broke, and the whole batch is rejected, so nothing is added when any entry is invalid.
- JavaScript
- Python
owncast.actions.add({ title: 'Donate', url: '/plugins/my-plugin/donate', openExternally: true });
owncast.actions.add({"title": "Donate", "url": "/plugins/my-plugin/donate", "openExternally": True})
Requiere ui.modify.
owncast.actions.clear()
Elimina todos los botones de acción añadidos en tiempo de ejecución. Las acciones declaradas en el manifiesto permanecen.
Requiere ui.modify.
Cobertura completa en UI: Botones de acción.
Push en tiempo real (Eventos enviados por el servidor)
owncast.sse.send(channel, event, data)
Envía un Evento enviado por el servidor a cada navegador conectado al punto final de tu plugin /_sse/\<channel>.
channel: qué flujo empujar. Usa""para el canal por defecto.event: el nombre del evento en el que el navegador escucha. Usa""para el eventomessagepor defecto.data: carga útil. Las cadenas se envían tal cual. Todo lo demás es codificado en JSON para ti.
- JavaScript
- Python
owncast.sse.send('alerts', 'donation', { from: 'alice', amount: 5 });
owncast.sse.send("alerts", "donation", {"from": "alice", "amount": 5})
Fire-and-forget. La llamada regresa inmediatamente y nunca bloquea. Los clientes lentos pierden fotogramas en lugar de detener tu complemento.
Requiere http.sse.
Cobertura completa en Servir HTTP: Actualizaciones en tiempo real.
Temporizadores
Programa trabajos diferidos y repetidos. Los temporizadores son ambientales, no se requiere permiso y se borran automáticamente cuando tu complemento está deshabilitado. (Python: set_timeout, set_interval, clear.)
owncast.timer.setTimeout(fn, ms)
Ejecuta fn una vez después de ms milisegundos. Devuelve un id.
owncast.timer.setInterval(fn, ms)
Ejecuta fn repetidamente cada ms milisegundos. Devuelve un id.
owncast.timer.clear(id)
Cancela un timeout o intervalo pendiente por el id que la llamada devolvió.
Activos agrupados
Lee archivos que enviaste en el directorio assets/ de tu complemento. Ambiental: no se requiere permiso. (Python: read, read_text.)
owncast.assets.read(path) and owncast.assets.readText(path)
Read a file bundled under assets/, relative to that directory. read returns the original bytes as a JavaScript Uint8Array or Python bytes. readText and Python's read_text decode the bytes as UTF-8. Python replaces malformed byte sequences when decoding. Missing files return null in JavaScript or None in Python.
- JavaScript
- Python
const image = owncast.assets.read('badge.png');
const template = owncast.assets.readText('template.html');
image = owncast.assets.read("badge.png")
template = owncast.assets.read_text("template.html")
Referencia completa de la API
Los nombres de los métodos a continuación son la forma en JavaScript (camelCase). Los equivalentes en Python son snake_case (sendAction → send_action, banIP → ban_ip, videoConfig → video_config, y así sucesivamente).
| API | Permiso |
|---|---|
owncast.log.info / .warning / .error | ninguno (ambiental) |
owncast.chat.send | chat.send |
owncast.chat.sendAction | chat.send |
owncast.chat.sendTo | chat.send |
owncast.chat.system | chat.send |
owncast.chat.replyTo | chat.send |
owncast.chat.history | chat.history |
owncast.chat.clients | chat.history |
owncast.chat.deleteMessage | chat.moderate |
owncast.chat.kick | chat.moderate |
owncast.users.list / .get | users.read |
owncast.users.setEnabled / .banIP | users.moderate |
owncast.users.register | users.register |
owncast.auth.grantSession / .endSession | auth.gate |
owncast.kv.get / .set / .getJSON / .setJSON | storage.kv |
owncast.storage.upload | storage.upload |
owncast.fs.read / .readText / .write / .list / .delete / .exists | storage.fs |
owncast.sql.exec / .query / .queryRow | storage.sql |
owncast.http.fetch | network.fetch |
owncast.events.emit | events.emit |
owncast.stream.current | server.read |
owncast.stream.broadcaster | server.read |
owncast.server.info / .socials / .emotes / .federation / .tags | server.read |
owncast.videoConfig.read | videoconfig.read |
owncast.videoConfig.write | videoconfig.write |
owncast.notifications.discord / .browserPush / .fediverse | notifications.send |
owncast.fediverse.post | fediverse.post |
owncast.actions.add / .clear | ui.modify |
owncast.timer.setTimeout / .setInterval / .clear | ninguno (ambiental) |
owncast.assets.read / .readText | ninguno (ambiental) |
owncast.config.get | none (ambient) |
owncast.sse.send | http.sse |
Improve this page
See something missing or incorrect? Edit the English version of this page or help improve translations.
Gabe Kangas