### Error handling on calls made after installation Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/hydrateFiles.md Error handling for calls made after installation. The download method rejects with "File path is not available for file ''" if the file has no file_path (e.g., is too large to be downloaded). The example catches the error and logs it. ```ts bot.api.config.use(hydrateFiles(bot.token)); bot.on(":document", async (ctx) => { const file = await ctx.getFile(); try { // Rejects with "File path is not available for file ''" // if the file has no file_path (e.g. is too large to be downloaded) const path = await file.download("/tmp/" + ctx.message.document.file_name); console.log("Saved:", path); } catch (err) { console.error(err); } }); ``` -------------------------------- ### Basic installation of hydrateFiles Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/hydrateFiles.md Basic installation of the hydrateFiles plugin. It installs the plugin on the API layer and uses the FileFlavor type to extend the context. The bot handles video and animation messages, downloads the file, and logs the path. ```ts import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles } from "@grammyjs/files"; type MyContext = FileFlavor; const bot = new Bot("123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"); // Install the plugin on the API layer bot.api.config.use(hydrateFiles(bot.token)); bot.on([":video", ":animation"], async (ctx) => { const file = await ctx.getFile(); const path = await file.download(); console.log("File saved at", path); }); bot.start(); ``` -------------------------------- ### FileX.getUrl() usage example Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Example usage of FileX.getUrl() to obtain the file's URL. The comment shows a sample output URL. ```ts const file = await ctx.getFile(); const url = file.getUrl(); console.log(url); // https://api.telegram.org/file/bot123456:ABC/.../file_5 ``` -------------------------------- ### With local Bot API server options Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/hydrateFiles.md Installation with options for a local Bot API server. The apiRoot option points to the local server on port 8081, and the environment is set to "prod". ```ts import { Bot } from "grammy"; import { hydrateFiles } from "@grammyjs/files"; const bot = new Bot("TOKEN"); // When running a local Bot API server on port 8081 bot.api.config.use( hydrateFiles(bot.token, { apiRoot: "http://localhost:8081", environment: "prod", }), ); ``` -------------------------------- ### hydrateFiles(token, options?) Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/hydrateFiles.md Creates an API transformer that hydrates file-like response objects with FileX methods. Install with bot.api.config.use(hydrateFiles(bot.token)). ```APIDOC ## hydrateFiles(token, options?) ### Description Creates an API transformer that hydrates file-like response objects with FileX methods (getUrl, download, async iterator). Install with `bot.api.config.use(hydrateFiles(bot.token))`. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `token` | `string` | yes | — | The bot token; use `bot.token`. Embedded into download URLs. | | `options` | `FilesPluginOptions` | no | `undefined` | Optional configuration; see FilesPluginOptions. | ### Return Value `Transformer` — an API transformer to be installed with `bot.api.config.use(hydrateFiles(bot.token))`. ### Behavior For every intercepted call: 1. Invokes `prev(method, payload, signal)`. 2. If the response has `res.ok === true` and the result is a file-like object (determined by `isFile(res.result)`, i.e. `typeof result === "object" && result !== null && "file_id" in result`), `Object.assign(res.result, methods)` attaches the `FileX` methods (`getUrl`, `download`, `[Symbol.asyncIterator]`) directly onto the result object. 3. Returns the (possibly hydrated) response unchanged otherwise. ### Default Options When options are omitted, the following defaults are used: | Option fallback | Value | Source | |-----------------|-------|--------| | `apiRoot` | `"https://api.telegram.org"` | `src/plugin.ts:112` | | `environment` | `"prod"` | `src/plugin.ts:113` | | `buildFileUrl` | `defaultBuildFileUrl` | `src/plugin.ts:115` | | `buildFilePath` | `undefined` (paths passed through unchanged) | `src/plugin.ts:119` | ### defaultBuildFileUrl Internal non-exported helper (`src/plugin.ts:136-144`): ```ts const defaultBuildFileUrl: NonNullable = ( root, token, path, env, ) => { const prefix = env === "test" ? "test/" : ""; return `${root}/file/bot${token}/${prefix}${path}`; }; ``` Produces `https://api.telegram.org/file/bot/` (or `.../test/` when `environment === "test"`). ``` -------------------------------- ### FileX[Symbol.asyncIterator]() usage example Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Example usage of FileX[Symbol.asyncIterator]() to iterate over file chunks and print their sizes. The comments indicate preparing the file and printing chunk sizes. ```ts bot.on([":video", ":animation"], async (ctx) => { // Prepare file for download const file = await ctx.getFile(); // Print the size of each chunk for await (const chunk of file) { console.log(`Read ${chunk.length} bytes`); } }); ``` -------------------------------- ### hydrateFiles Options Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/files-plugin-options.md Documentation for the options accepted by the hydrateFiles plugin, including apiRoot, environment, buildFileUrl, and buildFilePath, with usage examples. ```APIDOC ## hydrateFiles Options ### Description Options for the `hydrateFiles` plugin, which customizes how file URLs are built and how file paths are resolved. ### Options - **apiRoot** (string) - Optional - Base URL for the Telegram Bot API. Defaults to `https://api.telegram.org`. - **environment** (string) - Optional - Environment for the file download route. Defaults to `prod`. When set to `test`, downloads route to `/file/bot/test/`. - **buildFileUrl** (function) - Optional - Custom function to build the file URL. Signature: `(root, token, path, environment) => string`. Defaults to the built-in URL builder. - **buildFilePath** (function) - Optional - Custom function to rewrite absolute file paths returned by the Bot API. Signature: `(root, token, path, environment) => string`. If not provided, absolute paths are used as-is. ### Usage Pass these options to `hydrateFiles` when configuring the bot's API. ### Examples #### Override apiRoot and environment ```ts import { Bot } from "grammy"; import { hydrateFiles } from "@grammyjs/files"; const bot = new Bot("TOKEN", { client: { apiRoot: "https://my-proxy.example.com" } }); bot.api.config.use( hydrateFiles(bot.token, { apiRoot: "https://my-proxy.example.com", }), ); ``` #### Test environment ```ts bot.api.config.use( hydrateFiles(bot.token, { environment: "test", // downloads route to /file/bot/test/ }), ); ``` #### Custom URL builder ```ts bot.api.config.use( hydrateFiles(bot.token, { buildFileUrl: (root, token, path) => `https://cdn.example.com/download/${token}/${path}`, }), ); ``` #### Rewrite absolute paths returned by a local Bot API server ```ts bot.api.config.use( hydrateFiles(bot.token, { // Local server reports /var/telegram/; fetch from a NAS instead buildFilePath: (_root, _token, path) => `https://storage.example.com/${path.replace("/var/telegram/", "")}`, }), ); ``` ``` -------------------------------- ### Install hydrateFiles plugin Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/index.md Install the hydrateFiles plugin in a grammY bot to enrich file results with download methods. Requires a FileFlavor context type and a bot token. ```ts import { Bot, type Context } from "grammy"; import { type FileFlavor, hydrateFiles } from "@grammyjs/files"; type MyContext = FileFlavor; const bot = new Bot("TOKEN"); bot.api.config.use(hydrateFiles(bot.token)); ``` -------------------------------- ### Catching Download failed error from file.download() Source: https://github.com/grammyjs/files/blob/main/_autodocs/errors.md Example of catching the "Download failed, no response body!" error from file.download() and logging a custom message. Use this pattern to handle the Deno-specific error when the server returns an empty response. ```typescript try { await file.download("/tmp/out"); } catch (err) { if (err instanceof Error && err.message === "Download failed, no response body!") { console.error("Server returned an empty response"); } } ``` -------------------------------- ### Using ctx.api.raw.getFile for voice messages Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/file-flavor.md Shows how to use the raw api method (ctx.api.raw.getFile) to obtain a File & FileX object directly on a voice message. You can then call file.getUrl() to get the file's URL and log it. ```ts bot.on(":voice", async (ctx) => { const file = await ctx.api.raw.getFile(ctx.msg.voice.file_id); // file is typed as File & FileX const url = file.getUrl(); console.log(url); }); ``` -------------------------------- ### FileX.download() with explicit path and error handling Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Usage of FileX.download() with an explicit path and error handling. The catch block shows an example error message 'File path is not available for file 'AgAC...''. ```ts bot.on(":document", async (ctx) => { const file = await ctx.getFile(); try { const path = await file.download("/tmp/doc-" + ctx.message.document.file_name); console.log("Saved to", path); } catch (err) { // e.g. "File path is not available for file 'AgAC...'" console.error("Download failed", err); } }); ``` -------------------------------- ### Download files with @grammyjs/files plugin Source: https://github.com/grammyjs/files/blob/main/README.md Install the @grammyjs/files plugin and download video or animation files to a temporary location. The plugin adds a `download` method to the file object returned by `ctx.getFile()`. The bot token is passed to `hydrateFiles` to enable the file download functionality. ```ts 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); }); ``` -------------------------------- ### Custom buildFileUrl for CDN downloads Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/files-plugin-options.md Customizes how file URLs are built by providing a buildFileUrl function. The function receives the root, token, and path to construct a custom URL, for example pointing to a CDN. ```ts bot.api.config.use( hydrateFiles(bot.token, { buildFileUrl: (root, token, path) => `https://cdn.example.com/download/${token}/${path}`, }), ); ``` -------------------------------- ### Rewrite absolute file paths with buildFilePath Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/files-plugin-options.md Rewrites absolute file paths returned by a local Bot API server by providing a buildFilePath function. This example maps paths like /var/telegram/ to a NAS URL. ```ts bot.api.config.use( hydrateFiles(bot.token, { // Local server reports /var/telegram/; fetch from a NAS instead buildFilePath: (_root, _token, path) => `https://storage.example.com/${path.replace("/var/telegram/", "")}`, }), ); ``` -------------------------------- ### downloadFile (Deno) Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/runtime-dependencies.md Deno implementation of downloadFile that fetches a URL and pipes the response body into a newly created file. Note createNew: true causes an error if the destination file already exists. ```ts export async function downloadFile(url: string, dest: string) { const body = await fetchFile(url); using writer = await Deno.open(dest, { createNew: true, write: true }); await body.pipeTo(writer.writable); } ``` -------------------------------- ### FileX.download() implementation Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Implementation of FileX.download(). Downloads the file to the given path or a temporary file if omitted. If getUrl() returns an absolute filesystem path, the local file is copied; otherwise the URL is fetched and streamed to disk. On Deno, the destination is written with createNew: true, so an existing file causes an error. ```ts async download(path?: string) { const url = this.getUrl(); path ??= await createTempFile(); if (isAbsolutePath(url)) await copyFile(url, path); else await downloadFile(url, path); return path; } ``` -------------------------------- ### fetchFile (Deno) Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/runtime-dependencies.md Deno implementation of fetchFile that fetches a URL and returns the response body as a ReadableStream. Throws an Error with message "Download failed, no response body!" when the body is null. ```ts export async function fetchFile(url: string) { const { body } = await fetch(url); if (body === null) throw new Error("Download failed, no response body!"); return body; } ``` -------------------------------- ### createTempFile (Node) Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/runtime-dependencies.md Node implementation of createTempFile that creates a fresh temporary directory under the real system temp dir and returns `/filedata` as the destination for FileX.download. ```ts export const createTempFile = async () => path.join( await fs.promises.mkdtemp( (await fs.promises.realpath(os.tmpdir())) + path.sep, ), "filedata", ); ``` -------------------------------- ### Configure hydrateFiles with different options Source: https://github.com/grammyjs/files/blob/main/_autodocs/configuration.md Shows how to use hydrateFiles from @grammyjs/files with a Bot instance. It demonstrates four configurations: local Bot API server with apiRoot, test environment, custom buildFileUrl, and buildFilePath for remote stores. Each configuration is applied via bot.api.config.use(). ```TypeScript import { Bot } from "grammy"; import { hydrateFiles } from "@grammyjs/files"; const bot = new Bot("TOKEN"); // Local Bot API server: downloads resolve against the local server bot.api.config.use( hydrateFiles(bot.token, { apiRoot: "http://localhost:8081", }), ); // Test environment bot.api.config.use( hydrateFiles(bot.token, { environment: "test", }), ); // Full control over URL generation bot.api.config.use( hydrateFiles(bot.token, { buildFileUrl: (root, token, path, env) => new URL(`/custom/${env}/${token}/${path}`, root), }), ); // Local Bot API server with files on a remote store: rewrite absolute paths bot.api.config.use( hydrateFiles(bot.token, { buildFilePath: (_root, _token, path) => `https://files.example.com/${encodeURIComponent(path)}`, }), ); ``` -------------------------------- ### FileX.download() basic call Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Basic usage of FileX.download() without a path, which creates a temporary file and returns its path. The comment notes the file is temporary. ```ts bot.on(":document", async (ctx) => { const file = await ctx.getFile(); const path = await file.download(); // temporary file console.log("File saved at", path); }); ``` -------------------------------- ### defaultBuildFileUrl helper Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/hydrateFiles.md Internal helper that builds the download URL for a file. It prefixes the path with "test/" when the environment is "test". The resulting URL is `https://api.telegram.org/file/bot/` (or `.../test/` in test mode). ```ts const defaultBuildFileUrl: NonNullable = ( root, token, path, env, ) => { const prefix = env === "test" ? "test/" : ""; return `${root}/file/bot${token}/${prefix}${path}`; }; ``` -------------------------------- ### Default buildFileUrl implementation Source: https://github.com/grammyjs/files/blob/main/_autodocs/configuration.md Constructs the file URL with an optional 'test/' prefix for the test environment. Used when buildFileUrl is not provided. ```TypeScript // src/plugin.ts:136-144 const defaultBuildFileUrl: NonNullable = ( root, token, path, env, ) => { const prefix = env === "test" ? "test/" : ""; return `${root}/file/bot${token}/${prefix}${path}`; }; ``` -------------------------------- ### Use test environment in hydrateFiles Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/files-plugin-options.md Sets the environment to "test" so downloaded files are routed to /file/bot/test/. This is useful when testing against a Bot API server that uses a test environment. ```ts bot.api.config.use( hydrateFiles(bot.token, { environment: "test", // downloads route to /file/bot/test/ }), ); ``` -------------------------------- ### readFile (Deno) Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/runtime-dependencies.md Deno implementation of readFile that opens a file and yields its readable stream as an AsyncIterable. Used by FileX[Symbol.asyncIterator] for absolute paths. ```ts export async function* readFile(path: string): AsyncIterable { const file = await Deno.open(path); yield* file.readable; } ``` -------------------------------- ### Apply defaults in hydrateFiles with nullish coalescing Source: https://github.com/grammyjs/files/blob/main/_autodocs/configuration.md Shows how apiRoot, environment, buildFileUrl, and buildFilePath defaults are applied. buildFilePath defaults to undefined, leaving absolute paths untouched. ```TypeScript const root = options?.apiRoot ?? "https://api.telegram.org"; const environment = options?.environment ?? "prod"; const buildFileUrl = options?.buildFileUrl ?? defaultBuildFileUrl; const buildLink = (path: string) => buildFileUrl(root, token, path, environment); const buildFilePath = options?.buildFilePath ?? undefined; const buildPath = (path: string) => buildFilePath !== undefined ? buildFilePath(root, token, path, environment) : path; ``` -------------------------------- ### download(path?: string) Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Downloads the file to the specified path, or to a temporary file if no path is provided. Returns the absolute path of the downloaded file. If the file URL is an absolute local path, the file is copied; otherwise it is fetched and streamed to disk. ```APIDOC ## download(path?: string) ### Description Downloads the file to the specified path, or to a temporary file if no path is provided. Returns the absolute path of the downloaded file. If the file URL is an absolute local path, the file is copied; otherwise it is fetched and streamed to disk. ### Method N/A (interface method) ### Endpoint N/A ### Parameters #### Optional Parameters - `path` (string) - Optional - Destination path for the downloaded file. If omitted, a temporary file is created and its path is returned. ### Request Example ```ts bot.on(":document", async (ctx) => { const file = await ctx.getFile(); const path = await file.download(); // temporary file console.log("File saved at", path); }); ``` ### Response #### Success Response - Returns `Promise` - the absolute path of the downloaded/copied file. #### Response Example ```ts bot.on(":document", async (ctx) => { const file = await ctx.getFile(); try { const path = await file.download("/tmp/doc-" + ctx.message.document.file_name); console.log("Saved to", path); } catch (err) { // e.g. "File path is not available for file 'AgAC...'" console.error("Download failed", err); } }); ``` ### Error Handling - Rejects with `Error` when `file_path` is undefined (propagated from `getUrl`). - Platform errors (network failure, missing destination directory, `EEXIST` on Deno's `createNew`) are propagated from underlying helpers. ``` -------------------------------- ### Custom API with FileApiFlavor and FileFlavor Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/file-flavor.md Shows how to combine FileFlavor and FileApiFlavor when using a custom API type. Both flavors propagate the FileX methods, allowing you to iterate over the file's chunks with a for-await loop after calling ctx.api.getFile(). ```ts import { Api, Bot, Context } from "grammy"; import { type FileApiFlavor, type FileFlavor, hydrateFiles } from "@grammyjs/files"; type MyContext = FileFlavor; type MyApi = FileApiFlavor; // With a custom API type, both flavors propagate the FileX methods const bot = new Bot("TOKEN", { api: "custom" }); bot.api.config.use(hydrateFiles(bot.token)); bot.on(":photo", async (ctx) => { const file = await ctx.api.getFile(ctx.msg.photo.at(-1)!.file_id); const chunks: Uint8Array[] = []; for await (const chunk of file) chunks.push(chunk); }); ``` -------------------------------- ### hydrateFiles(token, options?) Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/hydrateFiles.md Creates a grammY API transformer that hydrates the results of getFile API calls with file-download utilities. The transformer wraps the API call and, if the result is a file, attaches methods to build file URLs or paths. ```APIDOC ## hydrateFiles(token, options?) ### Description Creates a grammY API transformer that hydrates the results of `getFile` API calls with file-download utilities. The transformer wraps the API call and, if the result is a file, attaches methods to build file URLs or paths. ### Signature ```ts export function hydrateFiles( token: string, options?: FilesPluginOptions, ): Transformer ``` ### Parameters - **token** (string) - Required - The bot token used to construct file URLs. - **options** (FilesPluginOptions) - Optional - Plugin options that can customize the API root, environment, and file URL/path builders. ### Returns - **Transformer** - A grammY API transformer function that wraps API calls and hydrates file results. ### Transformer Behavior The returned transformer is a function `(prev, method, payload, signal) => Promise` where: - `prev` performs the wrapped API call. - `method` is the Bot API method name. - `payload` is the method parameters. - `signal` is an optional `AbortSignal`. When the wrapped API call returns a successful result and the result is a file (as determined by `isFile`), the transformer attaches file-download utility methods to the result object. ### Options - **apiRoot** (string) - Optional - The API root URL, defaults to `"https://api.telegram.org"`. - **environment** (string) - Optional - The environment, defaults to `"prod"`. - **buildFileUrl** (function) - Optional - Custom function to build file URLs. - **buildFilePath** (function) - Optional - Custom function to build file paths. ### Example ```ts import { hydrateFiles } from "@grammyjs/files"; const bot = new Bot("YOUR_BOT_TOKEN"); bot.api.config.use(hydrateFiles("YOUR_BOT_TOKEN")); ``` ``` -------------------------------- ### FileX.getUrl() implementation Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Implementation of FileX.getUrl(). Returns a string: for non-absolute file_path, the URL from the plugin's URL builder (default https://api.telegram.org/file/bot/); for absolute paths, the rewritten path from buildFilePath or the raw path. Throws an Error with message 'File path is not available for file ''' when file_path is undefined. ```ts getUrl(this: File) { const path = this.file_path; if (path === undefined) { const id = this.file_id; throw new Error(`File path is not available for file '${id}'`); } if (isAbsolutePath(path)) return pathBuilder(path); const link = linkBuilder(path); if (link instanceof URL) return link.href; return link; } ``` -------------------------------- ### FilesPluginOptions interface Source: https://github.com/grammyjs/files/blob/main/_autodocs/types.md Options object accepted by hydrateFiles(token, options). Defaults: apiRoot is "https://api.telegram.org", environment is "prod". buildFileUrl defaults to a built-in builder; buildFilePath defaults to identity. ```ts export interface FilesPluginOptions { apiRoot?: string; environment?: "prod" | "test"; buildFileUrl?: ( root: string, token: string, path: string, env: "prod" | "test", ) => string | URL; buildFilePath?: ( root: string, token: string, path: string, env: "prod" | "test", ) => string; } ``` -------------------------------- ### Entry point re-export Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/index.md Single-line entry point for the plugin, re-exporting all public symbols from the plugin module. ```ts export * from "./plugin.ts"; ``` -------------------------------- ### FileX[Symbol.asyncIterator]() implementation Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Implementation of FileX[Symbol.asyncIterator](). Yields Uint8Array chunks of the file data. For absolute local paths, the local file is streamed; for URLs, the remote body is streamed. Rejects with an Error when file_path is undefined (propagated from getUrl). ```ts async *[Symbol.asyncIterator]() { const url = this.getUrl(); if (isAbsolutePath(url)) { yield* readFile(url); } else { yield* await fetchFile(url); } } ``` -------------------------------- ### getUrl() Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Returns a URL string for the file. For non-absolute file paths, it builds a URL using the plugin's URL builder (defaulting to the Telegram Bot API file endpoint). For absolute paths (local Bot API server), it returns the rewritten or raw local path. ```APIDOC ## getUrl() ### Description Returns a URL string for the file. For non-absolute file paths, it builds a URL using the plugin's URL builder (defaulting to the Telegram Bot API file endpoint). For absolute paths (local Bot API server), it returns the rewritten or raw local path. ### Method N/A (interface method) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response - Returns a `string` representing the file URL or local path. #### Response Example ```ts const file = await ctx.getFile(); const url = file.getUrl(); console.log(url); // https://api.telegram.org/file/bot123456:ABC/.../file_5 ``` ### Error Handling - Throws `Error` with message `File path is not available for file ''` when `file_path` is undefined. ``` -------------------------------- ### Internal mapping and helper types for FileFlavor Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/file-flavor.md Internal helper types that implement the flavor mechanism. The X interface maps method names to their return type extensions, and the helper types recursively add the extension to Context, Api, and RawApi. These are not exported but are used by the exported flavors. ```ts /** * Mapping table from method names to API call result extensions. * * In other words, every key K of this interface identifies a method of the Bot * API that exists as method on `ctx`, `ctx.api`, and `ctx.api.raw`. The return * type of every one of these three methods will be augmented by `X[K]` via type * intersection. */ interface X { getFile: FileX; } // Helper types to add `X` to `Context` and `Api` and `RawApi` type ContextX = AddX & { api: ApiX; }; type ApiX = AddX & { raw: RawApiX; }; type RawApiX = AddX; type AddX any>> = { [K in keyof X]: Extend; }; type Extend any, X> = ( ...args: Parameters ) => Promise> & X>; type Await = T extends PromiseLike ? Await : T; ``` -------------------------------- ### FileX interface definition Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Defines the FileX interface, which describes a Telegram File object augmented at runtime with methods for URL retrieval, downloading, and async iteration. The runtime methods are attached via Object.assign(res.result, methods) inside the transformer. ```ts export interface FileX { getUrl(): string; download(path?: string): Promise; [Symbol.asyncIterator](): AsyncIterator; } ``` -------------------------------- ### Catch 'File path is not available' error in a bot handler Source: https://github.com/grammyjs/files/blob/main/_autodocs/errors.md Shows how to catch the specific error thrown by getUrl() when a file cannot be downloaded because file_path is undefined. The check uses the exact error message with the file_id interpolated, and rethrows any other error. ```typescript bot.on(":document", async (ctx) => { const file = await ctx.getFile(); try { const path = await file.download(); console.log(path); } catch (err) { if (err instanceof Error && err.message === `File path is not available for file '${file.file_id}'`) { console.log("This file cannot be downloaded (no file_path)."); } else { throw err; } } }); ``` -------------------------------- ### Internal expansion of FileFlavor Source: https://github.com/grammyjs/files/blob/main/_autodocs/types.md Internal expansion of FileFlavor, showing how the context and API types are recursively augmented with the getFile return type. Not exported directly. ```ts type ContextX = AddX & { api: ApiX; }; type ApiX = AddX & { raw: RawApiX; }; type RawApiX = AddX; type AddX any>> = { [K in keyof X]: Extend; }; type Extend any, X> = ( ...args: Parameters ) => Promise> & X>; type Await = T extends PromiseLike ? Await : T; ``` -------------------------------- ### FilesPluginOptions interface definition Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/files-plugin-options.md The interface defines configuration options for the hydrateFiles plugin. It includes apiRoot for the Telegram Bot API server URL, environment for prod or test, and custom URL/path builder functions. ```ts export interface FilesPluginOptions { /** * Root URL of the Telegram Bot API server. Used when downloading files. * Should be the same as for your bot object. Default: * https://api.telegram.org */ apiRoot?: string; /** * Specifies whether to use the [test * environment](https://core.telegram.org/bots/webapps#using-bots-in-the-test-environment). * Can be either `"prod"` (default) or `"test"`. * * The testing infrastructure is separate from the regular production * infrastructure. No chats, accounts, or other data is shared between them. * If you set this option to `"test"`, you will need to make your Telegram * client connect to the testing data centers of Telegram, register your * phone number again, open a new chat with @BotFather, and create a * separate bot. */ environment?: "prod" | "test"; /** * URL builder function for downloading files. Can be used to modify which * API server should be called when downloading files. * * @param root The URL that was passed in `apiRoot`, or its default value * @param token The bot's token that was passed when installing the plugin * @param path The `file_path` value that identifies the file * @param env The value that was passed in `environment`, or its default value * @returns The URL that will be fetched during the download */ buildFileUrl?: ( root: string, token: string, path: string, env: "prod" | "test", ) => string | URL; /** * Similar to `buildFileUrl`, but used when the server returns an * absolute file path instead of a URL. This is useful when you are * running a Bot API server, and you want to download files * from a custom remote location instead of a local file system. * * The function can still pass a URL, and the plugin will download the * file instead of reading it from the file system. * * @param root The URL that was passed in `apiRoot`, or its default value * @param token The bot's token that was passed when installing the plugin * @param path The `file_path` value that identifies the file * @param env The value that was passed in `environment`, or its default value * @returns The URL or file path that will be used to download the file. */ buildFilePath?: ( root: string, token: string, path: string, env: "prod" | "test", ) => string; } ``` -------------------------------- ### hydrateFiles function implementation Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/hydrateFiles.md The main plugin function that creates a grammY API transformer. It hydrates getFile results with file-download utilities. The transformer wraps the API call, and if the result is a file, it assigns the file methods to the result object. The function uses options for apiRoot, environment, buildFileUrl, and buildFilePath, with defaults for apiRoot and environment. ```ts export function hydrateFiles( token: string, options?: FilesPluginOptions, ): Transformer { const root = options?.apiRoot ?? "https://api.telegram.org"; const environment = options?.environment ?? "prod"; const buildFileUrl = options?.buildFileUrl ?? defaultBuildFileUrl; const buildLink = (path: string) => buildFileUrl(root, token, path, environment); const buildFilePath = options?.buildFilePath ?? undefined; const buildPath = (path: string) => buildFilePath !== undefined ? buildFilePath(root, token, path, environment) : path; const methods = getFileMethods(buildLink, buildPath); const t: Transformer = async (prev, method, payload, signal) => { const res = await prev(method, payload, signal); if (res.ok && isFile(res.result)) { Object.assign(res.result, methods); } return res; }; return t; } ``` -------------------------------- ### [Symbol.asyncIterator]() Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/filex.md Returns an async iterator that yields Uint8Array chunks of the file data. For absolute local paths, the local file is streamed; for URLs, the remote body is streamed. ```APIDOC ## [Symbol.asyncIterator]() ### Description Returns an async iterator that yields Uint8Array chunks of the file data. For absolute local paths, the local file is streamed; for URLs, the remote body is streamed. ### Method N/A (interface method) ### Endpoint N/A ### Parameters None ### Request Example ```ts bot.on([":video", ":animation"], async (ctx) => { // Prepare file for download const file = await ctx.getFile(); // Print the size of each chunk for await (const chunk of file) { console.log(`Read ${chunk.length} bytes`); } }); ``` ### Response #### Success Response - Returns `AsyncIterator` - an async iterator of file data chunks. #### Response Example N/A ### Error Handling - Rejects with `Error` when `file_path` is undefined (propagated from `getUrl`). - Network errors propagate from the platform `fetchFile` helper. ``` -------------------------------- ### getUrl() throws Error when file_path is undefined Source: https://github.com/grammyjs/files/blob/main/_autodocs/errors.md Throws a plain Error when the Telegram File object lacks a file_path property, which occurs for files larger than 20 MB that cannot be downloaded via the standard mechanism. This method is the funnel for all public FileX methods, so download() and the async iterator reject with this error. ```typescript // src/files.ts:78-88 getUrl(this: File) { const path = this.file_path; if (path === undefined) { const id = this.file_id; throw new Error(`File path is not available for file '${id}'`); } ... } ``` -------------------------------- ### Export FileFlavor and FileApiFlavor types Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/file-flavor.md Defines the two exported flavor types. FileFlavor augments a Context type, while FileApiFlavor augments an Api type. These are the primary exports of the plugin. ```ts export type FileFlavor = ContextX & C; export type FileApiFlavor = ApiX & A; ``` -------------------------------- ### FileFlavor type alias Source: https://github.com/grammyjs/files/blob/main/_autodocs/types.md Use to augment a base context type so that the getFile method returns a File & FileX. Accept it as the first type parameter of new Bot(...). ```ts export type FileFlavor = ContextX & C; ``` -------------------------------- ### Files Plugin Types Source: https://github.com/grammyjs/files/blob/main/_autodocs/types.md Type definitions for the grammY files plugin, including the main plugin function and type flavors. ```APIDOC ## hydrateFiles ### Description Creates a transformer that augments the bot's `getFile` method to return `FileX` objects with additional file information. ### Parameters - **token** (string) - Required - The bot token used to construct file URLs. - **options** (FilesPluginOptions) - Optional - Configuration options for the plugin. ### Returns - **Transformer** - A transformer to be used with the bot. ``` ```APIDOC ## FileFlavor ### Description A context flavor that augments the `getFile` method on the context to return `FileX` objects. ### Type Parameters - **C** - The original context type. ### Returns - A context type with `FileX`-augmented `getFile`. ``` ```APIDOC ## FileApiFlavor ### Description An API flavor that augments the `getFile` method on the API to return `FileX` objects. ### Type Parameters - **A** - The original API type. ### Returns - An API type with `FileX`-augmented `getFile`. ``` ```APIDOC ## getFileMethods ### Description Provides methods to construct file URLs and retrieve file information. ### Parameters - **path** (string | URL) - Required - The file path or URL. - **path** (string) - Required - The file path. ### Returns - **FileX** - An object containing file information and methods. ``` -------------------------------- ### FileApiFlavor type alias Source: https://github.com/grammyjs/files/blob/main/_autodocs/types.md Use to augment a base API type so that the getFile method returns File & FileX, propagating to api.raw. Accept it as the second type parameter of new Bot(...). ```ts export type FileApiFlavor = ApiX & A; ``` -------------------------------- ### Override apiRoot for hydrateFiles Source: https://github.com/grammyjs/files/blob/main/_autodocs/api-reference/files-plugin-options.md Overrides the Telegram API endpoint using the apiRoot option. This is useful when running behind a proxy or a custom server that hosts the Bot API. ```ts import { Bot } from "grammy"; import { hydrateFiles } from "@grammyjs/files"; const bot = new Bot("TOKEN", { client: { apiRoot: "https://my-proxy.example.com" } }); bot.api.config.use( hydrateFiles(bot.token, { apiRoot: "https://my-proxy.example.com", }), ); ```