Yurst

API Reference

All exports, bot methods, contexts, and package structure

API Reference

Public exports

import { bot, ButtonsBuilder, api, L, fmtUptime, stats } from 'yurst.js';
ExportTypePurpose
botBotSingleton for registering commands, callbacks, and events
ButtonsBuilderclassBuilder for inline button rows
apifunctionLow-level HTTP requests to the Yurba API
LLoggerLogger with the debug, info, warn, error methods
fmtUptimefunctionFormats uptime: "1h 23m 4s"
statsobjectCounters: updates, errors, apiCalls, apiErrors, dupes

Subpaths (yurst.js/src/...) are not exported. The package is available only through the root 'yurst.js'.

bot — Core API

Registration methods

command(nameOrObj, descOrHandler?, handler?, opts?)

Registers a slash command.

Short form:

bot.command('ping', 'Опис', (ctx) => ctx.reply('pong'));

Object form:

bot.command({
  name: 'city',
  description: 'Обрати місто',
  scope: 'private',      // 'all' | 'private' | 'groups'
  register: true,        // чи реєструвати в Yurba
  run: (ctx) => ctx.reply('Місто?'),
});

callback(pattern, handler)

Registers a callback button handler.

bot.callback('menu:open', async (ctx) => {
  await ctx.answer();
  await ctx.replace('Відкрито');
});

Routing:

  • Exact match: ctx.data === pattern
  • Prefix: ctx.data.startsWith(pattern + ':')

on(event, handler)

Subscribes to an event.

bot.on('message', (ctx) => { ... });
bot.on('inline', (ctx) => { ... });
bot.on('stopped', (update) => { ... });

Properties

bot.me

Bot information (available after start()).

bot.me.data      // Об'єкт User або null
bot.me.name      // Ім'я або null
bot.me.link      // Username без @ або null
bot.me.id        // ID або null
bot.me.invite()  // URL для запуску бота
bot.me.invite('ref')  // URL з параметром

Lifecycle methods

start()

Starts the bot.

await bot.start();  // Не завершується у звичайному режимі

Performs:

  1. Authentication (GET /bot/me)
  2. Command registration (PUT /bot/commands)
  3. Transport start (WebSocket or polling)

MessageContext

Passed to commands and bot.on('message').

Fields

FieldTypeDescription
updateobjectRaw Yurba update
messageobjectMessage object
userobject | nullMessage author
dialogstring | nullDialog ID
argsstringCommand arguments
payloadstringDeep-link parameter

Methods

reply(text, options?)

await ctx.reply('Текст', {
  buttons: [[{ text: 'OK', data: 'ok' }]],
  keyboard: [['Так', 'Ні']],
  removeKeyboard: true,
  replyTo: null,
});

send(text, options?)

await ctx.send('Текст', { buttons: [...] });

typing()

await ctx.typing();

help()

const text = ctx.help();  // Список всіх команд

CallbackContext

Passed to bot.callback().

Fields

FieldTypeDescription
updateobjectRaw update
callbackobjectCallback object
userobject | nullWho pressed
dialogstring | nullDialog ID
messageobject | nullMessage with the button
datastringButton data

Methods

answer(textOrOpts?)

await ctx.answer();
await ctx.answer('Збережено');
await ctx.answer({ text: 'Увага!', alert: true });

replace(text, options?)

await ctx.replace('Новий текст', { buttons: [...] });

editMarkup(options?)

await ctx.editMarkup({ buttons: [...] });
await ctx.editMarkup({ removeKeyboard: true });

reply(text, options?)

await ctx.reply('Додаткове повідомлення');

InlineContext

Passed to bot.on('inline').

Fields

FieldTypeDescription
updateobjectRaw update
userobject | nullWho made the request
querystringRequest text

Methods

answer(results)

await ctx.answer([
  { id: '1', title: 'Заголовок', text: 'Текст' },
]);

Reply options

Accepted by reply(), send(), replace(), editMarkup().

interface ReplyOptions {
  buttons?: ButtonRow[];      // Inline-кнопки
  keyboard?: string[][];      // Reply-клавіатура
  placeholder?: string;       // Підказка для reply-клавіатури
  removeKeyboard?: boolean;   // Прибрати клавіатуру
}

Only ctx.reply() additionally accepts replyTo?: string | null — the ID of the message to quote. Pass replyTo: null to send a reply without a quote.

ButtonRow

type ButtonRow = Array<{
  text: string;
  data?: string;      // Callback-кнопка
  url?: string;       // Посилання
  app?: string;       // Мінізастосунок
  copy?: string;      // Копіювання
  command?: string;   // Команда
  style?: 'primary' | 'success' | 'danger';
}>;

ButtonsBuilder

const buttons = new ButtonsBuilder()
  .row()
  .link('Документація', 'https://yurba.one')
  .command('Допомога', '/help')
  .row()
  .callback('Підтвердити', 'confirm').success()
  .callback('Скасувати', 'cancel').danger()
  .build();

await ctx.reply('Оберіть:', { buttons });
MethodPurpose
row()Start a new row
link(text, url)Add a link button
command(text, command)Add a command button
callback(text, data)Add a callback button; btn() is an alias
copy(text, value)Add a copy button
primary(), success(), danger()Apply a style to the last button
gray()Reset the explicit style of the last button
build()Get ButtonRow[] for context methods
buildMarkup()Get the Yurba object { Inline: [...] }

For large lists, create rows while iterating over the data. A complete example is in the callback buttons guide.

ApiResponse

Returned by all sending methods and api().

interface ApiResponse {
  status: number;   // HTTP-статус
  ok: boolean;      // true для 200-299
  data: any;        // Тіло відповіді
  ms: number;       // Час виконання в мс
}

Configuration

Environment variables:

VariableDefaultDescription
TOKENrequiredBot token
MODEwsTransport mode
YURST—dev for debug mode
YURST_LOGinfoLog level
LOG_FILE—Log file
WS_IDLE_MS0WebSocket watchdog
WS_MAX_FAILS5Attempts before fallback
MAX_TEXT4000Max message length
API_TIMEOUT_MS10000HTTP timeout
POLL_TIMEOUT_S30Polling timeout
YURST_ENV_FILE—Additional path to .env

Requirements

  • Node.js: >= 22
  • Module: ESM ("type": "module")
  • Dependencies: 0 (runtime)

Package structure (internal)

FilePurpose
index.jsPublic exports
src/bot.jsBot class, singleton, routing
src/context.jsMessageContext, CallbackContext, InlineContext
src/api.jsHTTP client
src/config.jsConfiguration loading
src/state.jsGlobal state, stats, uptime
src/logger.jsLogger
src/transport/ws.jsWebSocket transport
src/transport/poll.jsLong polling transport
src/builders/buttons.jsButtonsBuilder implementation
src/builder.jsCompatibility re-export of ButtonsBuilder

Internal files are not part of the public API. They may change without notice.

On this page