@xbibzlibrary/xbibz-team-telegram-bot
v1.0.1
Published
A powerful and comprehensive Telegram bot library for TypeScript that exceeds Telegraf in functionality and ease of use
Maintainers
Readme
🚀 Xbibz Team Telegram Bot Library
⚡ A powerful and comprehensive Telegram bot library for TypeScript
Built with ❤️ by Xbibz Official
🌟 Features • 📦 Installation • 🎯 Quick Start • 📖 Documentation • 💡 Examples
🎨 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
# Using npm
npm install @xbibzlibrary/xbibz-team-telegram-bot
# Using yarn
yarn add @xbibzlibrary/xbibz-team-telegram-bot
# Using pnpm
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';
// Initialize the bot
const bot = new XbibzTelegramBot('YOUR_BOT_TOKEN', {
polling: true,
logLevel: 'info'
});
// Handle /start command
bot.command('start', async (ctx) => {
await ctx.reply('Hello! 👋 Welcome to Xbibz Bot!');
});
// Handle text messages
bot.onMessage(async (ctx) => {
if (ctx.text) {
await ctx.reply(`You said: ${ctx.text}`);
}
});
// Launch the bot
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!
// Single command
bot.command('help', async (ctx) => {
await ctx.reply('Need help? Contact @XbibzOfficial');
});
// Multiple commands
bot.command(['hello', 'hi', 'hey'], async (ctx) => {
await ctx.reply('Hello there! 👋');
});
// Access command arguments
bot.command('echo', async (ctx) => {
const args = ctx.stateData.args; // Array of arguments
await ctx.reply(args.join(' '));
});💬 Message Handling
Handle different types of messages with ease!
// Text messages
bot.onMessage(async (ctx) => {
if (ctx.text) {
console.log('Received text:', ctx.text);
}
});
// Photo messages
bot.messageHandler.onPhoto(async (ctx) => {
await ctx.reply('Nice photo! 📸');
});
// Video messages
bot.messageHandler.onVideo(async (ctx) => {
await ctx.reply('Cool video! 🎥');
});
// Document messages
bot.messageHandler.onDocument(async (ctx) => {
await ctx.reply('Got your document! 📄');
});
// Location messages
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!
// Send message with inline keyboard
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 });
});
// Handle callback queries
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 ⚙️');
});
// Use regex for callback data
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', // or 'file', 'redis', 'mongodb'
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!
// Logging middleware
bot.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`Processing took ${ms}ms`);
});
// Admin-only middleware
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!');
});
// Rate limiting middleware
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) { // 1 second cooldown
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';
// Private chat only
bot.use(async (ctx, next) => {
if (Filter.private(ctx)) {
return next();
}
await ctx.reply('This command works only in private chats!');
});
// Photo in private chat
bot.use(async (ctx, next) => {
if (Filter.and(Filter.private, Filter.photo)(ctx)) {
await ctx.reply('Private photo received! 📸');
}
await next();
});
// Text containing "hello"
bot.use(async (ctx, next) => {
if (Filter.contains('hello')(ctx)) {
await ctx.reply('Hello! 👋');
}
await next();
});
// Regex pattern
bot.use(async (ctx, next) => {
if (Filter.regex(/\d{4}/)(ctx)) { // 4 digits
await ctx.reply('Found a 4-digit number!');
}
await next();
});📤 Sending Messages
Multiple ways to send messages!
// Simple text
await ctx.reply('Hello World!');
// With formatting
await ctx.reply('*Bold* _italic_ `code`', {
parse_mode: 'Markdown'
});
// With HTML
await ctx.reply('<b>Bold</b> <i>italic</i>', {
parse_mode: 'HTML'
});
// Reply to message
await ctx.reply('This is a reply!', {
reply_to_message_id: ctx.messageId
});
// Send photo
await ctx.replyWithPhoto('https://example.com/photo.jpg', 'Photo caption');
// Send video
await ctx.replyWithVideo('https://example.com/video.mp4', 'Video caption');
// Send document
await ctx.replyWithDocument('https://example.com/doc.pdf', 'Document caption');
// Send location
await ctx.replyWithLocation(51.5074, -0.1278); // London coordinates
// Send poll
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) => {
// Message info
const text = ctx.text;
const messageId = ctx.messageId;
const chatId = ctx.chatId;
const userId = ctx.fromId;
// User info
const user = ctx.from;
console.log(user.first_name, user.username);
// Chat info
const chat = ctx.chat;
console.log(chat.type); // private, group, supergroup, channel
// Session
ctx.session.userData = 'some data';
// Typing action
await ctx.sendTyping();
// Edit message
await ctx.editMessage('New text');
// Delete message
await ctx.deleteMessage();
// Forward message
await ctx.forwardMessage(fromChatId, messageId);
// Chat actions
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
# Install dependencies
npm install
# Build the project
npm run build
# Development mode (watch)
npm run dev
# Run tests
npm test
# Lint code
npm run lint
# Clean build
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
📞 Support & Community
💬 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!
Made with ❤️ by Xbibz Official
Happy Botting! 🤖✨


