### Setup Repository Source: https://github.com/alfandi09/vibegram/blob/main/CONTRIBUTING.md Commands to clone the repository and install necessary dependencies. ```bash git clone https://github.com/[your-username]/vibegram.git cd vibegram npm install ``` -------------------------------- ### Quick Start: Defining and Using a Scene Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/scenes.md A basic example demonstrating how to define a scene, add handlers, and enter it. ```APIDOC ## Quick Start: Defining and Using a Scene ### Description This example shows the fundamental steps to create a scene, attach handlers to it, and then enter the scene from a command. ### Code Example ```typescript import { Bot, session, Scene, Stage } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session()); // Define a scene const settingsScene = new Scene('settings'); settingsScene.command('theme', ctx => ctx.reply('Choose: light or dark?')); settingsScene.hears('back', ctx => { ctx.reply('Exiting settings.'); ctx.scene?.leave(); }); settingsScene.on('message', ctx => ctx.reply('You are in settings. Type "back" to exit.')); // Register and activate the stage const stage = new Stage([settingsScene]); bot.use(stage.middleware()); // Command to enter the scene bot.command('settings', ctx => ctx.scene?.enter('settings')); ``` ``` -------------------------------- ### Inline Query Builder - Quick Start Source: https://github.com/alfandi09/vibegram/blob/main/docs/api/inline-builder.md A quick start guide demonstrating how to initialize the Vibegram bot and use the InlineResults builder to respond to inline queries. ```APIDOC ## Inline Query Builder - Quick Start This example shows how to set up a bot to handle inline queries and respond with formatted results using the `InlineResults` builder. ### Method `bot.on('inline_query', async (ctx) => { ... });` ### Endpoint N/A (This is an event handler for inline queries) ### Parameters N/A ### Request Example ```typescript import { Bot, InlineResults } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.on('inline_query', async (ctx) => { const query = ctx.update.inline_query?.query || ''; const results = InlineResults.builder() .article({ id: '1', title: 'Hello World', text: `You searched for: ${query}`, description: 'Send a greeting' }) .photo({ id: '2', url: 'https://picsum.photos/400', caption: 'Random photo' }) .build(); await ctx.answerInlineQuery(results, { cache_time: 10 }); }); ``` ### Response N/A (The `ctx.answerInlineQuery` method sends the results to the Telegram client.) ``` -------------------------------- ### Create and Install Plugins Source: https://context7.com/alfandi09/vibegram/llms.txt Demonstrates creating class-based and functional plugins, combining them into presets, and installing them on a bot instance. Ensure plugins are correctly imported and instantiated before installation. ```typescript import { Bot, BotPlugin, createPlugin, Preset, Composer } from 'vibegram'; // Class-based plugin class AnalyticsPlugin implements BotPlugin { name = 'analytics'; install(composer: Composer) { composer.use(async (ctx, next) => { const start = Date.now(); await next(); console.log(`[Analytics] Update processed in ${Date.now() - start}ms`); }); } } // Functional plugin with options const greetingPlugin = createPlugin('greeting', (composer, opts: { message: string }) => { composer.command('hello', (ctx) => ctx.reply(opts.message)); }); // Combine plugins into preset const productionPreset = new Preset('production', [ new AnalyticsPlugin(), greetingPlugin({ message: 'Welcome to our bot!' }) ]); const bot = new Bot('YOUR_BOT_TOKEN'); // Install individual plugins bot.plugin(new AnalyticsPlugin()); bot.plugin(greetingPlugin({ message: 'Hello!' })); // Or install preset (multiple plugins at once) bot.plugin(productionPreset); bot.launch(); ``` -------------------------------- ### Conversations Quick Start Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/conversations.md A basic example demonstrating how to set up and use a Conversation for a simple order process. ```APIDOC ## Quick Start Example ### Description This example shows how to initialize a `Conversation`, define a multi-step dialogue for taking an order, and integrate it into a Vibegram bot. ### Method ```typescript import { Bot, session, Conversation } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session()); const conv = new Conversation(); conv.define('order', async (ctx, c) => { await ctx.reply('What product do you want?'); const product = await c.waitForText(); await ctx.reply('How many?'); const qty = await c.waitForText({ validate: (ctx) => !isNaN(parseInt(ctx.message?.text || '')), validationError: 'Please enter a valid number.' }); await ctx.reply(`Order confirmed: ${parseInt(qty)}x ${product}`); }); bot.use(conv.middleware()); bot.command('order', ctx => conv.enter('order', ctx)); ``` ### Parameters * `YOUR_BOT_TOKEN` (string) - Your Telegram bot token. ### Request Body N/A for this setup example. ### Response N/A for this setup example. ### Notes - Ensure you have `vibegram` installed. - Replace `'YOUR_BOT_TOKEN'` with your actual bot token. ``` -------------------------------- ### Install Fastify Source: https://github.com/alfandi09/vibegram/blob/main/docs/adapters/express.md Install the Fastify framework to use with Vibegram. ```bash npm install fastify ``` -------------------------------- ### Install Express.js Source: https://github.com/alfandi09/vibegram/blob/main/docs/adapters/express.md Install the Express.js framework to use with Vibegram. ```bash npm install express ``` -------------------------------- ### Custom Storage Adapters (Redis Example) Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/session.md Demonstrates how to implement a custom session storage adapter using the `SessionStore` interface, with a Redis example. ```APIDOC ## Custom Storage Adapters ### Description Implement the `SessionStore` interface to integrate external databases or caching systems for session persistence. ### Method `bot.use(session({ store: new CustomAdapter() }))` ### Endpoint N/A (Middleware Configuration) ### Parameters #### Request Body - **`store`** (SessionStore) - An instance of a class implementing the `SessionStore` interface. ### Request Example ```typescript import { SessionStore } from 'vibegram'; class RedisAdapter implements SessionStore { async get(key: string) { const data = await redis.get(key); return data ? JSON.parse(data) : undefined; } async set(key: string, value: any) { await redis.set(key, JSON.stringify(value), 'EX', 86400); } async delete(key: string) { await redis.del(key); } } bot.use(session({ store: new RedisAdapter(), initial: () => ({ counter: 0 }) })); ``` ### Response N/A ``` -------------------------------- ### Quick Start: Basic Session Implementation Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/session.md This snippet demonstrates the basic setup for session management in Vibegram, initializing sessions with a default counter and handling messages to increment it. ```APIDOC ## Quick Start: Basic Session Implementation ### Description This example shows how to initialize and use basic sessions with a counter. ### Method `bot.use(session({...}))` ### Endpoint N/A (Middleware) ### Parameters #### Request Body N/A ### Request Example ```typescript import { Bot, session } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session({ initial: () => ({ counter: 0 }) })); bot.on('message', async (ctx) => { ctx.session.counter++; await ctx.reply(`Messages sent: ${ctx.session.counter}`); }); ``` ### Response #### Success Response (200) N/A (This is a middleware setup) #### Response Example N/A ``` -------------------------------- ### Initialize and Use Menu Builder Source: https://github.com/alfandi09/vibegram/blob/main/docs/ui/menu.md Set up a Vibegram bot with session middleware and create a basic menu with text buttons. This example demonstrates the core setup for using the Menu builder. ```typescript import { Bot, Menu, session } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session()); const menu = new Menu('main'); menu.text('📢 News', async (ctx) => { await ctx.answerCbQuery(); await ctx.reply('Latest news...'); }); menu.text('💰 Balance', async (ctx) => { await ctx.answerCbQuery(); await ctx.reply('Balance: $100.00'); }); bot.use(menu.middleware()); bot.command('menu', async (ctx) => { await ctx.reply('Main Menu:', { reply_markup: await menu.render(ctx) }); }); ``` -------------------------------- ### Initialize a basic bot Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/installation.md Example of creating a bot instance and launching it with a simple command handler. ```typescript import { Bot } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.command('ping', ctx => ctx.reply('pong')); bot.launch().then(() => console.log('Bot is running')); ``` -------------------------------- ### Install Hono Source: https://github.com/alfandi09/vibegram/blob/main/docs/adapters/express.md Install the Hono framework, compatible with Cloudflare Workers, Bun, Deno, and Node.js. ```bash npm install hono ``` -------------------------------- ### Quick Start: Vibegram Conversation Bot Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/conversations.md Set up a Vibegram bot with session management and define a simple 'order' conversation flow. This example demonstrates how to initiate a conversation and handle text inputs with validation. ```typescript import { Bot, session, Conversation } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session()); const conv = new Conversation(); conv.define('order', async (ctx, c) => { await ctx.reply('What product do you want?'); const product = await c.waitForText(); await ctx.reply('How many?'); const qty = await c.waitForText({ validate: (ctx) => !isNaN(parseInt(ctx.message?.text || '')), validationError: 'Please enter a valid number.' }); await ctx.reply(`Order confirmed: ${parseInt(qty)}x ${product}`); }); bot.use(conv.middleware()); bot.command('order', ctx => conv.enter('order', ctx)); ``` -------------------------------- ### Install Koa Source: https://github.com/alfandi09/vibegram/blob/main/docs/adapters/express.md Install Koa, its router, and koa-body middleware for handling webhook requests. ```bash npm install koa @koa/router koa-body ``` -------------------------------- ### Quick Start: Initialize and Use Sessions Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/session.md Set up session middleware with an initial state and increment a counter on each message. Requires the 'vibegram' package. ```typescript import { Bot, session } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session({ initial: () => ({ counter: 0 }) })); bot.on('message', async (ctx) => { ctx.session.counter++; await ctx.reply(`Messages sent: ${ctx.session.counter}`); }); ``` -------------------------------- ### Install VibeGram package Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/installation.md Use npm to add the VibeGram library to your project. ```bash npm install vibegram ``` -------------------------------- ### Implementing a Custom Cache Store Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/caching.md Provides an example of how to create a custom cache store by implementing the `CacheStore` interface, suitable for backends like Redis. ```APIDOC ## Implementing a Custom Cache Store ### Description Create a custom cache store by implementing the `CacheStore` interface for use with the `apiCache` middleware. This example shows a basic Redis implementation. ### Interface `CacheStore` requires `get`, `set`, `delete`, and `clear` methods. ### Request Example (Redis Cache Implementation) ```typescript import { CacheStore } from 'vibegram'; // Assume 'redis' is your Redis client instance class RedisCache implements CacheStore { async get(key: string) { const data = await redis.get(key); return data ? JSON.parse(data) : undefined; } async set(key: string, value: any, ttlMs: number) { await redis.set(key, JSON.stringify(value), 'PX', ttlMs); } async delete(key: string) { await redis.del(key); } async clear() { await redis.flushdb(); } } // Usage with apiCache: bot.use(apiCache({ ttl: 600, store: new RedisCache() })); ``` ``` -------------------------------- ### Managing Multiple Scenes Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/scenes.md An example illustrating how to define and manage multiple scenes within the same bot. ```APIDOC ## Managing Multiple Scenes ### Description This example demonstrates how to set up and use multiple distinct scenes, allowing for more complex conversation flows. ### Code Example ```typescript import { Bot, session, Scene, Stage } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session()); const faqScene = new Scene('faq'); faqScene.on('message', ctx => ctx.reply('FAQ: Ask a question or type "back".')); faqScene.hears('back', ctx => ctx.scene?.leave()); const contactScene = new Scene('contact'); contactScene.on('message', ctx => ctx.reply('Contact: Send your message or type "back".')); contactScene.hears('back', ctx => ctx.scene?.leave()); const stage = new Stage([faqScene, contactScene]); bot.use(stage.middleware()); bot.command('faq', ctx => ctx.scene?.enter('faq')); bot.command('contact', ctx => ctx.scene?.enter('contact')); ``` ### Important Note Ensure `bot.use(session())` is registered **before** `bot.use(stage.middleware())` as the Stage middleware relies on session data. ``` -------------------------------- ### Quick Start: Respond to Private Text and Admin Commands Source: https://github.com/alfandi09/vibegram/blob/main/docs/core/filters.md Demonstrates how to set up basic message handlers using `and`, `isPrivate`, and `hasText` for private chats, and `and`, `isGroup`, and `isAdmin` for admin commands in groups. ```typescript import { Bot, and, or, not, isPrivate, isGroup, isAdmin, hasText, hasPhoto } from 'vibegram'; // Only respond to text in private chats bot.on('message', and(isPrivate, hasText), async (ctx, next) => { console.log('Private text message'); await next(); }); // Admin-only command in groups bot.command('ban', and(isGroup, isAdmin()), async (ctx) => { await ctx.reply('Admin action executed.'); }); ``` -------------------------------- ### Custom Cache Store Implementation Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/caching.md Implement the CacheStore interface to use custom storage backends like Redis. The example shows how to define get, set, delete, and clear methods for Redis integration. ```typescript import { CacheStore } from 'vibegram'; class RedisCache implements CacheStore { async get(key: string) { const data = await redis.get(key); return data ? JSON.parse(data) : undefined; } async set(key: string, value: any, ttlMs: number) { await redis.set(key, JSON.stringify(value), 'PX', ttlMs); } async delete(key: string) { await redis.del(key); } async clear() { await redis.flushdb(); } } bot.use(apiCache({ ttl: 600, store: new RedisCache() })); ``` -------------------------------- ### Quick Start: Vibegram Registration Wizard Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/wizards.md Sets up a basic registration wizard with three steps: collecting name, email, and confirming details. Requires Bot and session middleware. ```typescript import { Bot, session, Wizard } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session()); const registrationWizard = new Wizard('register', [ async (ctx) => { await ctx.reply('Step 1: What is your name?'); ctx.wizard?.next(); }, async (ctx) => { ctx.wizard!.state.name = ctx.message?.text; await ctx.reply(`Step 2: Hello ${ctx.wizard!.state.name}! What is your email?`); ctx.wizard?.next(); }, async (ctx) => { ctx.wizard!.state.email = ctx.message?.text; await ctx.reply(`Done!\nName: ${ctx.wizard!.state.name}\nEmail: ${ctx.wizard!.state.email}`); ctx.wizard?.leave(); } ]); bot.use(registrationWizard.middleware()); bot.command('register', ctx => registrationWizard.enter(ctx)); ``` -------------------------------- ### Wizard State Management: Order Wizard Example Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/wizards.md Demonstrates using `ctx.wizard.state` to store and retrieve data across multiple wizard steps for an order process. Includes collecting product, quantity, and address. ```typescript const orderWizard = new Wizard('order', [ async (ctx) => { await ctx.reply('What product would you like to order?'); ctx.wizard?.next(); }, async (ctx) => { ctx.wizard!.state.product = ctx.message?.text; await ctx.reply('How many units?'); ctx.wizard?.next(); }, async (ctx) => { ctx.wizard!.state.quantity = parseInt(ctx.message?.text || '1'); await ctx.reply('What is your delivery address?'); ctx.wizard?.next(); }, async (ctx) => { const { product, quantity } = ctx.wizard!.state; const address = ctx.message?.text; await ctx.reply(`Order confirmed!\nProduct: ${product}\nQuantity: ${quantity}\nAddress: ${address}`); ctx.wizard?.leave(); } ]); ``` -------------------------------- ### Quick Start: Using apiCache Middleware Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/caching.md Demonstrates how to integrate the apiCache middleware into your Vibegram bot to cache API responses for a specified duration. ```APIDOC ## Quick Start: Using apiCache Middleware ### Description Integrate the `apiCache` middleware to cache responses from read-only Telegram API methods. This example caches API responses for 5 minutes (300 seconds). ### Method `bot.use()` ### Endpoint N/A (Middleware) ### Parameters #### Options - **ttl** (`number`) - Optional - Time-to-live in seconds. Defaults to 300. ### Request Example ```typescript import { Bot, apiCache } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); // Cache API responses for 5 minutes bot.use(apiCache({ ttl: 300 })); bot.command('info', async (ctx) => { const chat = await ctx.getChat(); // hits API const again = await ctx.getChat(); // returns cached await ctx.reply(`Chat: ${chat.title}`); }); ``` ### Response N/A (Middleware modifies bot behavior) ``` -------------------------------- ### Create a Plugin Preset Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/plugins.md Combine multiple plugins into a single, installable preset. This is useful for organizing related functionalities or creating standard configurations. ```typescript import { Preset } from 'vibegram'; const productionPreset = new Preset('production', [ new LoggerPlugin(), new RateLimitPlugin({ limit: 30 }), new SessionPlugin(), new CachePlugin({ ttl: 300 }) ]); bot.plugin(productionPreset); ``` -------------------------------- ### Quick Start: Initialize and Use Logger Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/logger.md Import the logger middleware and use it with your VibeGram bot instance. Ensure it's registered early in the middleware chain. ```typescript import { Bot, logger } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(logger()); ``` -------------------------------- ### Conversation Branching Example Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/conversations.md An example showcasing how to implement branching logic within a Conversation using standard control flow statements. ```APIDOC ## Branching Example ### Description This example demonstrates how to use `if/else` statements within an async Conversation function to create branching dialogue paths based on user input. ### Method ```typescript conv.define('support', async (ctx, c) => { await ctx.reply('What do you need help with?\n1. Billing\n2. Technical'); const choice = await c.waitForText(); if (choice === '1') { await ctx.reply('Describe your billing issue:'); const issue = await c.waitForText(); await ctx.reply(`Billing ticket created: "${issue}"`); } else { await ctx.reply('Describe the technical problem:'); const issue = await c.waitForText(); await ctx.reply('Attach a screenshot if possible:'); try { const photo = await c.waitForPhoto({ timeout: 60000 }); await ctx.reply('Screenshot received. Ticket created.'); } catch { await ctx.reply('No screenshot provided. Ticket created without attachment.'); } } }); ``` ### Parameters - `ctx` (Context) - The Telegram bot context. - `c` (ConversationContext) - The conversation context object. ### Notes - This example includes nested `waitForText` and `waitForPhoto` calls. - It also demonstrates error handling for `waitForPhoto`. ``` -------------------------------- ### Create a Class-Based Plugin Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/plugins.md Define a plugin by implementing the BotPlugin interface. Use the install method to register commands or middleware with the bot composer. Ensure the plugin has a unique name. ```typescript import { Bot, BotPlugin } from 'vibegram'; // Class-based plugin class WelcomePlugin implements BotPlugin { name = 'welcome'; install(bot) { bot.command('welcome', ctx => ctx.reply('Welcome!')); } } const bot = new Bot('YOUR_BOT_TOKEN'); bot.plugin(new WelcomePlugin()); ``` -------------------------------- ### Direct API Calls Source: https://github.com/alfandi09/vibegram/blob/main/docs/api/bot-methods.md Examples of making direct calls to the Telegram API using `bot.callApi` for methods not covered by specific shortcuts. ```APIDOC ## Direct API Calls ### `bot.callApi(method, params?)` #### Description This method allows you to call any Telegram Bot API method directly. It's useful for methods that don't have a dedicated shortcut in the library or for advanced usage. ### Request Example: Sending a Message ```typescript const result = await bot.callApi('sendMessage', { chat_id: 123456, text: 'Hello from callApi!' }); ``` ### Request Example: Setting a Webhook ```typescript await bot.callApi('setWebhook', { url: 'https://example.com/webhook', secret_token: 'my-secret' }); ``` #### Parameters for `sendMessage` - **method** (string) - Required - The API method name, e.g., 'sendMessage'. - **params** (object) - Optional - An object containing the parameters for the API method. - **chat_id** (integer) - Required - Unique identifier for the target chat. - **text** (string) - Required - Text of the message to be sent. #### Parameters for `setWebhook` - **method** (string) - Required - The API method name, e.g., 'setWebhook'. - **params** (object) - Optional - An object containing the parameters for the API method. - **url** (string) - Required - HTTPS URL to send updates to. Use an empty string to remove the webhook. - **secret_token** (string) - Optional - A secret token to be sent in the X-Telegram-Bot-Api-Secret-Token header when the webhook is called. ``` -------------------------------- ### Set up Express Server for Webhooks Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/instance.md Implement a webhook server using Express.js for production deployments. This example includes setting up JSON parsing and registering the bot's webhook callback. A secret token can be optionally provided to secure webhook endpoints. ```typescript import express from 'express'; const app = express(); app.use(express.json()); // Optional: secret token prevents unauthorized requests app.post('/webhook', bot.webhookCallback('my-secret-token')); app.listen(3000, () => { console.log('Webhook server running on port 3000'); }); ``` -------------------------------- ### Create a Functional Plugin Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/plugins.md Use the createPlugin helper for simpler plugins. This factory function takes a name and a callback that receives the bot composer and options. Install the plugin with specific configuration. ```typescript import { createPlugin } from 'vibegram'; const greetingPlugin = createPlugin('greeting', (bot, opts: { message: string }) => { bot.command('greet', ctx => ctx.reply(opts.message)); }); // Install with options bot.plugin(greetingPlugin({ message: 'Hello from plugin!' })); ``` -------------------------------- ### Recommended Middleware Registration Order Source: https://github.com/alfandi09/vibegram/blob/main/docs/core/middleware.md Register built-in middleware in the recommended order for optimal functionality, starting with observability and protection, then state management, routing, and finally business logic. ```typescript bot.use(logger()); // 1. Observability bot.use(rateLimit()); // 2. Protection bot.use(session()); // 3. State bot.use(stage.middleware()); // 4. Scene routing // Your handlers go here // 5. Business logic ``` -------------------------------- ### Setup Express Server with VibeGram Webhook Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/webhook.md Configure an Express.js server to handle VibeGram webhooks, including JSON parsing and the webhook callback with secret token validation. Ensure your bot token and secret are correctly set. ```typescript import express from 'express'; import { Bot } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); const WEBHOOK_SECRET = 'my-secure-random-secret'; const app = express(); app.use(express.json()); // The callback validates X-Telegram-Bot-Api-Secret-Token header app.post('/webhook', bot.webhookCallback(WEBHOOK_SECRET)); app.listen(3000); ``` -------------------------------- ### Quick Start: Using apiCache Middleware Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/caching.md Integrate the apiCache middleware into your bot to cache API responses. Configure the time-to-live (ttl) in seconds. Subsequent calls for the same read-only method within the TTL will return cached data. ```typescript import { Bot, apiCache } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); // Cache API responses for 5 minutes bot.use(apiCache({ ttl: 300 })); bot.command('info', async (ctx) => { const chat = await ctx.getChat(); // hits API const again = await ctx.getChat(); // returns cached await ctx.reply(`Chat: ${chat.title}`); }); ``` -------------------------------- ### Launch and Shutdown Vibegram Bot Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/instance.md Start the bot's polling process using `bot.launch()` and handle graceful shutdown with `bot.stop()`. It's recommended to handle process signals like SIGINT and SIGTERM for robust shutdown procedures. ```typescript // Start polling bot.launch().then(() => console.log('Bot running')); // Graceful shutdown bot.stop('Maintenance'); // Handle process signals process.once('SIGINT', () => bot.stop()); process.once('SIGTERM', () => bot.stop()); ``` -------------------------------- ### Build and Serve Documentation Source: https://github.com/alfandi09/vibegram/blob/main/README.md Commands to serve local documentation or generate API references. ```bash cd docs && npx vitepress dev ``` ```bash npm run docs:api ``` -------------------------------- ### Build Project Source: https://github.com/alfandi09/vibegram/blob/main/CONTRIBUTING.md Command to verify that the project builds correctly. ```bash npm run build ``` -------------------------------- ### Get File Download URL and Download File Source: https://github.com/alfandi09/vibegram/blob/main/docs/id/api/context.md Use `getFileLink` to get the download URL for a file. Use `downloadFile` to download the file content into a buffer or save it directly to a specified path on disk. ```typescript // Dapatkan URL unduhan file const url = await ctx.getFileLink(fileId); // Unduh langsung ke buffer atau file const buffer = await ctx.downloadFile(fileId); await ctx.downloadFile(fileId, './gambar.jpg'); // simpan ke disk ``` -------------------------------- ### Initialize a Basic Bot Source: https://github.com/alfandi09/vibegram/blob/main/README.md Create a bot instance and define command and message handlers. ```typescript import { Bot } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.command('start', async (ctx) => { const name = ctx.from?.first_name || 'there'; await ctx.reply(`Hello ${name}! Welcome to VibeGram.`); }); bot.hears(/hello|hi/i, async (ctx) => { await ctx.reply('Hey! How can I help you?'); }); bot.launch().then(() => console.log('Bot is running 🚀')); ``` -------------------------------- ### Get Chat Information Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/administration.md Retrieve details about the current chat, including its title and member count. ```typescript // Get chat details bot.command('info', async (ctx) => { const chat = await ctx.getChat(); const count = await ctx.getChatMembersCount(); await ctx.reply(`Chat: ${chat.title}\nMembers: ${count}`); }); ``` -------------------------------- ### Initialize and Use a Scene in Vibegram Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/scenes.md Demonstrates setting up a basic scene, registering it with a Stage, and triggering entry via a command. ```typescript import { Bot, session, Scene, Stage } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); bot.use(session()); // Define a scene const settingsScene = new Scene('settings'); settingsScene.command('theme', ctx => ctx.reply('Choose: light or dark?')); settingsScene.hears('back', ctx => { ctx.reply('Exiting settings.'); ctx.scene?.leave(); }); settingsScene.on('message', ctx => ctx.reply('You are in settings. Type "back" to exit.')); // Register and activate const stage = new Stage([settingsScene]); bot.use(stage.middleware()); // Enter the scene bot.command('settings', ctx => ctx.scene?.enter('settings')); ``` -------------------------------- ### Conversation Validation Example Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/conversations.md Illustrates how to implement input validation within a Conversation to ensure user input meets specific criteria. ```APIDOC ## Validation Example ### Description This example shows how to use the `validate` and `validationError` options within `waitForText` to ensure the user provides a valid email address. ### Method ```typescript const email = await c.waitForText({ validate: (ctx) => /\S+@\S+\.\S+/.test(ctx.message?.text || ''), validationError: 'Please enter a valid email address.' }); ``` ### Parameters - `c` (ConversationContext) - The conversation context object. - `validate` (function) - A function that receives the context (`ctx`) and should return `true` if the input is valid. - `validationError` (string) - The error message to send to the user if `validate` returns `false`. ### Response - `email` (string) - The validated email address entered by the user. ``` -------------------------------- ### Bot Initialization and Configuration Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/instance.md Methods for creating a bot instance and configuring polling behavior. ```APIDOC ## Bot Initialization ### Description Initializes a new bot instance using a Telegram bot token. ### Request Example ```typescript import { Bot } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); ``` ## Polling Configuration ### Description Configures the polling behavior for receiving updates from Telegram. ### Parameters - **interval** (number) - Optional - ms between polls (default: 300) - **limit** (number) - Optional - max updates per poll (default: 100) - **timeout** (number) - Optional - long-polling timeout in seconds (default: 30) - **allowed_updates** (array) - Optional - filter update types ### Request Example ```typescript const bot = new Bot('YOUR_BOT_TOKEN', { polling: { interval: 300, limit: 100, timeout: 30, allowed_updates: ['message', 'callback_query', 'chat_member'] } }); ``` ``` -------------------------------- ### Hono Webhook Handler Source: https://github.com/alfandi09/vibegram/blob/main/docs/adapters/express.md Implement a Hono handler for Vibegram webhooks. This example is suitable for serverless environments like Cloudflare Workers. ```typescript import { Hono } from 'hono'; import { Bot, createHonoHandler } from 'vibegram'; const bot = new Bot(process.env.BOT_TOKEN!); const app = new Hono(); app.post('/webhook', createHonoHandler(bot, { secretToken: process.env.WEBHOOK_SECRET })); export default app; ``` -------------------------------- ### Run the bot Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/installation.md Execute the bot entry point using ts-node. ```bash npx ts-node src/index.ts ``` -------------------------------- ### Reply with Draft Message Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/draft.md Use `ctx.replyWithDraft` to pre-fill the user's input box with specified text. This is useful for guiding user input. ```typescript bot.command('draft', async (ctx) => { await ctx.replyWithDraft('Pre-filled text appears in the input box...'); }); ``` -------------------------------- ### Plugin Interface Definition Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/plugins.md The BotPlugin interface defines the contract for all plugins. It requires a name property and an install method for integrating the plugin's logic. ```typescript interface BotPlugin { name: string; install(composer: Composer, options?: any): void; } ``` -------------------------------- ### Filter Media from Non-Bots Source: https://github.com/alfandi09/vibegram/blob/main/docs/core/filters.md This example filters messages that contain photos or videos, excluding messages sent by bots. It uses `not(isBot)` combined with `or(hasPhoto, hasVideo)`. ```typescript // Photos or videos from non-bots bot.on('message', and(not(isBot), or(hasPhoto, hasVideo)), ctx => { ctx.reply('Media received from a real user.'); }); ``` -------------------------------- ### Handle Commands with Arguments Source: https://context7.com/alfandi09/vibegram/llms.txt Demonstrates registering command handlers that parse arguments into `ctx.command.args`. Supports single commands, multiple commands, and typed argument handling. ```typescript import { Bot } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); // Single command with argument parsing bot.command('echo', async (ctx) => { // /echo hello world -> ctx.command.args = ['hello', 'world'] const text = ctx.command?.args.join(' ') || 'Nothing to echo'; await ctx.reply(text); }); // Multiple commands with same handler bot.command(['help', 'info', 'about'], async (ctx) => { await ctx.reply(`You used /${ctx.command?.name}. This bot demonstrates VibeGram features.`); }); // Command with typed argument handling bot.command('remind', async (ctx) => { const [minutes, ...messageParts] = ctx.command?.args || []; const delay = parseInt(minutes) || 5; const message = messageParts.join(' ') || 'Reminder!'; setTimeout(() => ctx.reply(`Reminder: ${message}`), delay * 60000); await ctx.reply(`I'll remind you in ${delay} minutes.`); }); bot.launch(); ``` -------------------------------- ### Instance Methods Source: https://github.com/alfandi09/vibegram/blob/main/docs/api/bot-methods.md Methods that can be called directly on the Bot instance without requiring a Context object. ```APIDOC ## Instance Methods ### `bot.launch()` #### Description Starts the bot's long-polling mechanism. ### `bot.stop(reason?)` #### Description Stops the bot's polling gracefully. An optional reason can be provided. ### `bot.handleUpdate(update)` #### Description Processes a raw update object manually. Useful for custom update handling. ### `bot.webhookCallback(secretToken?)` #### Description Creates an Express-compatible webhook handler. An optional secret token can be provided for security. ### `bot.callApi(method, params?)` #### Description Calls any Telegram API method directly. Requires the method name and optional parameters. ### `bot.validateWebAppData(initData, opts?)` #### Description Validates the Mini App initData. Accepts initData and optional options. ### `bot.getMe()` #### Description Retrieves information about the bot itself. ### `bot.setMyCommands(commands, extra?)` #### Description Sets the bot's command menu. Requires a list of commands and optional extra parameters. ### `bot.getMyCommands(extra?)` #### Description Retrieves the bot's current command list. Optional extra parameters can be provided. ### `bot.deleteMyCommands(extra?)` #### Description Deletes the bot's command menu. Optional extra parameters can be provided. ``` -------------------------------- ### Vibegram Conversation: Handling Timeouts Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/conversations.md Configure timeouts for waiting for user input in a Vibegram conversation. This example shows how to catch a `ConversationTimeout` error and provide a user-friendly message. ```typescript try { const answer = await c.waitForText({ timeout: 30000 }); // 30 seconds await ctx.reply(`You said: ${answer}`); } catch (err) { if (err instanceof ConversationTimeout) { await ctx.reply('Time is up! Conversation cancelled.'); } } ``` -------------------------------- ### Get Bot Information Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/instance.md Retrieve information about the bot, such as its ID, username, and name, using the `bot.getMe()` method. The returned object contains details about the bot's identity. ```typescript // Get bot information const me = await bot.getMe(); console.log(`Running as @${me.username}`); ``` -------------------------------- ### Webhook Integration Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/instance.md Methods for setting up webhooks for production deployments. ```APIDOC ## bot.webhookCallback(secretToken) ### Description Creates an express middleware to handle incoming webhook requests. ### Parameters - **secretToken** (string) - Optional - Secret token to prevent unauthorized requests. ## bot.callApi('setWebhook', params) ### Description Registers the webhook URL with Telegram. ### Parameters - **url** (string) - Required - The public URL for the webhook. - **secret_token** (string) - Optional - Secret token for verification. ``` -------------------------------- ### Composing Custom Middleware with Composer Source: https://github.com/alfandi09/vibegram/blob/main/docs/core/middleware.md Create and use a custom middleware composer to group related logic, such as access control. This example uses `Composer` to create an admin-only guard. ```typescript import { Composer } from 'vibegram'; const adminGuard = new Composer(); adminGuard.use(async (ctx, next) => { const adminIds = [123456, 789012]; if (adminIds.includes(ctx.from?.id || 0)) { return next(); } await ctx.reply('Access denied.'); }); adminGuard.command('secret', ctx => ctx.reply('Admin-only content.')); bot.use(adminGuard.middleware()); ``` -------------------------------- ### Initialize and Launch Telegram Bot Source: https://context7.com/alfandi09/vibegram/llms.txt Initializes the VibeGram Bot with a token and launch options for polling mode. Includes a basic command handler for '/start'. ```typescript import { Bot } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN', { polling: { interval: 300, limit: 100, timeout: 30, allowed_updates: ['message', 'callback_query'] } }); // Register command handlers bot.command('start', async (ctx) => { const name = ctx.from?.first_name || 'there'; await ctx.reply(`Hello ${name}! Welcome to my bot.`); }); // Launch in polling mode with startup callback bot.launch({ onStart: (botInfo) => console.log(`@${botInfo.username} is running!`) }); // Graceful shutdown handling is automatic (SIGINT/SIGTERM) ``` -------------------------------- ### Bot Lifecycle Management Source: https://github.com/alfandi09/vibegram/blob/main/docs/basics/instance.md Methods for launching the bot and handling graceful shutdowns. ```APIDOC ## bot.launch() ### Description Starts the polling process for the bot. ## bot.stop(reason) ### Description Gracefully shuts down the bot instance. ### Parameters - **reason** (string) - Optional - The reason for stopping the bot. ``` -------------------------------- ### Native Node.js HTTP Webhook Handler Source: https://github.com/alfandi09/vibegram/blob/main/docs/adapters/express.md Handle Vibegram webhook updates using Node.js's built-in `http` module without any external frameworks. This is a minimal setup. ```typescript import http from 'http'; import { Bot, createNativeHandler } from 'vibegram'; const bot = new Bot(process.env.BOT_TOKEN!); http.createServer( createNativeHandler(bot, { secretToken: process.env.WEBHOOK_SECRET }) ).listen(3000, () => console.log('Listening on :3000')); ``` -------------------------------- ### Initialize Pagination in VibeGram Source: https://github.com/alfandi09/vibegram/blob/main/docs/ui/pagination.md Create a paginated inline keyboard from an array of items using the Markup.pagination method. ```typescript import { Markup, PaginationItem } from 'vibegram'; const products: PaginationItem[] = Array.from({ length: 50 }).map((_, i) => ({ text: `Product #${i + 1}`, callback_data: `buy_${i + 1}` })); const keyboard = Markup.pagination(products, { currentPage: 1, itemsPerPage: 5, actionNext: 'page_next', actionPrev: 'page_prev', pageIndicatorPattern: 'Page {current} of {total}' }); await ctx.reply('Browse products:', { reply_markup: keyboard }); ``` -------------------------------- ### Setup Express Server Without Secret Token Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/webhook.md Configure an Express.js server to handle VibeGram webhooks without secret token validation. This is less secure and should be avoided in production environments. ```typescript app.post('/webhook', bot.webhookCallback()); ``` -------------------------------- ### Initialize I18n Middleware Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/i18n.md Configure the bot with default locales and load translation dictionaries for supported languages. ```typescript import { Bot, I18n } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); const i18n = new I18n('en'); // default locale // Load locale dictionaries i18n.loadLocale('en', { welcome: 'Welcome {name}!', help: 'Available commands: /start, /help', bye: 'Goodbye!' }); i18n.loadLocale('id', { welcome: 'Selamat datang {name}!', help: 'Perintah tersedia: /start, /help', bye: 'Sampai jumpa!' }); i18n.loadLocale('es', { welcome: '¡Bienvenido {name}!', help: 'Comandos disponibles: /start, /help', bye: '¡Adiós!' }); bot.use(i18n.middleware()); ``` -------------------------------- ### Initialize Rate Limiter with Defaults Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/rate-limit.md Apply the default rate limiting middleware to a bot instance. ```typescript import { Bot, rateLimit } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); // Use default limits (1 msg/sec private, 20 msg/min group) bot.use(rateLimit()); ``` -------------------------------- ### MemoryCache Configuration Source: https://github.com/alfandi09/vibegram/blob/main/docs/security/caching.md Details how to configure the built-in `MemoryCache` with a maximum entry limit and LRU eviction strategy. ```APIDOC ## Memory Management with MemoryCache ### Description The built-in `MemoryCache` provides a default caching mechanism with a configurable maximum number of entries and Least Recently Used (LRU) eviction strategy. ### Options - **maxEntries** (`number`) - Optional - The maximum number of entries the cache can hold. Defaults to 10,000. ### Request Example (Custom Max Entries) ```typescript import { Bot, apiCache, MemoryCache } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); // Create a MemoryCache with a maximum of 5,000 entries const store = new MemoryCache(5000); // Use the custom MemoryCache with apiCache bot.use(apiCache({ store })); ``` ``` -------------------------------- ### Build Inline Keyboards with Vibegram Source: https://context7.com/alfandi09/vibegram/llms.txt Construct inline keyboards with various button types like callback, URL, web app, and switch inline query. Ensure the bot token is correctly set. ```typescript import { Bot, Markup } from 'vibegram'; const bot = new Bot('YOUR_BOT_TOKEN'); // Inline keyboard with various button types bot.command('menu', async (ctx) => { await ctx.reply('Main Menu:', { reply_markup: Markup.inlineKeyboard([ [Markup.button.callback('Settings', 'settings')], [Markup.button.url('Documentation', 'https://docs.example.com')], [Markup.button.webApp('Open App', 'https://app.example.com')], [Markup.button.switchInlineQuery('Share', 'hello')] ]) }); }); // Grid layout for buttons bot.command('days', async (ctx) => { await ctx.reply('Select a day:', { reply_markup: Markup.grid([ Markup.button.callback('Mon', 'day_1'), Markup.button.callback('Tue', 'day_2'), Markup.button.callback('Wed', 'day_3'), Markup.button.callback('Thu', 'day_4'), Markup.button.callback('Fri', 'day_5'), Markup.button.callback('Sat', 'day_6'), Markup.button.callback('Sun', 'day_7'), ], 4) // 4 buttons per row }); }); // Automatic pagination const products = Array.from({ length: 50 }, (_, i) => ({ text: `Product ${i + 1}`, callback_data: `product_${i + 1}` })); let currentPage = 1; bot.command('products', async (ctx) => { await ctx.reply('Browse products:', { reply_markup: Markup.pagination(products, { currentPage: 1, itemsPerPage: 5, columns: 2, actionNext: 'page_next', actionPrev: 'page_prev', pageIndicatorPattern: 'Page {current} of {total}' }) }); }); bot.action(/page_(next|prev)/, async (ctx) => { currentPage += ctx.match![1] === 'next' ? 1 : -1; await ctx.editMessageReplyMarkup( Markup.pagination(products, { currentPage, itemsPerPage: 5, columns: 2, actionNext: 'page_next', actionPrev: 'page_prev' }) ); await ctx.answerCbQuery(`Page ${currentPage}`); }); // Reply keyboard with special buttons bot.command('contact', async (ctx) => { await ctx.reply('Please share your info:', { reply_markup: Markup.keyboard([ [Markup.replyButton.requestContact('Share Phone')], [Markup.replyButton.requestLocation('Share Location')], [Markup.replyButton.text('Cancel')] ], { resize_keyboard: true, one_time_keyboard: true }) }); }); bot.launch(); ``` -------------------------------- ### Configure Progress and Error Handling Source: https://github.com/alfandi09/vibegram/blob/main/docs/advanced/queue.md Initialize BotQueue with callbacks for onProgress and onError to monitor broadcast status and handle individual failures. ```typescript const queue = new BotQueue(bot.client, { concurrency: 30, delayMs: 1000, onProgress: (completed, total) => { console.log(`Progress: ${completed}/${total} (${Math.round(completed/total*100)}%)`); }, onError: (err, chatId) => { console.error(`Failed for ${chatId}: ${err.message}`); } }); ``` -------------------------------- ### Session Options Source: https://github.com/alfandi09/vibegram/blob/main/docs/state/session.md Details on the available options for configuring the session middleware, including storage, key generation, and initial state. ```APIDOC ## Session Options ### Description Configuration options for the `session` middleware. ### Method `session(options)` ### Endpoint N/A (Middleware Configuration) ### Parameters #### Options - **`store`** (SessionStore) - Custom storage adapter for sessions. - **`getSessionKey`** ((ctx) => string) - Function to generate a unique key for each session. Defaults to `chatId:userId`. - **`initial`** (() => S) - Factory function that returns the initial state for a new session. ### Request Example ```typescript // Example using custom options bot.use(session({ getSessionKey: (ctx) => `${ctx.chat.id}:${ctx.from.id}`, initial: () => ({ data: null }) })); ``` ### Response N/A ```