py-telegram
v1.0.0
Published
Official Telegram Bot API integration for Payaar
Maintainers
Readme
py-telegram
Production-ready Telegram Bot framework for Node.js with TypeScript
Features
- ✅ Dual Mode: Polling and Webhook support
- ✅ High Performance: Handle 10,000+ messages/second
- ✅ Type Safe: Full TypeScript support with complete type definitions
- ✅ Production Ready: Rate limiting, error handling, queue system
- ✅ Developer Friendly: Simple API, comprehensive documentation
- ✅ Extensible: Middleware system, session management, handlers
Installation
# Using npm
npm install py-telegram
# Using pnpm
pnpm add py-telegram
# Using yarn
yarn add py-telegramQuick Start
Basic Echo Bot (Polling Mode)
import { TelegramClient } from 'py-telegram';
const bot = new TelegramClient({
token: process.env.TELEGRAM_BOT_TOKEN,
polling: { enabled: true },
});
bot.command('start', async (ctx) => {
await ctx.reply('Hello! I am your bot 🤖');
});
bot.on('message', async (ctx) => {
await ctx.reply(`You said: ${ctx.message?.text}`);
});
await bot.start();Webhook Mode with Express
import express from 'express';
import { TelegramClient } from 'py-telegram';
const app = express();
const bot = new TelegramClient({
token: process.env.TELEGRAM_BOT_TOKEN,
webhook: {
enabled: true,
url: process.env.WEBHOOK_URL,
secretToken: process.env.WEBHOOK_SECRET,
},
});
app.post('/telegram/webhook', express.json(), async (req, res) => {
await bot.handleWebhookUpdate(req.body);
res.sendStatus(200);
});
bot.on('message', async (ctx) => {
await ctx.reply('Hello from webhook mode!');
});
app.listen(3000, async () => {
await bot.setupWebhook();
console.log('Webhook server running on port 3000');
});Command Handler
import { TelegramClient } from 'py-telegram';
const bot = new TelegramClient({
token: process.env.TELEGRAM_BOT_TOKEN,
polling: { enabled: true },
});
bot.command('start', async (ctx) => {
await ctx.reply('Welcome! Use /help for available commands.');
});
bot.command('help', async (ctx) => {
const help = `
Available commands:
/start - Start the bot
/help - Show this help
/echo <text> - Echo your message
`.trim();
await ctx.reply(help);
});
bot.command('echo', async (ctx) => {
const text = ctx.message?.text?.split(' ').slice(1).join(' ');
await ctx.reply(text || 'Please provide text to echo');
});
await bot.start();Inline Keyboards
import { TelegramClient, InlineKeyboard } from 'py-telegram';
const bot = new TelegramClient({
token: process.env.TELEGRAM_BOT_TOKEN,
polling: { enabled: true },
});
bot.command('menu', async (ctx) => {
const keyboard = new InlineKeyboard()
.text('Option 1', 'option_1')
.text('Option 2', 'option_2')
.row()
.url('Visit Website', 'https://example.com');
await ctx.reply('Choose an option:', { reply_markup: keyboard });
});
bot.on('callback_query', async (ctx) => {
await ctx.answerCallbackQuery();
await ctx.reply(`You selected: ${ctx.callbackQuery.data}`);
});
await bot.start();Documentation
📚 Complete Guides:
- Getting Started Guide - Installation and setup
- Package Guide - Full API reference
- Quick Reference - Common patterns and snippets
- Migration Guide - Migrate from other libraries
- Publishing Guide - npm publishing
Examples
See examples/ directory for complete working examples:
- Basic Echo Bot
- Command Handler
- Inline Keyboards
- Webhook with Express
- Advanced Polling
- Media Upload/Download
- Session Management
- Custom Middleware
Configuration
Basic Configuration
import { TelegramClient } from 'py-telegram';
const bot = new TelegramClient({
// Required
token: process.env.TELEGRAM_BOT_TOKEN,
// Polling mode
polling: {
enabled: true,
interval: 1000, // Poll every 1 second
timeout: 30, // Long polling timeout
},
// OR Webhook mode
webhook: {
enabled: true,
url: 'https://yourdomain.com/webhook',
secretToken: 'your-secret-token',
},
// Optional: Rate limiting
rateLimiting: {
enabled: true,
maxRetries: 3,
retryDelay: 1000,
},
// Optional: Logging
logging: {
enabled: true,
level: 'info', // 'debug' | 'info' | 'warn' | 'error'
},
});API Methods
Sending Messages
// Send text message
await bot.api.sendMessage({
chat_id: chatId,
text: 'Hello, World!',
});
// Send photo
await bot.api.sendPhoto({
chat_id: chatId,
photo: 'https://example.com/photo.jpg',
caption: 'Photo caption',
});
// Send document
await bot.api.sendDocument({
chat_id: chatId,
document: fs.createReadStream('file.pdf'),
});
// Edit message
await bot.api.editMessageText({
chat_id: chatId,
message_id: messageId,
text: 'Updated text',
});
// Delete message
await bot.api.deleteMessage({
chat_id: chatId,
message_id: messageId,
});Events
Available Events
// Message events
bot.on('message', handler); // Any message
bot.on('message:text', handler); // Text messages
bot.on('message:photo', handler); // Photo messages
bot.on('message:video', handler); // Video messages
bot.on('message:document', handler); // Document messages
bot.on('message:audio', handler); // Audio messages
// Other events
bot.on('callback_query', handler); // Inline button clicks
bot.on('inline_query', handler); // Inline mode queries
bot.on('poll', handler); // Poll updates
bot.on('chat_member', handler); // Chat member updatesMiddleware
import { TelegramClient } from 'py-telegram';
const bot = new TelegramClient({
token: process.env.TELEGRAM_BOT_TOKEN,
polling: { enabled: true },
});
// Logging middleware
bot.use(async (ctx, next) => {
console.log(`Update: ${ctx.update.update_id}`);
await next();
});
// Auth middleware
bot.use(async (ctx, next) => {
if (ctx.from?.id === ADMIN_ID) {
await next();
} else {
await ctx.reply('Unauthorized');
}
});
// Error handling
bot.use(async (ctx, next) => {
try {
await next();
} catch (error) {
console.error('Error:', error);
await ctx.reply('An error occurred');
}
});Contributing
Contributions are welcome! Please read our Contributing Guide for details on code of conduct and the process for submitting pull requests.
License
MIT © Aurasko Development Team
Support
Built with ❤️ by the Aurasko Development Team
Based on the official Telegram Bot API
