telegram-polling-bot
v1.0.0
Published
Lightweight, type-safe Telegram bot library using long polling
Maintainers
Readme
telegram-polling-bot
A lightweight, type-safe Telegram bot library using long polling.
Installation
npm install telegram-polling-botQuick Start
import { TelegramBot } from 'telegram-polling-bot';
const bot = new TelegramBot({
token: 'YOUR_BOT_TOKEN',
chatId: 'YOUR_CHAT_ID', // Optional: filter messages from specific chat
});
// Handle commands
bot.onCommand('start', async (ctx) => {
await ctx.reply('Hello! I am your bot.');
});
// Handle text patterns
bot.onText(/^\d{4}$/, async (ctx, match) => {
await ctx.reply(`You sent a 4-digit code: ${match[0]}`);
});
// Handle all messages
bot.onMessage(async (ctx) => {
console.log('Received:', ctx.message.text);
});
// Start polling
bot.start();API Reference
Constructor
const bot = new TelegramBot(options);Options:
token(string, required): Telegram bot token from @BotFatherchatId(string | number, optional): Filter messages from specific chatpollingInterval(number, optional): Polling interval in ms (default: 3000)onError(function, optional): Global error handler
Methods
bot.onCommand(command, handler)
Handle slash commands like /start, /help
bot.onCommand('start', async (ctx) => {
await ctx.reply('Welcome!');
});bot.onText(pattern, handler)
Handle messages matching regex pattern
bot.onText(/hello/i, async (ctx) => {
await ctx.reply('Hi there!');
});bot.onMessage(handler)
Handle all incoming messages
bot.onMessage(async (ctx) => {
console.log('Message:', ctx.message.text);
});bot.use(middleware)
Add middleware for message processing
bot.use(async (ctx, next) => {
console.log('Before:', ctx.message.text);
await next();
console.log('After processing');
});bot.start()
Start polling for messages
await bot.start();bot.stop()
Stop polling
bot.stop();Context API (ctx)
The context object passed to handlers contains:
interface Context {
message: TelegramMessage; // Original message
bot: TelegramBot; // Bot instance
// Send text message
reply(text: string): Promise<void>;
// Send photo
sendPhoto(photo: string | Buffer, caption?: string): Promise<void>;
// Send document
sendDocument(document: string | Buffer, caption?: string): Promise<void>;
// Get update data
update: TelegramUpdate;
}Advanced Usage
Multiple Handlers
// Login command
bot.onCommand('login', async (ctx) => {
await ctx.reply('Logging you in...');
// Perform login logic
});
// Status command
bot.onCommand('status', async (ctx) => {
await ctx.sendPhoto(screenshot, 'Current status');
});
// Captcha code (4 digits)
bot.onText(/^\d{4}$/, async (ctx, match) => {
const code = match[0];
await ctx.reply(`Processing captcha code: ${code}`);
});Middleware Chain
// Logging middleware
bot.use(async (ctx, next) => {
console.log(`[${new Date().toISOString()}] ${ctx.message.text}`);
await next();
});
// Authentication middleware
bot.use(async (ctx, next) => {
if (ctx.message.chat.id !== AUTHORIZED_CHAT_ID) {
await ctx.reply('Unauthorized');
return;
}
await next();
});
// Commands will only run after middleware passes
bot.onCommand('admin', async (ctx) => {
await ctx.reply('Admin command executed');
});Error Handling
const bot = new TelegramBot({
token: TOKEN,
onError: (error) => {
console.error('Bot error:', error);
// Send to monitoring service
},
});
// Per-handler error handling
bot.onCommand('start', async (ctx) => {
try {
await riskyOperation();
} catch (error) {
await ctx.reply('Something went wrong!');
}
});Custom Message Sending
// Direct API access
await bot.sendMessage(chatId, 'Hello!');
await bot.sendPhoto(chatId, photoBuffer, 'Caption here');
await bot.sendDocument(chatId, fileBuffer, 'document.pdf');Examples
Captcha Solver Bot
import { TelegramBot } from 'telegram-polling-bot';
const bot = new TelegramBot({
token: process.env.BOT_TOKEN!,
chatId: process.env.CHAT_ID!,
});
// Handle 1-4 digit captcha codes
bot.onText(/^\d{1,4}$/, async (ctx, match) => {
const code = match[0];
console.log('Solving captcha with code:', code);
// Solve captcha logic here
const solved = await solveCaptcha(code);
if (solved) {
await ctx.reply('✅ Captcha solved successfully!');
} else {
await ctx.reply('❌ Failed to solve captcha');
}
});
bot.start();Multi-Command Bot
import { TelegramBot } from 'telegram-polling-bot';
const bot = new TelegramBot({
token: process.env.BOT_TOKEN!,
});
bot.onCommand('start', async (ctx) => {
await ctx.reply('Welcome! Available commands:\n/status - Get status\n/login - Login');
});
bot.onCommand('status', async (ctx) => {
const screenshot = await captureScreen();
await ctx.sendPhoto(screenshot, 'Current status');
});
bot.onCommand('login', async (ctx) => {
await performLogin();
await ctx.reply('Logged in successfully!');
});
bot.onCommand('help', async (ctx) => {
await ctx.reply('Commands:\n/start\n/status\n/login\n/help');
});
bot.start();TypeScript Support
Full TypeScript support out of the box:
import { TelegramBot, Context, TelegramMessage } from 'telegram-polling-bot';
const bot = new TelegramBot({
token: process.env.BOT_TOKEN!,
});
bot.onCommand('test', async (ctx: Context) => {
const message: TelegramMessage = ctx.message;
await ctx.reply('Type-safe!');
});License
MIT
