๐ Xbibz Team Telegram Bot Library

๐จ Why Choose Xbibz?
๐ฏ Easy to Use
Simple and intuitive API that makes bot development a breeze
|
๐ High Performance
Optimized for speed and efficiency with minimal overhead
|
๐ช Full-Featured
Complete Telegram Bot API support with advanced features
|
๐ TypeScript First
Built with TypeScript for excellent type safety and IntelliSense
|
๐ง Flexible
Highly customizable with middleware and plugin support
|
๐ Well Documented
Comprehensive documentation with plenty of examples
|
โจ Features
๐ฎ Command Handling
- โ
Easy command registration
- โ
Multi-command support
- โ
Command arguments parsing
- โ
Bot name filtering
๐ฌ Message Processing
- โ
Text, Photo, Video, Audio
- โ
Documents, Stickers, Voice
- โ
Location, Contact, Poll
- โ
Custom filters
๐ Session Management
- โ
Built-in session support
- โ
Memory storage (default)
- โ
File/Redis/MongoDB support
- โ
Custom session handlers
๐ญ Middleware System
- โ
Powerful middleware chain
- โ
Easy to create custom middleware
- โ
Async/await support
- โ
Error handling
๐ฏ Inline & Callback Queries
- โ
Inline query handling
- โ
Callback query support
- โ
Regex pattern matching
- โ
Data-based routing
๐ ๏ธ Advanced Features
- โ
Complete API coverage
- โ
File upload support
- โ
Payment handling
- โ
Webhook support
๐ฆ Installation
npm install @xbibzlibrary/xbibz-team-telegram-bot
yarn add @xbibzlibrary/xbibz-team-telegram-bot
pnpm add @xbibzlibrary/xbibz-team-telegram-bot
๐ฏ Quick Start
Create your first bot in just a few lines of code!
import { XbibzTelegramBot } from '@xbibzlibrary/xbibz-team-telegram-bot';
const bot = new XbibzTelegramBot('YOUR_BOT_TOKEN', {
polling: true,
logLevel: 'info'
});
bot.command('start', async (ctx) => {
await ctx.reply('Hello! ๐ Welcome to Xbibz Bot!');
});
bot.onMessage(async (ctx) => {
if (ctx.text) {
await ctx.reply(`You said: ${ctx.text}`);
}
});
bot.launch();
console.log('๐ค Bot is running!');
๐ That's it! Your bot is now live!
Get your bot token from @BotFather and replace YOUR_BOT_TOKEN with it.
๐ Documentation
๐ฎ Command Handling
Commands are the backbone of Telegram bots. Xbibz makes it incredibly easy!
bot.command('help', async (ctx) => {
await ctx.reply('Need help? Contact @XbibzOfficial');
});
bot.command(['hello', 'hi', 'hey'], async (ctx) => {
await ctx.reply('Hello there! ๐');
});
bot.command('echo', async (ctx) => {
const args = ctx.stateData.args;
await ctx.reply(args.join(' '));
});
๐ฌ Message Handling
Handle different types of messages with ease!
bot.onMessage(async (ctx) => {
if (ctx.text) {
console.log('Received text:', ctx.text);
}
});
bot.messageHandler.onPhoto(async (ctx) => {
await ctx.reply('Nice photo! ๐ธ');
});
bot.messageHandler.onVideo(async (ctx) => {
await ctx.reply('Cool video! ๐ฅ');
});
bot.messageHandler.onDocument(async (ctx) => {
await ctx.reply('Got your document! ๐');
});
bot.messageHandler.onLocation(async (ctx) => {
const { latitude, longitude } = ctx.message.location;
await ctx.reply(`Your location: ${latitude}, ${longitude} ๐`);
});
๐ฏ Inline Keyboards & Callback Queries
Create interactive buttons for your bot!
bot.command('menu', async (ctx) => {
const keyboard = {
inline_keyboard: [
[
{ text: '๐ Stats', callback_data: 'stats' },
{ text: 'โ๏ธ Settings', callback_data: 'settings' }
],
[
{ text: 'โ Help', callback_data: 'help' }
]
]
};
await ctx.reply('Choose an option:', { reply_markup: keyboard });
});
bot.callbackQueryHandler.onData('stats', async (ctx) => {
await ctx.answerCallbackQuery({ text: 'Loading stats...' });
await ctx.editMessage('Here are your stats! ๐');
});
bot.callbackQueryHandler.onData('settings', async (ctx) => {
await ctx.answerCallbackQuery();
await ctx.editMessage('Settings menu โ๏ธ');
});
bot.callbackQueryHandler.onRegex(/^page_(\d+)$/, async (ctx) => {
const match = ctx.stateData.callbackMatch;
const page = match[1];
await ctx.editMessage(`Showing page ${page}`);
});
๐ Session Management
Keep track of user data across conversations!
const bot = new XbibzTelegramBot('YOUR_BOT_TOKEN', {
session: {
enabled: true,
storage: 'memory',
defaultSession: { count: 0 }
}
});
bot.command('count', async (ctx) => {
ctx.session.count = (ctx.session.count || 0) + 1;
await ctx.reply(`Button pressed ${ctx.session.count} times!`);
});
bot.command('reset', async (ctx) => {
ctx.session.count = 0;
await ctx.reply('Counter reset! ๐');
});
๐ญ Custom Middleware
Create powerful middleware for your bot!
bot.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`Processing took ${ms}ms`);
});
async function adminOnly(ctx, next) {
const adminIds = [123456789, 987654321];
if (adminIds.includes(ctx.fromId)) {
return next();
}
await ctx.reply('โ Admin only command!');
}
bot.command('admin', adminOnly, async (ctx) => {
await ctx.reply('โ
Admin access granted!');
});
const userLastMessage = new Map();
bot.use(async (ctx, next) => {
const userId = ctx.fromId;
const now = Date.now();
const lastMsg = userLastMessage.get(userId) || 0;
if (now - lastMsg < 1000) {
await ctx.reply('โฐ Please wait before sending another message!');
return;
}
userLastMessage.set(userId, now);
await next();
});
๐จ Filters
Use filters to handle specific types of messages!
import { Filter } from '@xbibzlibrary/xbibz-team-telegram-bot';
bot.use(async (ctx, next) => {
if (Filter.private(ctx)) {
return next();
}
await ctx.reply('This command works only in private chats!');
});
bot.use(async (ctx, next) => {
if (Filter.and(Filter.private, Filter.photo)(ctx)) {
await ctx.reply('Private photo received! ๐ธ');
}
await next();
});
bot.use(async (ctx, next) => {
if (Filter.contains('hello')(ctx)) {
await ctx.reply('Hello! ๐');
}
await next();
});
bot.use(async (ctx, next) => {
if (Filter.regex(/\d{4}/)(ctx)) {
await ctx.reply('Found a 4-digit number!');
}
await next();
});
๐ค Sending Messages
Multiple ways to send messages!
await ctx.reply('Hello World!');
await ctx.reply('*Bold* _italic_ `code`', {
parse_mode: 'Markdown'
});
await ctx.reply('<b>Bold</b> <i>italic</i>', {
parse_mode: 'HTML'
});
await ctx.reply('This is a reply!', {
reply_to_message_id: ctx.messageId
});
await ctx.replyWithPhoto('https://example.com/photo.jpg', 'Photo caption');
await ctx.replyWithVideo('https://example.com/video.mp4', 'Video caption');
await ctx.replyWithDocument('https://example.com/doc.pdf', 'Document caption');
await ctx.replyWithLocation(51.5074, -0.1278);
await ctx.replyWithPoll('What is your favorite color?', [
'Red', 'Blue', 'Green', 'Yellow'
]);
๐ฏ Context (ctx) Methods
The context object gives you access to everything!
bot.onMessage(async (ctx) => {
const text = ctx.text;
const messageId = ctx.messageId;
const chatId = ctx.chatId;
const userId = ctx.fromId;
const user = ctx.from;
console.log(user.first_name, user.username);
const chat = ctx.chat;
console.log(chat.type);
ctx.session.userData = 'some data';
await ctx.sendTyping();
await ctx.editMessage('New text');
await ctx.deleteMessage();
await ctx.forwardMessage(fromChatId, messageId);
await ctx.banChatMember(userId);
await ctx.unbanChatMember(userId);
await ctx.pinChatMessage(messageId);
});
๐ก Examples
๐ Example 1: Simple Echo Bot
import { XbibzTelegramBot } from '@xbibzlibrary/xbibz-team-telegram-bot';
const bot = new XbibzTelegramBot('YOUR_BOT_TOKEN');
bot.command('start', async (ctx) => {
await ctx.reply('Echo bot started! Send me any message.');
});
bot.onMessage(async (ctx) => {
if (ctx.text && !ctx.text.startsWith('/')) {
await ctx.reply(ctx.text);
}
});
bot.launch();
๐ฎ Example 2: Quiz Bot
const bot = new XbibzTelegramBot('YOUR_BOT_TOKEN', {
session: { enabled: true }
});
const questions = [
{ q: 'What is 2+2?', a: '4' },
{ q: 'Capital of France?', a: 'Paris' },
{ q: 'Largest planet?', a: 'Jupiter' }
];
bot.command('quiz', async (ctx) => {
ctx.session.score = 0;
ctx.session.questionIndex = 0;
const q = questions[0];
await ctx.reply(`Question 1: ${q.q}`);
});
bot.onMessage(async (ctx) => {
if (ctx.session.questionIndex !== undefined) {
const currentQ = questions[ctx.session.questionIndex];
if (ctx.text?.toLowerCase() === currentQ.a.toLowerCase()) {
ctx.session.score++;
await ctx.reply('โ
Correct!');
} else {
await ctx.reply(`โ Wrong! Answer: ${currentQ.a}`);
}
ctx.session.questionIndex++;
if (ctx.session.questionIndex < questions.length) {
const nextQ = questions[ctx.session.questionIndex];
await ctx.reply(`Question ${ctx.session.questionIndex + 1}: ${nextQ.q}`);
} else {
await ctx.reply(`๐ Quiz finished! Score: ${ctx.session.score}/${questions.length}`);
delete ctx.session.questionIndex;
}
}
});
bot.launch();
๐ Example 3: Shopping Bot
const bot = new XbibzTelegramBot('YOUR_BOT_TOKEN', {
session: { enabled: true, defaultSession: { cart: [] } }
});
const products = {
'apple': { name: 'Apple', price: 1.5 },
'banana': { name: 'Banana', price: 0.8 },
'orange': { name: 'Orange', price: 1.2 }
};
bot.command('shop', async (ctx) => {
const keyboard = {
inline_keyboard: Object.keys(products).map(key => ([
{ text: `${products[key].name} - $${products[key].price}`, callback_data: `buy_${key}` }
]))
};
await ctx.reply('๐ Welcome to our shop!', { reply_markup: keyboard });
});
bot.callbackQueryHandler.onRegex(/^buy_(.+)$/, async (ctx) => {
const productKey = ctx.stateData.callbackMatch[1];
const product = products[productKey];
ctx.session.cart.push(product);
await ctx.answerCallbackQuery({ text: `Added ${product.name} to cart!` });
});
bot.command('cart', async (ctx) => {
if (ctx.session.cart.length === 0) {
await ctx.reply('๐ Your cart is empty!');
return;
}
const total = ctx.session.cart.reduce((sum, item) => sum + item.price, 0);
const items = ctx.session.cart.map(item => `${item.name} - $${item.price}`).join('\n');
await ctx.reply(`๐ Your cart:\n${items}\n\nTotal: $${total.toFixed(2)}`);
});
bot.command('clear', async (ctx) => {
ctx.session.cart = [];
await ctx.reply('๐๏ธ Cart cleared!');
});
bot.launch();
๐๏ธ Project Structure
xbibz-team-telegram-bot/
โโโ src/
โ โโโ core/
โ โ โโโ bot.ts # Main bot class
โ โ โโโ context.ts # Context class
โ โโโ api/
โ โ โโโ api-client.ts # Telegram API client
โ โโโ handlers/
โ โ โโโ command-handler.ts
โ โ โโโ message-handler.ts
โ โ โโโ callback-query-handler.ts
โ โ โโโ inline-query-handler.ts
โ โโโ middleware/
โ โ โโโ middleware.ts # Middleware system
โ โโโ session/
โ โ โโโ session-manager.ts
โ โโโ filters/
โ โ โโโ filter.ts # Message filters
โ โโโ utils/
โ โ โโโ logger.ts
โ โ โโโ error-handler.ts
โ โโโ types/
โ โ โโโ index.ts # TypeScript types
โ โโโ index.ts # Main export
โโโ examples/
โ โโโ basic/
โ โโโ advanced/
โ โโโ custom-middleware/
โโโ tests/
โโโ dist/ # Compiled output
โโโ package.json
๐ Building & Development
npm install
npm run build
npm run dev
npm test
npm run lint
npm run clean
๐ค Contributing
We welcome contributions! Here's how you can help:
- ๐ด Fork the repository
- ๐ฟ Create a new branch (
git checkout -b feature/amazing-feature)
- ๐พ Commit your changes (
git commit -m 'Add amazing feature')
- ๐ค Push to the branch (
git push origin feature/amazing-feature)
- ๐ Open a Pull Request
๐ฌ Get in Touch
Found this helpful? Consider supporting the project! โค๏ธ
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
Author ๐ฟ

๐ Star History
If you like this project, please give it a โญ on GitHub!