// === Needed imports import { type ApiMethods as ApiMethodsF, type InputMedia as InputMediaF, type InputMediaAnimation as InputMediaAnimationF, type InputMediaAudio as InputMediaAudioF, type InputMediaDocument as InputMediaDocumentF, type InputMediaLivePhoto as InputMediaLivePhotoF, type InputMediaPhoto as InputMediaPhotoF, type InputMediaSticker as InputMediaStickerF, type InputMediaVideo as InputMediaVideoF, type InputMediaVoiceNote as InputMediaVoiceNoteF, type InputPaidMedia as InputPaidMediaF, type InputPaidMediaLivePhoto as InputPaidMediaLivePhotoF, type InputPaidMediaPhoto as InputPaidMediaPhotoF, type InputPaidMediaVideo as InputPaidMediaVideoF, type InputPollMedia as InputPollMediaF, type InputPollOption as InputPollOptionF, type InputPollOptionMedia as InputPollOptionMediaF, type InputProfilePhoto as InputProfilePhotoAnimatedF, type InputProfilePhoto as InputProfilePhotoF, type InputProfilePhoto as InputProfilePhotoStaticF, type InputRichBlock as InputRichBlockF, type InputRichBlockAnimation as InputRichBlockAnimationF, type InputRichBlockAudio as InputRichBlockAudioF, type InputRichBlockBlockQuotation as InputRichBlockBlockQuotationF, type InputRichBlockCollage as InputRichBlockCollageF, type InputRichBlockDetails as InputRichBlockDetailsF, type InputRichBlockDocument as InputRichBlockDocumentF, type InputRichBlockExpandableBlockQuotation as InputRichBlockExpandableBlockQuotationF, type InputRichBlockList as InputRichBlockListF, type InputRichBlockListItem as InputRichBlockListItemF, type InputRichBlockPhoto as InputRichBlockPhotoF, type InputRichBlockSlideshow as InputRichBlockSlideshowF, type InputRichBlockVideo as InputRichBlockVideoF, type InputRichBlockVoiceNote as InputRichBlockVoiceNoteF, type InputRichMessage as InputRichMessageF, type InputRichMessageMedia as InputRichMessageMediaF, type InputSticker as InputStickerF, type InputStoryContent as InputStoryContentF, type InputStoryContentPhoto as InputStoryContentPhotoF, type InputStoryContentVideo as InputStoryContentVideoF, type Opts as OptsF, } from "@grammyjs/types"; import { createReadStream, type ReadStream } from "fs"; import { AbortController } from "abort-controller"; import fetch from "node-fetch"; import { basename } from "path"; import { debug as d } from "./platform.node"; const debug = d("grammy:warn"); // === Export all API types export * from "@grammyjs/types"; /** A value, or a potentially async function supplying that value */ type MaybeSupplier = T | (() => T | Promise); /** Something that looks like a URL. */ interface URLLike { /** * Identifier of the resource. Must be in a format that can be parsed by the * URL constructor. */ url: string; } /** Something that looks like a `Response` object of the Fetch API. */ interface ResponseLike extends URLLike { /** Whether the response was successful */ ok: boolean; /** HTTP status code of the response */ status: number; /** Stream of the response body, or `null` if there is none */ body: AsyncIterable | null; } // === InputFile handling and File augmenting /** * An `InputFile` wraps a number of different sources for [sending * files](https://grammy.dev/guide/files#uploading-your-own-files). * * It corresponds to the `InputFile` type in the [Telegram Bot API * Reference](https://core.telegram.org/bots/api#inputfile). */ export class InputFile { private consumed = false; private readonly fileData: ConstructorParameters[0]; /** * Optional name of the constructed `InputFile` instance. * * Check out the * [documentation](https://grammy.dev/guide/files#uploading-your-own-files) * on sending files with `InputFile`. */ public readonly filename?: string; /** * Constructs an `InputFile` that can be used in the API to send files. * * @param file A path to a local file or a `Buffer` or a `fs.ReadStream` that specifies the file data * @param filename Optional name of the file */ constructor( file: MaybeSupplier< | string | URL | ResponseLike | URLLike | Uint8Array | ReadStream | Iterable | AsyncIterable >, filename?: string, ) { this.fileData = file; filename ??= this.guessFilename(file); this.filename = filename; if ( typeof file === "string" && (file.startsWith("http:") || file.startsWith("https:")) ) { debug( `InputFile received the local file path '${file}' that looks like a URL. Is this a mistake?`, ); } } private guessFilename( file: ConstructorParameters[0], ): string | undefined { if (typeof file === "string") return basename(file); if ("url" in file) return basename(file.url); if (!(file instanceof URL)) return undefined; if (file.pathname !== "/") { const filename = basename(file.pathname); if (filename) return filename; } return basename(file.hostname); } /** * Internal method. Do not use. * * Converts this instance into a binary representation that can be sent to * the Bot API server in the request body. */ async toRaw(): Promise< Uint8Array | Iterable | AsyncIterable > { if (this.consumed) { throw new Error("Cannot reuse InputFile data source!"); } const data = this.fileData; // Handle local files if (typeof data === "string") return createReadStream(data); // Handle URLs and URLLike objects if (data instanceof URL) { return data.protocol === "file" // node-fetch does not support file URLs ? createReadStream(data.pathname) : fetchFile(data); } // Reuse streams from fetch responses, otherwise fetch their URL below. // Technically breaking: user-constructed Responses can pass this check // but yield non-Uint8Array chunks; we do not expect this use case. if ( "body" in data && "ok" in data && typeof data.body?.[Symbol.asyncIterator] === "function" ) { if (!data.ok) { throw new Error( `Cannot upload response with HTTP status ${data.status}!`, ); } if (data.body === null) throw new Error(`No response body!`); this.consumed = true; return data.body; } if ("url" in data) return fetchFile(data.url); // Return buffers as-is if (data instanceof Uint8Array) return data; // Unwrap supplier functions if (typeof data === "function") { return new InputFile(await data()).toRaw(); } // Mark streams and iterators as consumed and return them as-is this.consumed = true; return data; } toJSON() { throw new Error("InputFile instances must be sent via grammY"); } } async function* fetchFile(url: string | URL): AsyncIterable { const controller = new AbortController(); const { ok, status, body } = await fetch(url, { signal: controller.signal, }); if (!ok) { controller.abort(); throw new Error( `Download failed, received HTTP status ${status} from '${url}'`, ); } for await (const chunk of body) { if (typeof chunk === "string") { throw new Error( `Could not transfer file, received string data instead of bytes from '${url}'`, ); } yield chunk; } } // === Export InputFile types /** Wrapper type to bundle all methods of the Telegram API */ export type ApiMethods = ApiMethodsF; /** Utility type providing the argument type for the given method name or `{}` if the method does not take any parameters */ export type Opts = OptsF[M]; /** This object describes a sticker to be added to a sticker set. */ export type InputSticker = InputStickerF; /** This object represents the content of a media message to be sent. It should be one of - InputMediaAnimation - InputMediaAudio - InputMediaDocument - InputMediaLivePhoto - InputMediaPhoto - InputMediaVideo */ export type InputMedia = InputMediaF; /** Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. */ export type InputMediaAnimation = InputMediaAnimationF; /** Represents an audio file to be treated as music to be sent. */ export type InputMediaAudio = InputMediaAudioF; /** Represents a general file to be sent. */ export type InputMediaDocument = InputMediaDocumentF; /** Represents a live photo to be sent. */ export type InputMediaLivePhoto = InputMediaLivePhotoF; /** Represents a photo to be sent. */ export type InputMediaPhoto = InputMediaPhotoF; /** Represents a sticker file to be sent. */ export type InputMediaSticker = InputMediaStickerF; /** Represents a video to be sent. */ export type InputMediaVideo = InputMediaVideoF; /** Represents a voice message file to be sent. */ export type InputMediaVoiceNote = InputMediaVoiceNoteF; /** This object contains information about one answer option in a poll to send. */ export type InputPollOption = InputPollOptionF; /** This object represents the content of a poll description or a quiz explanation to be sent. It should be one of - InputMediaAnimation - InputMediaAudio - InputMediaDocument - InputMediaLivePhoto - InputMediaLocation - InputMediaPhoto - InputMediaVenue - InputMediaVideo */ export type InputPollMedia = InputPollMediaF; /** This object represents the content of a poll option to be sent. It should be one of - InputMediaAnimation - InputMediaLivePhoto - InputMediaLocation - InputMediaPhoto - InputMediaSticker - InputMediaVenue - InputMediaVideo */ export type InputPollOptionMedia = InputPollOptionMediaF; /** This object describes the paid media to be sent. Currently, it can be one of - InputPaidMediaPhoto - InputPaidMediaVideo */ export type InputPaidMedia = InputPaidMediaF; /** The paid media to send is a live photo. */ export type InputPaidMediaLivePhoto = InputPaidMediaLivePhotoF; /** The paid media to send is a photo. */ export type InputPaidMediaPhoto = InputPaidMediaPhotoF; /** The paid media to send is a video. */ export type InputPaidMediaVideo = InputPaidMediaVideoF; /** This object describes a profile photo to set. Currently, it can be one of - InputProfilePhotoStatic - InputProfilePhotoAnimated */ export type InputProfilePhoto = InputProfilePhotoF; /** A static profile photo in the .JPG format. */ export type InputProfilePhotoStatic = InputProfilePhotoStaticF; /** An animated profile photo in the MPEG4 format. */ export type InputProfilePhotoAnimated = InputProfilePhotoAnimatedF; /** This object describes the content of a story to post. Currently, it can be one of - InputStoryContentPhoto - InputStoryContentVideo */ export type InputStoryContent = InputStoryContentF; /** Describes a photo to post as a story. */ export type InputStoryContentPhoto = InputStoryContentPhotoF; /** Describes a video to post as a story. */ export type InputStoryContentVideo = InputStoryContentVideoF; /** Describes a rich message to be sent. Exactly one of the fields html, markdown, or blocks must be used. */ export type InputRichMessage = InputRichMessageF; /** Describes a rich message to be sent. Exactly one of the fields html, markdown, or blocks must be used. */ export type InputRichMessageWithoutUpload = InputRichMessageF; /** Describes a media element embedded in an outgoing rich message. */ export type InputRichMessageMedia = InputRichMessageMediaF; /** An item of a list to be sent. */ export type InputRichBlockListItem = InputRichBlockListItemF; /** This object represents a block in a rich formatted message to be sent. Currently, it can be any of the following types: - InputRichBlockParagraph - InputRichBlockSectionHeading - InputRichBlockPreformatted - InputRichBlockFooter - InputRichBlockDivider - InputRichBlockMathematicalExpression - InputRichBlockAnchor - InputRichBlockList - InputRichBlockBlockQuotation - InputRichBlockExpandableBlockQuotation - InputRichBlockPullQuotation - InputRichBlockCollage - InputRichBlockSlideshow - InputRichBlockTable - InputRichBlockDetails - InputRichBlockMap - InputRichBlockButtons - InputRichBlockAnimation - InputRichBlockAudio - InputRichBlockDocument - InputRichBlockPhoto - InputRichBlockVideo - InputRichBlockVoiceNote - InputRichBlockThinking */ export type InputRichBlock = InputRichBlockF; /** A list of blocks, corresponding to the HTML tag \
    or \
      with multiple nested tags \
    1. . */ export type InputRichBlockList = InputRichBlockListF; /** A block quotation, corresponding to the HTML tag \
      . */ export type InputRichBlockBlockQuotation = InputRichBlockBlockQuotationF< InputFile >; /** A block quotation, corresponding to the HTML tag \
      with custom attribute "expandable". */ export type InputRichBlockExpandableBlockQuotation = InputRichBlockExpandableBlockQuotationF; /** A collage, corresponding to the custom HTML tag \. */ export type InputRichBlockCollage = InputRichBlockCollageF; /** A slideshow, corresponding to the custom HTML tag \. */ export type InputRichBlockSlideshow = InputRichBlockSlideshowF; /** An expandable block for details disclosure, corresponding to the HTML tag \
      . */ export type InputRichBlockDetails = InputRichBlockDetailsF; /** A block with an animation, corresponding to the HTML tag \