API Reference

Complete API reference for @igniter-js/bot. Builder methods, Bot class, adapters, middlewares, plugins, types, and error codes.

API Reference

This page documents every public API surface of @igniter-js/bot. All methods, types, and exports are listed with their signatures and descriptions.


IgniterBotBuilder

The main entry point for constructing bots.

Static Methods

IgniterBot.create()

Creates a new builder instance.

static create(): IgniterBotBuilder

Identity Methods

withHandle(handle: string): this

Sets the bot handle (e.g., @mybot). Auto-generates id and name from the handle if not set explicitly.

withHandle(handle: string): this

withId(id: string): this

Sets a unique bot identifier. Optional — derived from handle if not provided.

withId(id: string): this

withName(name: string): this

Sets a human-readable display name. Optional — derived from handle if not provided.

withName(name: string): this

Configuration Methods

withLogger(logger: BotLogger): this

Configures a structured logger for the bot and all adapters.

withLogger(logger: BotLogger): this

The BotLogger interface:

interface BotLogger {
  debug?: (...args: any[]) => void
  info?: (...args: any[]) => void
  warn?: (...args: any[]) => void
  error?: (...args: any[]) => void
}

withSessionStore(store: BotSessionStore): this

Configures session storage for conversational state.

withSessionStore(store: BotSessionStore): this

withOptions(options: BotOptions): this

Sets advanced bot options.

withOptions(options: BotOptions): this

interface BotOptions {
  timeout?: number                      // Request timeout in ms
  retries?: number                      // Retry attempts for failed operations
  autoRegisterCommands?: boolean        // Auto-register with platforms
  errorHandler?: (error: BotError, context?: BotContext) => void | Promise<void>
}

Adapter Methods

addAdapter(key: string, adapter: IBotAdapter): IgniterBotBuilder

Adds a single platform adapter. Returns a new builder with updated generic types.

addAdapter<K extends string, A extends IBotAdapter<any>>(
  key: K,
  adapter: A
): IgniterBotBuilder<TAdapters & Record<K, A>, TCommands, TContext>

addAdapters(adapters: Record<string, IBotAdapter>): IgniterBotBuilder

Adds multiple adapters at once.

addAdapters<A extends Record<string, IBotAdapter<any>>>(
  adapters: A
): IgniterBotBuilder<TAdapters & A, TCommands, TContext>

Command Methods

addCommand(name: string, command: BotCommand): IgniterBotBuilder

Registers a command. Returns a new builder with updated types.

addCommand<K extends string, C extends BotCommand<TContext>>(
  name: K,
  command: C
): IgniterBotBuilder<TAdapters, TCommands & Record<K, C>, TContext>

addCommands(commands: Record<string, BotCommand>): IgniterBotBuilder

Registers multiple commands at once.

addCommands<C extends Record<string, BotCommand<TContext>>>(
  commands: C
): IgniterBotBuilder<TAdapters, TCommands & C, TContext>

addCommandGroup(prefix: string, commands: Record<string, BotCommand>): IgniterBotBuilder

Registers prefixed commands (e.g., admin_ban, admin_kick).

addCommandGroup<C extends Record<string, BotCommand<TContext>>>(
  prefix: string,
  commands: C
): IgniterBotBuilder<TAdapters, TCommands, TContext>

Middleware Methods

addMiddleware(middleware: Middleware): IgniterBotBuilder

Adds a middleware to the pipeline.

addMiddleware<TContextAdditions>(
  middleware: Middleware<TContext, TContextAdditions>
): IgniterBotBuilder<TAdapters, TCommands, TContext & Awaited<TContextAdditions>>

addMiddlewares(middlewares: Middleware[]): this

Adds multiple middlewares at once.

addMiddlewares(middlewares: Middleware<TContext, any>[]): this

Plugin Methods

usePlugin(plugin: BotPlugin): this

Loads a plugin, registering all its commands, middlewares, adapters, and hooks.

usePlugin(plugin: BotPlugin): this

Event Listener Methods

onMessage(handler: BotEventHandler): this

Registers a message event listener.

onMessage(handler: BotEventHandler<TContext>): this

type BotEventHandler<TContext> = (ctx: TContext) => Promise<void> | void

onError(handler: BotErrorHandler): this

Registers an error event listener.

onError(handler: BotErrorHandler<TContext>): this

type BotErrorHandler<TContext> = (
  ctx: TContext & { error: BotError },
) => Promise<void> | void

onCommand(handler: BotEventHandler): this

Registers a command event listener (called for all commands).

onCommand(handler: BotEventHandler<TContext>): this

onStart(handler: BotStartHandler): this

Registers a startup hook.

onStart(handler: BotStartHandler): this

type BotStartHandler = () => Promise<void> | void

Build Method

build(): Bot

Validates configuration and returns the immutable Bot instance.

build(): Bot<TAdapters, Middleware<TContext, any>[], TCommands>

Throws if:

  • No adapters are registered
  • No handle is configured (neither global nor in any adapter)

Bot Class

The runtime bot instance. Returned by builder.build().

Properties

PropertyTypeDescription
idstringUnique bot identifier
namestringDisplay name
botHandlestring | undefinedGlobal handle

Methods

start(): Promise<void>

Initializes all adapters (registers webhooks, commands, etc.) and runs startup hooks.

async start(): Promise<void>

handle(provider: string, request: Request): Promise<Response>

Routes an incoming request to the appropriate adapter.

async handle(provider: string, request: Request): Promise<Response>

Throws BotError with code PROVIDER_NOT_FOUND if the adapter isn't registered.

send(params: BotSendParams): Promise<void>

Sends an outbound message through a specific adapter.

async send(params: BotSendParams): Promise<void>

type BotSendParams<TConfig> = {
  provider: string
  channel: string
  content: BotOutboundContent
  options?: BotSendOptions
  config: TConfig
}

Throws BotError with code CONTENT_TYPE_NOT_SUPPORTED if the adapter doesn't support the content type.

on(event: BotEvent, callback: Function): void

Registers a runtime event listener.

on(event: BotEvent, callback: (ctx: BotContext) => Promise<void>): void

type BotEvent = 'start' | 'message' | 'error'

registerCommand(name: string, command: BotCommand): this

Dynamically registers a command at runtime.

registerCommand(name: string, command: BotCommand): this

registerAdapter(key: string, adapter: IBotAdapter): this

Dynamically registers an adapter at runtime.

registerAdapter<K extends string, A extends IBotAdapter<any>>(key: K, adapter: A): this

use(middleware: Middleware): this

Dynamically adds a middleware at runtime.

use(mw: Middleware<any, any>): this

onPreProcess(hook: Function): this

Registers a hook that runs before the middleware pipeline (for session loading, context enrichment).

onPreProcess(hook: (ctx: BotContext) => Promise<void> | void): this

onPostProcess(hook: Function): this

Registers a hook that runs after successful processing.

onPostProcess(hook: (ctx: BotContext) => Promise<void> | void): this

emit(event: BotEvent, ctx: BotContext): Promise<void>

Manually emits an event to registered listeners.

async emit(event: BotEvent, ctx: BotContext): Promise<void>

getAdapter(provider: string): IBotAdapter | undefined

Returns the adapter for a specific provider.

getAdapter(provider: string): IBotAdapter<any> | undefined

getAdapters(): Record<string, IBotAdapter>

Returns all registered adapters.

getAdapters(): Record<string, IBotAdapter<any>>

Static Methods

Bot.adapter(config): AdapterFactory

Creates a typed adapter factory. Used internally by built-in adapters and for custom adapters.

static adapter<TConfig extends ZodObject<any>>(config: {
  name: string
  parameters: TConfig
  capabilities: BotAdapterCapabilities
  verify?: (params: AdapterVerifyParams) => Promise<Response | null>
  init: (params: AdapterInitParams) => Promise<void>
  handle: (params: AdapterHandleParams) => Promise<Omit<BotContext, 'bot' | 'session' | ...> | null>
  sendTyping?: (params: AdapterSendTypingParams) => Promise<void>
  client?: (config, logger?) => AdapterClient
  sendText?: (params: AdapterSendTextParams) => Promise<void>
  sendImage?: (params: AdapterSendImageParams) => Promise<void>
  // ... all send methods, editMessage, deleteMessage
}): (config?: Partial<TypeOf<TConfig>>) => IBotAdapter<TConfig>

Bot.command(command): BotCommand

Validates and returns a command definition.

static command<TContext, TContextAdditions>(
  command: BotCommand<TContext, TContextAdditions>
): BotCommand<TContext, TContextAdditions>

Bot.middleware(middleware): Middleware

Validates and returns a middleware function.

static middleware<TContext, TContextAdditions>(
  middleware: Middleware<TContext, TContextAdditions>
): Middleware<TContext, TContextAdditions>

Bot.create(config): Bot

Internal factory. Deprecated: Use IgniterBot builder instead.

static create<TAdapters, TMiddlewares, TCommands>(config: {
  id: string
  name: string
  handle?: string
  adapters: TAdapters
  middlewares?: TMiddlewares
  commands?: TCommands
  on?: Partial<Record<BotEvent, (ctx: BotContext) => Promise<void>>>
  logger?: BotLogger
  sessionStore?: BotSessionStore
}): Bot<TAdapters, TMiddlewares, TCommands>

BotCommand Interface

interface BotCommand<TContext = BotContext, TArgs = any> {
  name: string
  aliases: string[]
  description: string
  help: string
  args?: ZodType<TArgs>
  handle: (ctx: TContext, params: TArgs) => Promise<void>
  subcommands?: Record<string, Omit<BotCommand<TContext>, 'name' | 'aliases'>>
}

BotContext Interface

interface BotContext {
  event: BotEvent                               // 'start' | 'message' | 'error'
  provider: string                               // 'telegram' | 'whatsapp' | 'discord'

  bot: {
    id: string
    name: string
    send: (params: Omit<BotSendParams<any>, 'config'>) => Promise<void>
    getAdapter?: (provider: string) => IBotAdapter | undefined
    getAdapters?: () => Record<string, IBotAdapter>
  }

  channel: {
    id: string
    name: string
    isGroup: boolean
  }

  message: {
    id?: string
    content?: BotContent
    attachments?: BotAttachmentContent[]
    author: {
      id: string
      name: string
      username: string
    }
    isMentioned: boolean
  }

  session: BotSessionHelper

  reply(content: BotOutboundContent | string, options?: BotSendOptions): Promise<void>
  replyWithButtons(text: string, buttons: BotButton[], options?: BotSendOptions): Promise<void>
  replyWithImage(image: string | File, caption?: string, options?: BotSendOptions): Promise<void>
  replyWithDocument(file: File, caption?: string, options?: BotSendOptions): Promise<void>
  editMessage?(messageId: string, content: BotOutboundContent): Promise<void>
  deleteMessage?(messageId: string): Promise<void>
  react?(emoji: string, messageId?: string): Promise<void>
  sendTyping?(): Promise<void>
}

Content Types

BotOutboundContent (Send)

type BotOutboundContent =
  | BotTextContent        // { type: 'text', content: string }
  | BotImageContent       // { type: 'image', content: string, file?: File, caption?: string }
  | BotVideoContent       // { type: 'video', content: string, file?: File, caption?: string }
  | BotAudioContent       // { type: 'audio', content: string, file?: File }
  | BotDocumentContent    // { type: 'document', content: string, file: File, filename?: string, caption?: string }
  | BotStickerContent     // { type: 'sticker', content: string, file?: File }
  | BotLocationContent    // { type: 'location', latitude: number, longitude: number, name?: string, address?: string }
  | BotContactContent     // { type: 'contact', phoneNumber: string, firstName: string, lastName?: string }
  | BotPollContent        // { type: 'poll', question: string, options: string[], ... }
  | BotInteractiveContent // { type: 'interactive', text: string, buttons?: BotButton[], inlineKeyboard?: BotInlineKeyboardRow[] }
  | BotReplyContent       // { type: 'reply', messageId: string, content: BotOutboundContent }

BotSendOptions

interface BotSendOptions {
  replyToMessageId?: string
  disableWebPagePreview?: boolean
  disableNotification?: boolean
  parseMode?: 'HTML' | 'Markdown' | 'MarkdownV2'
  protectContent?: boolean
  autoFormat?: boolean
}

BotError

class BotError extends Error {
  code: BotErrorCode
  meta?: Record<string, unknown>

  constructor(code: BotErrorCode, message?: string, meta?: Record<string, unknown>)
}

type BotErrorCode =
  | 'CLIENT_NOT_PROVIDED'
  | 'PROVIDER_NOT_FOUND'
  | 'COMMAND_NOT_FOUND'
  | 'INVALID_COMMAND_PARAMETERS'
  | 'ADAPTER_HANDLE_RETURNED_NULL'
  | 'CONTENT_TYPE_NOT_SUPPORTED'
  | 'INVALID_CONTENT'

Session Interfaces

BotSessionStore

interface BotSessionStore {
  get(userId: string, channelId: string): Promise<BotSession | null>
  set(userId: string, channelId: string, session: BotSession): Promise<void>
  delete(userId: string, channelId: string): Promise<void>
  clear(userId: string): Promise<void>
}

BotSessionHelper

interface BotSessionHelper extends BotSession {
  save(): Promise<void>
  delete(): Promise<void>
  update(data: Partial<Record<string, any>>): Promise<void>
}

Plugin Interface

interface BotPlugin {
  name: string
  version: string
  description?: string
  commands?: Record<string, BotCommand>
  middlewares?: Middleware<any, any>[]
  adapters?: Record<string, IBotAdapter<any>>
  hooks?: {
    onStart?: () => Promise<void> | void
    onMessage?: (ctx: BotContext) => Promise<void> | void
    onError?: (ctx: BotContext & { error: BotError }) => Promise<void> | void
    onStop?: () => Promise<void> | void
  }
  config?: Record<string, any>
}

Exports

Main Exports

export { IgniterBot, IgniterBotBuilder } from './builder'
export { Bot, BotError, BotErrorCodes } from './bot.provider'
export { telegram } from './adapters/telegram'
export { whatsapp } from './adapters/whatsapp'
export { discord } from './adapters/discord'
export { nextRouteHandlerAdapter } from './adapters/nextjs'
export { tanstackStartRouteHandlerAdapter } from './adapters/tanstack-start'
export { adapters } from './index' // Convenience: { telegram, whatsapp, discord }
export { VERSION } from './index'

// Middlewares
export { authMiddleware, authPresets, roleMiddleware } from './middlewares/auth'
export { rateLimitMiddleware, rateLimitPresets, memoryRateLimitStore } from './middlewares/rate-limit'
export { loggingMiddleware, loggingPresets, commandLoggingMiddleware } from './middlewares/logging'

// Plugins
export { analyticsPlugin } from './plugins/analytics'

// Stores
export { memoryStore, MemorySessionStore } from './stores/memory'

Next Steps

On this page

API ReferenceIgniterBotBuilderStatic MethodsIgniterBot.create()Identity MethodswithHandle(handle: string): thiswithId(id: string): thiswithName(name: string): thisConfiguration MethodswithLogger(logger: BotLogger): thiswithSessionStore(store: BotSessionStore): thiswithOptions(options: BotOptions): thisAdapter MethodsaddAdapter(key: string, adapter: IBotAdapter): IgniterBotBuilderaddAdapters(adapters: Record<string, IBotAdapter>): IgniterBotBuilderCommand MethodsaddCommand(name: string, command: BotCommand): IgniterBotBuilderaddCommands(commands: Record<string, BotCommand>): IgniterBotBuilderaddCommandGroup(prefix: string, commands: Record<string, BotCommand>): IgniterBotBuilderMiddleware MethodsaddMiddleware(middleware: Middleware): IgniterBotBuilderaddMiddlewares(middlewares: Middleware[]): thisPlugin MethodsusePlugin(plugin: BotPlugin): thisEvent Listener MethodsonMessage(handler: BotEventHandler): thisonError(handler: BotErrorHandler): thisonCommand(handler: BotEventHandler): thisonStart(handler: BotStartHandler): thisBuild Methodbuild(): BotBot ClassPropertiesMethodsstart(): Promise<void>handle(provider: string, request: Request): Promise<Response>send(params: BotSendParams): Promise<void>on(event: BotEvent, callback: Function): voidregisterCommand(name: string, command: BotCommand): thisregisterAdapter(key: string, adapter: IBotAdapter): thisuse(middleware: Middleware): thisonPreProcess(hook: Function): thisonPostProcess(hook: Function): thisemit(event: BotEvent, ctx: BotContext): Promise<void>getAdapter(provider: string): IBotAdapter | undefinedgetAdapters(): Record<string, IBotAdapter>Static MethodsBot.adapter(config): AdapterFactoryBot.command(command): BotCommandBot.middleware(middleware): MiddlewareBot.create(config): BotBotCommand InterfaceBotContext InterfaceContent TypesBotOutboundContent (Send)BotSendOptionsBotErrorSession InterfacesBotSessionStoreBotSessionHelperPlugin InterfaceExportsMain ExportsNext Steps