tgram.js
v1.22.0
Published
Lightweight modern library for telegram bot. use Node.js
Maintainers
Readme
tgram.js
A modern, lightweight Telegram Bot library for Node.js with native ESM support.
Features
- Pure ESM Module - Native ES module support with modern JavaScript
- Minimal API Surface - Clean, intuitive interface for rapid development
- Command System - Built-in command routing with customizable prefixes
- Rich Media Support - Audio, stickers, documents, and file handling
- Interactive Components - Button interfaces and callback handling
- Zero Dependencies - Lightweight with no external dependencies
- TypeScript Native - Written in TypeScript with complete type definitions
Installation
npm install tgram.jsQuick Start
import { TelegramJS } from "tgram.js";
const bot = new TelegramJS({
token: "YOUR_BOT_TOKEN",
prefix: "#"
});
bot.commands("start", async (tg) => {
await tg.reply("Bot initialized successfully");
});
bot.setup();
await bot.start();Requirements
- Node.js >= 16.0.0
- ES modules environment
Installation
npm install tgram.jsBasic Usage
import { TelegramJS } from "tgram.js";
const bot = new TelegramJS({
token: process.env.BOT_TOKEN,
prefix: "#"
});
bot.commands("start", async (tg) => {
await tg.reply("Bot initialized successfully");
});
bot.setup();
await bot.start();Advanced Examples
Command with Parameters
bot.commands("ytmp3", async (tg, text) => {
if (!text) return tg.reply("Please provide a YouTube URL");
try {
const { data } = await fetch(`https://api.example.com/youtube?url=${text}&type=audio`);
const response = await data.json();
await tg.sendAudio(response.downloadUrl, `${response.title}.mp3`);
} catch (error) {
await tg.reply("Failed to process request");
}
});API Reference
The library automatically parses incoming messages and provides a rich context object:
bot.commands("example", async (tg, text) => {
console.log({
jid: tg.jid, // Chat ID: -1001234567890
command: tg.command, // Parsed command: "example"
args: tg.args, // Arguments array: ["arg1", "arg2"]
textArgs: tg.textArgs, // Arguments string: "arg1 arg2"
from: tg.from, // User object: { id, username, first_name }
chat: tg.chat // Chat object: { id, type, title }
});
});Media Operations Examples
bot.commands("media", async (tg) => {
// Send photo with caption
await tg.sendPhoto("https://example.com/image.jpg", "Beautiful sunset");
// Send audio file
await tg.sendAudio("https://example.com/audio.mp3", "song.mp3", "My favorite song");
// Send video
await tg.sendVideo("https://example.com/video.mp4", "Tutorial video");
// Send sticker
await tg.sendSticker("https://example.com/sticker.webp", "funny.webp");
// Send document from URL
await tg.sendDocument("https://example.com/file.pdf", "manual.pdf", "User manual");
// Send document from Buffer
const buffer = Buffer.from("Generated content");
await tg.sendDocument(buffer, "report.txt", "System report");
// Interactive button
await tg.sendButton("Select action:", ["Download", "download_action"]);
});TelegramJS Class
Constructor
new TelegramJS(options: BotOptions)BotOptions:
token: string- Telegram bot token from @BotFatherprefix: string- Command prefix (default: "/")
Methods
bot.commands(command: string, handler: CommandHandler) Register command handler for specified command.
bot.setup(): void Initialize bot configuration and middleware.
bot.start(): Promise Start polling for updates from Telegram servers.
bot.sendDocumentMessage(jid: string, buffer: Buffer, filename: string, caption?: string): Promise Send document from buffer to specified chat.
TelegramContext (tg)
The context object passed to command handlers contains message data and utility methods.
Properties
tg.update: Complete update object from Telegram API
tg.jid: Chat ID (equivalent to tg.message.chat.id)
tg.message: Original message object from Telegram
tg.chat: Chat information object
tg.from: Sender information object
tg.text: Full message text content
tg.command: Extracted command name (lowercase)
tg.args: Array of command arguments
tg.textArgs: Command arguments joined as string
Methods
tg.reply(text: string): Promise Send text message as reply to current chat.
await tg.reply("Hello world");tg.sendPhoto(photo: string, caption?: string): Promise Send photo by URL or file path with optional caption.
await tg.sendPhoto("https://example.com/image.jpg", "Photo caption");tg.sendAudio(audioUrl: string, filename: string, caption?: string): Promise Send audio file with specified filename and optional caption.
await tg.sendAudio("https://example.com/audio.mp3", "song.mp3", "Audio description");tg.sendVideo(videoUrl: string, caption?: string): Promise Send video file by URL with optional caption.
await tg.sendVideo("https://example.com/video.mp4", "Video description");tg.sendSticker(stickerUrl: string, filename: string): Promise Send sticker by URL with specified filename.
await tg.sendSticker("https://example.com/sticker.webp", "sticker.webp");tg.sendDocument(document: string | Buffer, filename: string, caption?: string): Promise Send document file (supports URL, file path, or Buffer) with filename and optional caption.
// Send from URL
await tg.sendDocument("https://example.com/file.pdf", "document.pdf", "File caption");
// Send from Buffer
const buffer = Buffer.from("File content");
await tg.sendDocument(buffer, "textfile.txt", "Generated file");tg.sendButton(text: string, buttons: [string, string], options?: object): Promise
Send message with inline keyboard buttons. Buttons format: [display_text, callback_data].
await tg.sendButton("Choose an option:", ["Click me", "callback_data"], {
// Optional additional parameters
});Error Handling
bot.commands("example", async (tg) => {
try {
// Your bot logic here
await tg.reply("Success");
} catch (error) {
console.error("Command error:", error);
await tg.reply("An error occurred");
}
});Environment Configuration
Create a .env file:
BOT_TOKEN=your_telegram_bot_token_hereLoad in your application:
import dotenv from 'dotenv';
dotenv.config();
const bot = new TelegramJS({
token: process.env.BOT_TOKEN,
prefix: "#"
});Contributing
Comming Soon.
License
MIT License. See LICENSE file for details.
Changelog
v1.2.1
- Enhanced media handling capabilities
- Improved button interface system
- Performance optimizations for polling
- Bug fixes in document sending functionality
Built with modern JavaScript for the modern web.
