TypeScript quickstart

This walks you from nothing to a bot that posts a message, answers !ping with pong, and plays an audio file in a voice room. It uses the SDK in sdk/js (yuva-bot), written in TypeScript and shipped with its type declarations. Node.js 22 or newer. Prefer plain JavaScript? See the JavaScript quickstart: same SDK, same calls.

1. Create the bot#

  1. In Yuva, open Ayarlar → Geliştirici and use Bot oluştur (a name, and optionally what it does).

  2. Copy the token (yb_…) right away: it is shown once. If you lose it, Anahtarı yenile gives a new one and the old one stops working. Keep it out of your code and out of git; the examples read it from YUVA_BOT_TOKEN.

  3. Copy the bot id (bot_…) with Kimliği kopyala.

See authentication for how the token is sent and what to do when it is revoked.

2. Get it into a lodge#

A bot only sees the lodges it was added to. Someone with the manageBots staff right in the lodge (the owner, or a role that has it) opens the lodge settings, Botlar, pastes the bot id and picks what the bot may do: read, write, speak, mention, and so on. They can change or take away those rights at any time. To post you need write, to join voice speak. Permissions lists every right.

3. Install the SDK#

The SDK is not on npm; install it from your checkout of the Yuva repository. In your bot's own folder:

sh

npm init -ynpm pkg set type=modulenpm install /path/to/yuva/sdk/jsnpm install -D typescript tsx @types/node

npm install builds the SDK (TypeScript to sdk/js/dist) and links it, so after pulling a newer Yuva run npm run build in sdk/js. The package is ES modules only, hence "type": "module". If you compile with tsc yourself, use "module": "NodeNext". The examples run with npx tsx bot.ts.

Voice playback needs FFmpeg: the ffmpeg command must be on your PATH (ffmpeg -version should work in the same terminal). Text-only bots don't need it.

4. Post a message#

ts

import { Client } from "yuva-bot";const bot = new Client(process.env.YUVA_BOT_TOKEN!, "https://yuva.chat");const me = await bot.me();console.log("I am", me.displayName, me.userId);for (const lodge of await bot.lodges()) {  const { channels } = await bot.lodge(lodge.id);  const room = channels.find((c) => c.kind === "text" && c.perms.write);  if (room) await bot.sendMessage(room.id, "Merhaba! 👋");}

The second argument is your Yuva site; the SDK talks to <site>/api/bot/v1. Every method maps to one endpoint of the API reference and resolves to its typed JSON (Lodge, Channel, Member, Message, … are exported types). A failed call rejects with ApiError, which has .status and .message (the server's Turkish message, fine to show to people):

ts

import { ApiError } from "yuva-bot";try {  await bot.sendMessage(301, "selam @everyone");} catch (err) {  if (err instanceof ApiError && err.status === 403) console.log("not allowed:", err.message);  else throw err;}
MethodEndpoint
me()GET /me
lodges(), lodge(id)GET /lodges, GET /lodges/{id}
messages(channelId, { beforeId | afterId | aroundId })GET /channels/{id}/messages
sendMessage(channelId, "text" | { body, fileId, image })POST /channels/{id}/messages
uploadFile(channelId, path | { data, name })POST /channels/{id}/files
editMessage(id, body), deleteMessage(id)PATCH / DELETE /messages/{id}
react(id, emoji), pin(id)POST /messages/{id}/reactions, /pin
changes(channelId, since?)GET /channels/{id}/changes
events(cursor?)GET /events (one call; see below)

The voice endpoints are there too (voicePeers, voiceJoin, voiceBeat, voiceLeave, voiceMedia, and for mesh lodges voiceIce, voiceSignal, voiceDrain), but joinVoice (below) uses them for you.

Files: const file = await bot.uploadFile(channelId, "rapor.pdf") (or { data: buffer, name: "rapor.pdf" }), then await bot.sendMessage(channelId, { body: "Rapor", fileId: file.id }). Attachments need a trusted account, see the reference.

5. Answer messages#

ts

import { Client } from "yuva-bot";const bot = new Client(process.env.YUVA_BOT_TOKEN!, "https://yuva.chat");bot.on("message.create", async ({ channelId, message }) => {  if (message.body.trim() === "!ping") {    await bot.sendMessage(channelId, "pong");    await bot.react(message.id, "heart"); // or one Unicode emoji: "🔥", "👍🏽", "🇹🇷"  }});bot.on("error", (err) => console.error("bot error:", err));await bot.start(); // runs until bot.stop(), or until the token stops working

start() polls GET /events every 1.5 seconds across every text room the bot can read, keeps the cursor, polls again at once after a full page of 100, and backs off (2 s, doubling up to 30 s) on 429, 5xx and network errors. It skips the bot's own messages (new Client(token, site, { includeOwn: true }) to get them). On 401 it reports the ApiError to the "error" handlers and resolves, since a revoked token never comes back. Handlers may be async; they run one at a time in event order, so a slow handler delays the next poll. A handler that throws goes to "error" and the loop carries on. Also available: message.update (edits, reactions, pins; may repeat, treat it as "this is the message now") and message.delete (event.messageId). on() returns a function that removes the handler; bot.stop() ends start().

Stay within the rate limits: the events loop and a voice connection use a fraction of them.

6. Play audio in a voice room#

ts

import { ApiError, Client } from "yuva-bot";const bot = new Client(process.env.YUVA_BOT_TOKEN!, "https://yuva.chat");const [lodge] = await bot.lodges();const { channels } = await bot.lodge(lodge.id);const room = channels.find((c) => c.kind === "voice" && c.perms.speak);if (!room) throw new Error("no voice room the bot may speak in");const voice = await bot.joinVoice(lodge.id, room.id);voice.on("lost", (err) => console.log("seat lost:", err.message));try {  await voice.play("song.mp3"); // resolves when the file ends} catch (err) {  if (err instanceof ApiError) console.log("kicked out:", err.message);  else throw err;} finally {  await voice.leave();}

joinVoice takes the seat and keeps it alive with a beat every 5 seconds. In a lodge whose voice runs on LiveKit (most of them) it asks the server for a media ticket (voiceMedia) and joins the room's LiveKit room, where it publishes one microphone track while a file plays; in an older mesh lodge it dials everyone in the room over WebRTC instead (signals drained and acknowledged between beats). voice.transport tells which ("sfu" or "mesh"); your code is the same either way. People who join later get the bot's audio too, including the rest of a file that is already playing. While nothing plays (or after voice.setMuted(true)) the bot sends nothing and shows as muted; it never listens to the room and shows as deafened. voice.stop() ends the current file early (its play() resolves), a new play() replaces the current one, voice.playing tells whether something plays, and voice.peers is the peer list from the latest beat (voice.on("peers", …) gets every update).

If a moderator moves the bot, it follows to the new room (voice.channelId changes). If a moderator disconnects it, speak is taken away, it is removed from the lodge, another process takes the seat over or the token is revoked, the connection closes: "lost" handlers get the ApiError and a pending play() rejects with it. A dropped LiveKit connection or mesh link is restored by itself; other trouble (a failed request) goes to voice.on("error", …) and the connection carries on. Call leave() when you're done.

How playback works: in a LiveKit lodge the SDK uses @livekit/rtc-node (prebuilt native binaries for Windows, macOS and Linux on x64 and arm64, nothing to compile). play() starts ffmpeg -re -i <file> -f s16le -ac 1 -ar 48000 pipe:1: FFmpeg decodes any format it knows to 48 kHz mono PCM, paced in real time, and the SDK feeds it to the published track in 10 ms frames; LiveKit encodes it to Opus once and forwards it to everyone listening. In a mesh lodge WebRTC runs in pure TypeScript (werift): play() starts ffmpeg -re -i <file> -c:a libopus … -f rtp aimed at a local UDP port, and the SDK copies each 20 ms Opus packet to every peer connection's audio track. The voice guide describes the protocol underneath if you want to know what the SDK does.

Next#