UNPKG

tgram.js

Version:

Lightweight modern library for telegram bot. use Node.js

288 lines (207 loc) 7.43 kB
# tgram.js A modern, lightweight Telegram Bot library for Node.js with native ESM support. [![npm version](https://img.shields.io/npm/v/tgram.js.svg)](https://www.npmjs.com/package/tgram.js) [![License](https://img.shields.io/npm/l/tgram.js.svg)](https://github.com/yourusername/tgram.js/blob/main/LICENSE) [![Node.js Version](https://img.shields.io/node/v/tgram.js.svg)](https://nodejs.org/) ## 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 ```bash npm install tgram.js ``` ## Quick Start ```javascript 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 ```bash npm install tgram.js ``` ## Basic Usage ```javascript 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 ```javascript 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: ```javascript 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 ```javascript 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 ```typescript new TelegramJS(options: BotOptions) ``` **BotOptions:** - `token: string` - Telegram bot token from @BotFather - `prefix: 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<void>** Start polling for updates from Telegram servers. **bot.sendDocumentMessage(jid: string, buffer: Buffer, filename: string, caption?: string): Promise<void>** 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<void>** Send text message as reply to current chat. ```javascript await tg.reply("Hello world"); ``` **tg.sendPhoto(photo: string, caption?: string): Promise<void>** Send photo by URL or file path with optional caption. ```javascript await tg.sendPhoto("https://example.com/image.jpg", "Photo caption"); ``` **tg.sendAudio(audioUrl: string, filename: string, caption?: string): Promise<void>** Send audio file with specified filename and optional caption. ```javascript await tg.sendAudio("https://example.com/audio.mp3", "song.mp3", "Audio description"); ``` **tg.sendVideo(videoUrl: string, caption?: string): Promise<void>** Send video file by URL with optional caption. ```javascript await tg.sendVideo("https://example.com/video.mp4", "Video description"); ``` **tg.sendSticker(stickerUrl: string, filename: string): Promise<void>** Send sticker by URL with specified filename. ```javascript await tg.sendSticker("https://example.com/sticker.webp", "sticker.webp"); ``` **tg.sendDocument(document: string | Buffer, filename: string, caption?: string): Promise<void>** Send document file (supports URL, file path, or Buffer) with filename and optional caption. ```javascript // 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<void>** Send message with inline keyboard buttons. Buttons format: `[display_text, callback_data]`. ```javascript await tg.sendButton("Choose an option:", ["Click me", "callback_data"], { // Optional additional parameters }); ``` ## Error Handling ```javascript 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: ```env BOT_TOKEN=your_telegram_bot_token_here ``` Load in your application: ```javascript import dotenv from 'dotenv'; dotenv.config(); const bot = new TelegramJS({ token: process.env.BOT_TOKEN, prefix: "#" }); ``` ## Contributing **Comming Soon.** ## License MIT License. See [LICENSE](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.