Skip to main content

Overview

@kreisler/bot-tl-ts is a TypeScript framework for building Telegram bots with an elegant command system and event handling. Package: @kreisler/bot-tl-ts
Version: 1.0.0
License: MIT

Installation

npm install @kreisler/bot-tl-ts

Quick Start

import { ClientBot as Bot } from '@kreisler/bot-tl-ts';

(async () => {
  const bot = new Bot();
  await bot.initialize();
})();

Classes

ClientBot

Extends TelegramBot from node-telegram-bot-api with additional functionality for command management and media handling.

Constructor

token
string
default:"TOKEN from env"
The Telegram Bot API token. Defaults to TELEGRAM_TOKEN_DEV or TELEGRAM_TOKEN_PROD based on NODE_ENV.
options
object
default:"{ polling: true }"
Configuration options for the Telegram bot.
const bot = new ClientBot(token, { polling: true });

Properties

commands
Map<RegExp, IExportCMD>
Map storing all registered bot commands with their regular expression patterns.
slashArray
any[]
Array for storing slash commands.
Bot
ClientBot
Getter that returns the bot instance itself.

Methods

initialize()
Initializes the bot by loading events, handlers, and commands.
return
Promise<void>
Returns a promise that resolves when initialization is complete.
await bot.initialize();
sendMediaGroupTenByTen()
Sends media in groups of 10 photos to a chat.
chatId
TelegramBot.ChatId
required
The chat ID to send media to.
medias
readonly TelegramBot.InputMedia[]
required
Array of media to send.
options
TelegramBot.SendMediaGroupOptions
Optional parameters for sending media group.
return
Promise<TelegramBot.Message[]>
Array of sent messages.
const messages = await bot.sendMediaGroupTenByTen(
  chatId,
  [
    { type: 'photo', media: 'https://example.com/photo1.jpg' },
    { type: 'photo', media: 'https://example.com/photo2.jpg' }
  ]
);
sendDocumentOnebyOne()
Sends multiple documents one by one to a chat.
chatId
TelegramBot.ChatId
required
The chat ID to send documents to.
documents
string[] | Stream[] | Buffer[]
required
Array of documents to send.
options
TelegramBot.SendDocumentOptions
Optional parameters for sending documents.
fileOptions
TelegramBot.FileOptions
Additional file options.
return
Promise<TelegramBot.Message[]>
Array of sent messages.
await bot.sendDocumentOnebyOne(
  chatId,
  [buffer1, buffer2],
  { caption: 'Documents' }
);
getCommands
Gets all registered commands as an array of tuples.
return
[RegExp, IExportCMD][]
Array of command patterns and their handlers.
const commands = bot.getCommands;
findCommand()
Finds a command that matches the given string.
str
string
required
The string to match against command patterns.
return
[boolean, [RegExp, IExportCMD] | []]
Tuple with match status and command data if found.
const [found, command] = bot.findCommand('/start');
if (found) {
  console.log('Command found:', command);
}
loadEvents()
Loads all event handlers for the bot.
return
Promise<void>
Promise that resolves when events are loaded.
loadCommands()
Loads all commands from the commands directory.
return
Promise<void>
Promise that resolves when commands are loaded.
loadCommandsSlash()
Loads slash commands and sets them using Telegram’s setMyCommands API.
return
Promise<void>
Promise that resolves when slash commands are loaded.
loadHandlers()
Loads all error handlers including anti-crash handlers.
return
Promise<void>
Promise that resolves when handlers are loaded.
dynamicImport()
Dynamically imports a module by path.
path
string
required
The module path to import.
return
Promise<O>
The imported module.
const module = await bot.dynamicImport<{ handler: Function }>(
  '@/bot/events/client/message.js'
);

Interfaces

IClsBot.ICTX

Context object passed to command handlers.
msg
TelegramBot.Message
The raw Telegram message object.
ctx
Message
The wrapped Message instance with helper methods.

IClsBot.IExportCMD

Command definition interface.
active
boolean
Whether the command is active and should be loaded.
regexp
RegExp
Regular expression pattern to match the command.
cmd
(client: ClientBot, context: ICTX, match: RegExpMatchArray | null) => Promise<void>
The command handler function.

IClsBot.TSendContent

Union type for sending different content types.
text
string
Text content to send.
doc
string | Stream | Buffer
Document to send.
photo
string | Stream | Buffer
Photo to send.
video
string | Stream | Buffer
Video to send.
sticker
string | Stream | Buffer
Sticker to send.
audio
string | Stream | Buffer
Audio to send.

Message Class

Wrapper class for Telegram messages with helper methods.

Constructor

client
ClientBot | TelegramBot
required
The bot client instance.
data
TelegramBot.Message
required
The raw Telegram message data.

Properties

chatId
number
The chat ID where the message was sent.
message_id
number
The unique message identifier.
text
string | undefined
The text content of the message.
isReply
boolean
Whether this message is a reply to another message.
isGroup
boolean
Whether the message was sent in a group chat.
isChannel
boolean
Whether the message was sent in a channel.

Methods

send()

Sends a message to the same chat. Supports multiple overloads for different content types.
content
{ text: string } | { doc: string | Stream | Buffer } | { photo: string | Stream | Buffer } | { video: string | Stream | Buffer } | { sticker: string | Stream | Buffer } | { audio: string | Stream | Buffer }
required
Content to send.
options
TelegramBot.SendMessageOptions | TelegramBot.SendDocumentOptions | TelegramBot.SendPhotoOptions | TelegramBot.SendVideoOptions | TelegramBot.SendStickerOptions | TelegramBot.SendAudioOptions
Options for sending the content.
fileOptions
TelegramBot.FileOptions
Additional file options (for media types).
return
Promise<Message>
The sent message wrapped in the Message class.
// Send text
await message.send({ text: 'Hello!' });

// Send photo
await message.send({ photo: buffer }, { caption: 'A photo' });

// Send document
await message.send({ doc: './file.pdf' });

reply()

Replies to the message.
content
any
required
Content to send as reply.
options
any
Options for the reply.
return
Promise<TelegramBot.Message>
The sent reply message.
await message.reply('This is a reply!');

delete()

Deletes the message.
return
Promise<boolean | TelegramBot.Message>
Result of the delete operation.
await message.delete();

editText()

Edits the message text.
text
string
required
New text for the message.
options
TelegramBot.EditMessageTextOptions
Options for editing the message.
return
Promise<TelegramBot.Message | boolean>
The edited message or true on success.
await message.editText('Updated text', { parse_mode: 'Markdown' });

getQuotedMsg()

Gets the quoted/replied message if this is a reply.
return
TelegramBot.Message | undefined
The quoted message or undefined.
const quoted = message.getQuotedMsg();
if (quoted) {
  console.log('Replying to:', quoted.text);
}

getData()

Gets the raw Telegram message data.
return
TelegramBot.Message
The raw message object.

Types

IClsBot.TImportEvent

Event handler function type.
type TImportEvent = (client: ClientBot, msg: TelegramBot.Message) => Promise<void>

EChatType

Enum for chat types.
Group
'group'
Regular group chat.
SuperGroup
'supergroup'
Supergroup chat.
Channel
'channel'
Channel.

Usage Examples

Creating a Simple Command

import { ClientBot, IClsBot } from '@kreisler/bot-tl-ts';

const command: IClsBot.IExportCMD = {
  active: true,
  regexp: /^\/start$/,
  cmd: async (client, context, match) => {
    const { msg, ctx } = context;
    await ctx.send({ text: 'Welcome to the bot!' });
  }
};

export default command;

Handling Media Messages

const bot = new ClientBot();

bot.on('message', async (msg) => {
  const message = new Message(bot, msg);
  
  if (msg.photo) {
    await message.reply('Nice photo!');
  }
});

Sending Multiple Photos

const photos = [
  { type: 'photo', media: 'https://example.com/1.jpg' },
  { type: 'photo', media: 'https://example.com/2.jpg' },
  { type: 'photo', media: 'https://example.com/3.jpg' }
];

await bot.sendMediaGroupTenByTen(chatId, photos);

Custom Command with Regex

const echoCommand: IClsBot.IExportCMD = {
  active: true,
  regexp: /^\/echo (.+)$/,
  cmd: async (client, context, match) => {
    if (!match) return;
    const text = match[1];
    await context.ctx.reply(text);
  }
};

Error Handling

The bot includes built-in anti-crash handlers that catch unhandled exceptions and rejections:
await bot.loadHandlers(); // Loads anti-crash handlers

Environment Variables

TELEGRAM_TOKEN_DEV
string
required
Telegram bot token for development environment.
TELEGRAM_TOKEN_PROD
string
required
Telegram bot token for production environment.
NODE_ENV
'development' | 'production'
default:"'development'"
Environment mode.

Dependencies

  • node-telegram-bot-api - Telegram Bot API wrapper
  • @kreisler/bot-services - Shared bot services
  • @kreisler/createapi - API request utilities
  • @kreisler/debounce - Debounce utilities
  • @kreisler/js-helpers - JavaScript helper functions
  • file-type - File type detection

Build docs developers (and LLMs) love