### Install Grammy Files Plugin Source: https://context7.com/grammyjs/files/llms.txt Applies file handling capabilities to your bot's API using the `hydrateFiles` function. This function transforms `getFile` responses to include download and URL methods. It requires the bot token and optionally accepts configuration options. ```typescript import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles } from "@grammyjs/files"; // Apply the transformative API flavor to your context type MyContext = FileFlavor; // Create bot with the enhanced context type const bot = new Bot("YOUR_BOT_TOKEN"); // Install the files plugin bot.api.config.use(hydrateFiles(bot.token)); // Now all getFile calls return enhanced file objects bot.on("message:photo", async (ctx) => { const file = await ctx.getFile(); console.log("File ready for download"); }); bot.start(); ``` -------------------------------- ### Utilize FileFlavor Type for Type-Safe File Operations in Grammy Source: https://context7.com/grammyjs/files/llms.txt This example shows how to apply the `FileFlavor` type to your context in grammY to gain full TypeScript type safety for file-related methods. It demonstrates basic usage and an advanced scenario with other context plugins like `@grammyjs/hydrate`. The code highlights how `getFile()`, `getUrl()`, `download()`, and async iteration are properly typed. ```typescript import { Bot, type Context, type Api } from "grammy"; import { type FileFlavor, type FileApiFlavor, hydrateFiles } from "@grammyjs/files"; // Basic usage with context flavor type MyContext = FileFlavor; const bot = new Bot("YOUR_BOT_TOKEN"); bot.api.config.use(hydrateFiles(bot.token)); // Advanced: Apply to custom context with other plugins import { type HydrateFlavor } from "@grammyjs/hydrate"; type CustomContext = FileFlavor>; const advancedBot = new Bot("YOUR_BOT_TOKEN"); advancedBot.api.config.use(hydrateFiles(advancedBot.token)); // TypeScript now knows about download(), getUrl(), and async iteration advancedBot.on("message:voice", async (ctx) => { const file = await ctx.getFile(); // These methods are properly typed const url: string = file.getUrl(); const path: string = await file.download(); // Async iteration is also typed for await (const chunk of file) { // chunk is Uint8Array console.log(chunk.length); } }); advancedBot.start(); ``` -------------------------------- ### Get File URL using file.getUrl() Source: https://context7.com/grammyjs/files/llms.txt Retrieves the downloadable URL for a file. For standard Telegram API servers, this returns an HTTPS URL. For local Bot API servers, it returns the local file path. This URL can be used with external services or custom download logic. ```typescript import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles } from "@grammyjs/files"; type MyContext = FileFlavor; const bot = new Bot("YOUR_BOT_TOKEN"); bot.api.config.use(hydrateFiles(bot.token)); bot.on("message:document", async (ctx) => { const file = await ctx.getFile(); // Get the download URL const url = file.getUrl(); console.log("Download URL:", url); // Output: https://api.telegram.org/file/bot/documents/file_123.pdf // Use the URL with external services or custom download logic await ctx.reply(`File available at: ${url}`); }); bot.start(); ``` -------------------------------- ### Download Files with grammy.js Source: https://github.com/grammyjs/files/blob/main/README.md This snippet demonstrates how to set up a grammy.js bot to download video and animation files from Telegram. It utilizes the `hydrateFiles` plugin to enable file download functionality and shows how to obtain a file object and download it to a temporary location. ```typescript import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles } from "@grammyjs/files"; // Transformative API flavor type MyContext = FileFlavor; // Create bot const bot = new Bot(""); // Install plugin bot.api.config.use(hydrateFiles(bot.token)); // Download videos and GIFs to temporary files bot.on([":video", ":animation"], async (ctx) => { // Prepare file for download const file = await ctx.getFile(); // Download file to temporary location on your disk const path = await file.download(); // Print file path console.log("File saved at", path); }); ``` -------------------------------- ### Configure Grammy Files Plugin Options Source: https://context7.com/grammyjs/files/llms.txt Customizes file download behavior using `FilesPluginOptions`. This is useful for local Bot API servers or test environments. Options include setting a custom `apiRoot`, `environment`, and defining custom builders for file URLs and local file paths. ```typescript import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles, type FilesPluginOptions } from "@grammyjs/files"; type MyContext = FileFlavor; const bot = new Bot("YOUR_BOT_TOKEN"); // Configure for a local Bot API server const options: FilesPluginOptions = { // Custom API root for local Bot API server apiRoot: "http://localhost:8081", // Use test environment (optional) environment: "prod", // Custom URL builder for file downloads buildFileUrl: (root, token, path, env) => { const prefix = env === "test" ? "test/" : ""; return `${root}/file/bot${token}/${prefix}${path}`; }, // Custom path builder for local file system access buildFilePath: (root, token, path, env) => { return `/var/telegram-bot-api/files/${path}`; }, }; bot.api.config.use(hydrateFiles(bot.token, options)); bot.start(); ``` -------------------------------- ### Download File using file.download() Source: https://context7.com/grammyjs/files/llms.txt Downloads a file from Telegram servers to the local file system. Without arguments, it saves to a temporary file. With a path argument, it saves to the specified location. The method returns the absolute path of the downloaded file. ```typescript import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles } from "@grammyjs/files"; type MyContext = FileFlavor; const bot = new Bot("YOUR_BOT_TOKEN"); bot.api.config.use(hydrateFiles(bot.token)); // Download to a temporary file bot.on([":video", ":animation"], async (ctx) => { const file = await ctx.getFile(); // Download to auto-generated temporary location const tempPath = await file.download(); console.log("File saved to temporary location:", tempPath); // Or download to a specific path const customPath = await file.download("/path/to/videos/my_video.mp4"); console.log("File saved to:", customPath); }); // Download photos with custom naming bot.on("message:photo", async (ctx) => { const file = await ctx.getFile(); const timestamp = Date.now(); const path = await file.download(`./downloads/photo_${timestamp}.jpg`); console.log("Photo downloaded:", path); }); bot.start(); ``` -------------------------------- ### Stream File Contents Asynchronously with Grammy Files Source: https://context7.com/grammyjs/files/llms.txt This snippet demonstrates how to stream file contents chunk by chunk using async iteration provided by the grammyjs/files plugin. It avoids loading the entire file into memory, which is crucial for large files. The code logs the progress of reading chunks and the total file size. ```typescript import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles } from "@grammyjs/files"; import { createWriteStream } from "fs"; type MyContext = FileFlavor; const bot = new Bot("YOUR_BOT_TOKEN"); bot.api.config.use(hydrateFiles(bot.token)); // Stream file contents and track progress bot.on([":video", ":animation"], async (ctx) => { const file = await ctx.getFile(); let totalBytes = 0; // Iterate through file chunks for await (const chunk of file) { totalBytes += chunk.length; console.log(`Read ${chunk.length} bytes (total: ${totalBytes})`); } console.log(`File streaming complete. Total size: ${totalBytes} bytes`); }); // Stream to a custom destination with progress tracking bot.on("message:document", async (ctx) => { const file = await ctx.getFile(); const chunks: Uint8Array[] = []; for await (const chunk of file) { chunks.push(chunk); } // Combine chunks into a single buffer const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0); const buffer = new Uint8Array(totalLength); let offset = 0; for (const chunk of chunks) { buffer.set(chunk, offset); offset += chunk.length; } console.log(`Document loaded: ${buffer.length} bytes`); }); bot.start(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.