### Installing Dependencies for Type Generation Source: https://github.com/gramiojs/types/blob/main/README.md Install the necessary project dependencies using 'bun install' after cloning the @gramio/types repository. This prepares the environment for running the generation script. ```bash bun install ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Use this command to install all project dependencies managed by Bun. ```bash bun install ``` -------------------------------- ### Install @gramio/types with npm Source: https://github.com/gramiojs/types/blob/main/_autodocs/README.md Install the library using npm for Node.js environments. ```bash npm install @gramio/types ``` -------------------------------- ### Install @gramio/types with Deno (JSR) Source: https://github.com/gramiojs/types/blob/main/_autodocs/README.md Install the library using Deno and JSR for JavaScript Runtime environments. ```bash deno add @gramio/types # JSR ``` -------------------------------- ### Usage Examples Source: https://github.com/gramiojs/types/blob/main/_autodocs/MANIFEST.txt Practical code examples demonstrating real-world integration patterns and error handling. ```APIDOC ## 07-usage-examples.md ### Description This file provides 16 practical code examples showcasing real-world integration patterns and effective error handling techniques. ### Content - 16 practical code examples - Real-world integration patterns - Error handling ``` -------------------------------- ### Build and Publish Source: https://github.com/gramiojs/types/blob/main/_autodocs/MANIFEST.txt Guide to build commands, workflow, CI/CD pipeline, and publishing to npm and JSR. ```APIDOC ## 09-build-and-publish.md ### Description This file outlines the build commands and workflow, the CI/CD pipeline, and the process for publishing the library to npm and JSR. ### Content - Build commands and workflow - CI/CD pipeline - Publishing to npm and JSR ``` -------------------------------- ### InputMedia Union Example Source: https://github.com/gramiojs/types/blob/main/_autodocs/10-advanced-topics.md Shows an example of creating an array of TelegramInputMedia, demonstrating how different media types (photo, video, document) are represented using their respective types and the 'type' discriminator. ```typescript const media: TelegramInputMedia[] = [ { type: "photo", media: photoBlob }, { type: "video", media: videoBlob, thumbnail: thumbBlob }, { type: "document", media: docBlob } ] ``` -------------------------------- ### Example: SendChatAction Parameters Source: https://github.com/gramiojs/types/blob/main/_autodocs/06-code-generator-api.md Example output for generating parameters for the 'sendChatAction' method, showing enum union types and the main params interface. ```typescript export type SendChatActionAction = | "typing" | "upload_photo" | "record_video" | // ... more actions export interface SendChatActionParams { chat_id: number | string action: SendChatActionAction message_thread_id?: number } ``` -------------------------------- ### Example Usage: getMe API Method Source: https://github.com/gramiojs/types/blob/main/_autodocs/03-api-methods-reference.md Demonstrates calling an API method that takes no parameters, such as getMe, which returns a Promise of TelegramUser. ```typescript const user = await api.getMe(); ``` -------------------------------- ### Example: sendMessage APIMethods Entry Source: https://github.com/gramiojs/types/blob/main/_autodocs/06-code-generator-api.md Example output for generating a single APIMethods interface entry for the 'sendMessage' method, including its JSDoc comment and type signature. ```typescript /** * Use this method to send text messages... * * [Documentation](https://core.telegram.org/bots/api/#sendmessage) */ sendMessage: CallAPI ``` -------------------------------- ### Integrating with @gramio/keyboards Source: https://github.com/gramiojs/types/blob/main/README.md Demonstrates how to use the custom API wrapper with @gramio/keyboards to send messages that include custom keyboards. Ensure @gramio/keyboards is installed separately. ```typescript import { Keyboard } from "@gramio/keyboards"; // the code from the example above api.sendMessage({ chat_id: 1, text: "message with keyboard", reply_markup: new Keyboard().text("button text"), }); ``` -------------------------------- ### Send Invoice for Payment Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md This example shows how to send an invoice to a user for a product or service. It requires `chat_id`, `title`, `description`, `payload`, `currency`, `prices`, and a `provider_token`. ```typescript import type { SendInvoiceParams } from "@gramio/types/params"; import type { TelegramLabeledPrice } from "@gramio/types/objects"; const invoiceParams: SendInvoiceParams = { chat_id: 12345, title: "Premium Subscription", description: "1 month of premium features", payload: "premium_1mo_user123", currency: "USD", prices: [ { label: "Subscription", amount: 999 }, // $9.99 { label: "Tax", amount: 100 } // $1.00 ] as TelegramLabeledPrice[], provider_token: "STRIPE_PROVIDER_TOKEN" }; await api.sendInvoice(invoiceParams); ``` -------------------------------- ### Tree-Shaking Example with Gramio Types Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Demonstrates how to import specific types from '@gramio/types' to enable tree-shaking. Only necessary types are imported, allowing bundlers to remove unused code in production builds. ```typescript // Only imports what's needed import type { TelegramUser } from "@gramio/types/objects" ``` -------------------------------- ### Example Usage: getUpdates API Method Source: https://github.com/gramiojs/types/blob/main/_autodocs/03-api-methods-reference.md Demonstrates calling an API method with optional parameters, such as getUpdates. It can be called with or without parameters like offset. ```typescript const updates = await api.getUpdates(); // or const updates = await api.getUpdates({ offset: 42 }); ``` -------------------------------- ### Command Handler Framework in TypeScript Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Implement a command handling system for your bot. This example defines interfaces for command contexts and handlers, allowing for organized processing of incoming commands. ```typescript import type { APIMethods, TelegramMessage, TelegramUser } from "@gramio/types"; interface CommandContext { api: APIMethods; message: TelegramMessage; user: TelegramUser; args: string[]; } type CommandHandler = (ctx: CommandContext) => Promise; const commands: Record = { start: async (ctx) => { await ctx.api.sendMessage({ chat_id: ctx.message.chat.id, text: `Welcome, ${ctx.user.first_name}!` }); }, help: async (ctx) => { await ctx.api.sendMessage({ chat_id: ctx.message.chat.id, text: "Available commands: /start, /help", parse_mode: "Markdown" }); } }; async function handleMessage(api: APIMethods, message: TelegramMessage) { const text = message.text || ""; if (!text.startsWith("/")) return; const [cmd, ...args] = text.slice(1).split(" "); const handler = commands[cmd]; if (!handler) { await api.sendMessage({ chat_id: message.chat.id, text: "Unknown command" }); return; } await handler({ api, message, user: message.from!, args }); } ``` -------------------------------- ### Direct Git Reference for Dependency Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Specifies a dependency using a direct Git reference, allowing users to install directly from a GitHub repository tag. ```json { "dependencies": { "@gramio/types": "github:gramiojs/types#v10.1.0" } } ``` -------------------------------- ### Example Usage: sendMessage API Method Source: https://github.com/gramiojs/types/blob/main/_autodocs/03-api-methods-reference.md Demonstrates calling an API method that requires parameters, such as sendMessage. It takes SendMessageParams and returns a Promise of TelegramMessage. ```typescript const msg = await api.sendMessage({ chat_id: 123, text: "hello" }); ``` -------------------------------- ### Webhook Setup with Secret Token Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Illustrates how to configure a webhook for receiving updates from Telegram, including setting a secret token for security. This uses the SetWebhookParams type for precise configuration. ```typescript import type { SetWebhookParams } from "@gramio/types/params"; const params: SetWebhookParams = { url: "https://bot.example.com/webhook", secret_token: "super_secret_token_abc123", max_connections: 100, allowed_updates: [ "message", "edited_message", "callback_query", "inline_query", "poll" ] }; await api.setWebhook(params); ``` -------------------------------- ### Sending Photo with Inline Keyboard Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Shows how to send a photo with a caption and an inline keyboard using the SendPhotoParams type. This example demonstrates structuring the reply_markup for interactive buttons. ```typescript import type { SendPhotoParams } from "@gramio/types/params"; import type { TelegramInlineKeyboardMarkup, TelegramInlineKeyboardButton } from "@gramio/types/objects"; const params: SendPhotoParams = { chat_id: 12345, photo: "https://example.com/photo.jpg", caption: "Check this out!", parse_mode: "HTML", reply_markup: { inline_keyboard: [[ { text: "Click me", callback_data: "button_1" }, { text: "Or me", callback_data: "button_2" } ]] } as TelegramInlineKeyboardMarkup }; await api.sendPhoto(params); ``` -------------------------------- ### Generator Pipeline Overview Source: https://github.com/gramiojs/types/blob/main/CLAUDE.md This diagram illustrates the generator pipeline, starting with fetching the custom schema from '@gramio/schema-parser'. The process is orchestrated by 'src/index.ts', which applies manual patches and then calls generation functions for objects, parameters, and API methods, outputting to 'out/' directory. ```text getCustomSchema() ← @gramio/schema-parser (fetches live Telegram docs) │ ▼ src/index.ts ← orchestrates everything ├─ applies manual patches (Currencies, APIResponse*, InputFile, button styling) └─ calls entities/ ├─ Objects.generateMany() → out/objects.d.ts ├─ Params.generateMany() → out/params.d.ts ├─ APIMethods.generateMany() → out/methods.d.ts └─ (header/utils built inline) ``` -------------------------------- ### ChatMember Type Guard Example Source: https://github.com/gramiojs/types/blob/main/_autodocs/10-advanced-topics.md Provides an example of using type guards with the discriminated union for TelegramChatMember. It demonstrates how to narrow down the type based on the 'status' field to access specific properties. ```typescript const member = await api.getChatMember({ chat_id, user_id }) as TelegramChatMember if (member.status === "administrator") { // member is now TelegramChatMemberAdministrator console.log(member.can_delete_messages) } if (member.status === "restricted") { // member is now TelegramChatMemberRestricted console.log(member.permissions.can_send_messages) } ``` -------------------------------- ### Creating a Type-Safe Telegram Bot API Wrapper Source: https://github.com/gramiojs/types/blob/main/README.md Implement a custom, type-safe Telegram Bot API wrapper using APIMethods, APIMethodParams, and TelegramAPIResponse. This example demonstrates how to create a proxy to handle API requests dynamically. ```typescript import type { APIMethods, APIMethodParams, TelegramAPIResponse, } from "@gramio/types"; const TBA_BASE_URL = "https://api.telegram.org/bot"; const TOKEN = ""; const api = new Proxy({} as APIMethods, { get: (_target: APIMethods, method: T) => async (params: APIMethodParams) => { const response = await fetch(`${TBA_BASE_URL}${TOKEN}/${method}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(params), }); const data = (await response.json()) as TelegramAPIResponse; if (!data.ok) throw new Error(`Some error occurred in ${method}`); return data.result; }, }); api.sendMessage({ chat_id: 1, text: "message", }); ``` -------------------------------- ### Optional vs. Required Parameters Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Explains how TypeScript interfaces reflect API requirements for optional and required parameters, with examples for `GetUpdatesParams`, `DeleteMessageParams`, and `SendMessageParams`. ```APIDOC ## Optional vs. Required Parameters The TypeScript interface accurately reflects API requirements: ```typescript // All optional export interface GetUpdatesParams { offset?: number // ? limit?: number // ? timeout?: number // ? } // All required export interface DeleteMessageParams { chat_id: number | string // No ? message_id: number // No ? } // Mixed export interface SendMessageParams { chat_id: number | string // Required text: string | { toString(): string } // Required parse_mode?: "HTML" | "MarkdownV2" | "Markdown" // Optional } ``` ``` -------------------------------- ### TypeScript Definition File Header Example Source: https://github.com/gramiojs/types/blob/main/_autodocs/02-entry-points-and-imports.md Examine the header comment block in generated .d.ts files. It includes module descriptions, API version, release date, and generation timestamps, linking types to official Telegram Bot API documentation. ```typescript /** * @module * * This module contains [Objects](https://core.telegram.org/bots/api#available-types) with the `Telegram` prefix * * @example import object * ```typescript * import { TelegramUser } from "@gramio/types/objects"; * ``` * * Based on Bot API v10.1 (11.06.2026) * * Generated at 11.06.2026, 18:06:00 using [types] and [schema] generators */ ``` -------------------------------- ### Package.json Export Configuration Source: https://github.com/gramiojs/types/blob/main/_autodocs/02-entry-points-and-imports.md Configure package.json to define entry points for different module paths, enabling specific imports like './objects' or './methods'. This setup ensures correct resolution of TypeScript definition files. ```json { "types": "./out/index.d.ts", "typings": "./out/index.d.ts", "exports": { ".": { "types": "./out/index.ts" }, "./*": { "types": "./out/*.d.ts" } } } ``` -------------------------------- ### Directly Import Pre-generated Types Source: https://github.com/gramiojs/types/blob/main/_autodocs/02-entry-points-and-imports.md Use this pattern to directly import specific types like APIMethods and SendMessageParams for immediate use in your code. Ensure you have the @gramio/types package installed. ```typescript import type { APIMethods, SendMessageParams } from "@gramio/types"; const api = {} as APIMethods; await api.sendMessage({ chat_id: 123, text: "hi" }); ``` -------------------------------- ### Custom Wrapper Implementation for API Calls Source: https://github.com/gramiojs/types/blob/main/_autodocs/02-entry-points-and-imports.md Implement a custom wrapper function to abstract API calls. This example shows how to create a generic function that accepts a method name and parameters, then makes a fetch request. It requires types for APIMethods and APIMethodParams. ```typescript import type { APIMethods, APIMethodParams } from "@gramio/types"; async function callAPI( method: T, params: APIMethodParams ): Promise { const response = await fetch(`/api/${method}`, { method: "POST", body: JSON.stringify(params), }); return response.json(); } ``` -------------------------------- ### Access Telegram Objects and Params via Namespace Source: https://github.com/gramiojs/types/blob/main/_autodocs/README.md Objects and parameters are exposed as namespaces for organized access. This example shows how to alias a specific user type and a send message parameter type. ```typescript import type { TelegramObjects, TelegramParams } from "@gramio/types"; type User = TelegramObjects.TelegramUser; type Params = TelegramParams.SendMessageParams; ``` -------------------------------- ### Import All Types from @gramio/types Source: https://github.com/gramiojs/types/blob/main/_autodocs/02-entry-points-and-imports.md Use this entry point to import all available types, methods, parameters, and utilities from the package. ```typescript import { APIMethods, APIMethodParams, APIMethodReturn, TelegramUser, TelegramMessage, SendMessageParams, TelegramParams, TelegramObjects, } from "@gramio/types"; ``` -------------------------------- ### Field Type Transformations Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Details the transformations applied by the `fieldToType()` resolver, mapping schema types to their transformed equivalents with examples. ```APIDOC ## Field Type Transformations The `fieldToType()` resolver applies several transformations: | Schema Type | Transforms To | Example | |-------------|---------------|---------| | `string` with key `parse_mode` | `"HTML" \| "MarkdownV2" \| "Markdown"` | `parse_mode` field | | `string` with `semanticType:"formattable"` | `string \| { toString(): string }` | Text fields | | `string` with enum | Named union type | `action` in `SendChatActionParams` | | `integer` with enum | Named union type (number values) | `TelegramDice.value` | | `reference` to markup type | Union with `{ toJSON() }` | `reply_markup` | | `array` of updateType | `Exclude[]` | `allowed_updates` | | File type | `Blob` | Photo/audio/video fields | ``` -------------------------------- ### Enum Union Type Aliases Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Demonstrates how named union types are generated for parameters with a restricted set of values, using `SendChatActionAction` as an example. ```APIDOC ## Enum Union Type Aliases When a parameter field has a restricted set of values, a named union is generated: ```typescript // In SendChatActionParams, the action field has fixed values: export type SendChatActionAction = | "typing" | "upload_photo" | "record_video" | "upload_video" | "record_audio" | "upload_audio" | "upload_document" | "find_location" | "record_video_note" | "upload_video_note" export interface SendChatActionParams { chat_id: number | string action: SendChatActionAction message_thread_id?: number } ``` ``` -------------------------------- ### Run npm Scripts with Bun Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Execute any script defined in your package.json using Bun as the task runner. ```bash bun ``` -------------------------------- ### Importing Method Parameters Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Demonstrates three ways to import parameter types: direct import, namespace import, and via the main export. Choose the method that best suits your project's import strategy. ```typescript // Direct import import type { SendMessageParams, GetUpdatesParams } from "@gramio/types/params"; // Namespace import import type * as Params from "@gramio/types/params"; const params: Params.SendMessageParams = { ... }; // Via main export import type { TelegramParams } from "@gramio/types"; const p: TelegramParams.SendMessageParams = { ... }; ``` -------------------------------- ### Basic Usage of @gramio/types Source: https://github.com/gramiojs/types/blob/main/_autodocs/README.md Demonstrates basic usage by sending a message and leveraging type inference for the response. Ensure you have imported the necessary types. ```typescript import type { APIMethods, TelegramMessage } from "@gramio/types"; const api = {} as APIMethods; const msg = await api.sendMessage({ chat_id: 123, text: "Hello, Telegram!" }); // msg is correctly typed as TelegramMessage ``` -------------------------------- ### InlineQueryResult Type Narrowing Example Source: https://github.com/gramiojs/types/blob/main/_autodocs/10-advanced-topics.md Demonstrates type narrowing for the TelegramInlineQueryResult union. By checking the 'type' field, you can safely access properties specific to each result variant. ```typescript const results: TelegramInlineQueryResult[] = [ { type: "article", id: "1", title: "...", input_message_content: {...} }, { type: "photo", id: "2", photo_url: "...", thumbnail_url: "..." }, { type: "video", id: "3", video_url: "...", mime_type: "video/mp4", ... } ] // Type narrowing: results.forEach(result => { if (result.type === "article") { console.log(result.title) // ✓ valid for article } }) ``` -------------------------------- ### Clean Build of Gramio Types Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Removes all previously generated files and regenerates them from a fresh schema fetch. This ensures a clean state before rebuilding. ```bash rm -rf out/ bun generate ``` -------------------------------- ### Manual npm Publish Command Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Publishes the current package.json version and ./out/ files to npm. Requires npm auth configured and all out/*.d.ts files generated. ```bash npm publish ``` -------------------------------- ### Poll Creation in TypeScript Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Create a regular poll in a chat. This example demonstrates how to structure the `SendPollParams` object with question and options, and then send it using the `sendPoll` API method. ```typescript import type { SendPollParams } from "@gramio/types/params"; import type { TelegramInputPollOption } from "@gramio/types/objects"; const pollParams: SendPollParams = { chat_id: 12345, question: "Which framework do you prefer?", options: [ { text: "TypeScript" }, { text: "JavaScript" }, { text: "Other" } ] as TelegramInputPollOption[], is_anonymous: false, type: "regular", allows_multiple_answers: false }; const message = await api.sendPoll(pollParams); console.log(`Poll created: ${message.poll?.id}`); ``` -------------------------------- ### File Upload Pattern Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Demonstrates how to send files using either a file ID or by uploading binary data as a Blob. This pattern is applicable for parameters like `photo`, `audio`, `document`, etc. ```typescript await api.sendPhoto({ chat_id: 123, photo: "AgACAgIAAxkBAAI..." }); ``` ```typescript const file = new Blob([buffer], { type: "image/jpeg" }); await api.sendPhoto({ chat_id: 123, photo: file }); ``` -------------------------------- ### Importing Parameter Types Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Demonstrates various ways to import parameter types for Telegram Bot API methods. ```APIDOC ## Importing Params ```typescript // Direct import import type { SendMessageParams, GetUpdatesParams } from "@gramio/types/params"; // Namespace import import type * as Params from "@gramio/types/params"; const params: Params.SendMessageParams = { ... }; // Via main export import type { TelegramParams } from "@gramio/types"; const p: TelegramParams.SendMessageParams = { ... }; ``` ``` -------------------------------- ### Importing GramioJS Object Types Source: https://github.com/gramiojs/types/blob/main/_autodocs/04-types-and-objects.md Demonstrates different ways to import object types from the @gramio/types library, including direct imports, namespace imports, and via the main export. ```typescript import type { TelegramUser, TelegramMessage } from "@gramio/types/objects"; ``` ```typescript // Namespace import import type * as Objects from "@gramio/types/objects"; const user: Objects.TelegramUser = { ... }; ``` ```typescript // Via main export import type { TelegramObjects } from "@gramio/types"; const msg: TelegramObjects.TelegramMessage = { ... }; ``` -------------------------------- ### Get Updates via Polling with GramioJS Source: https://github.com/gramiojs/types/blob/main/_autodocs/QUICK-REFERENCE.md Use `getUpdates` to fetch new messages and events. Specify `offset` to avoid processing old updates and `allowed_updates` to filter event types. ```typescript const updates = await api.getUpdates({ offset: lastUpdateId, timeout: 30, allowed_updates: ["message", "callback_query"] }) ``` -------------------------------- ### Chat Member Inspection in TypeScript Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Check a user's administrative status or retrieve their permissions within a chat. This example uses `getChatMember` and type guards to discriminate between different member statuses. ```typescript import type { APIMethods, TelegramChatMember } from "@gramio/types"; async function isMemberAdmin(api: APIMethods, chatId: number, userId: number): Promise { const member = await api.getChatMember({ chat_id: chatId, user_id: userId }) as TelegramChatMember; // Type guard for union type return member.status === "administrator" || member.status === "creator"; } async function getMemberPermissions(api: APIMethods, chatId: number, userId: number) { const member = await api.getChatMember({ chat_id: chatId, user_id: userId }) as TelegramChatMember; // Discriminate by status if (member.status === "administrator") { return { canDeleteMessages: member.can_delete_messages, canRestrictMembers: member.can_restrict_members, canPromoteMembers: member.can_promote_members }; } if (member.status === "restricted") { return { canSendMessages: member.permissions.can_send_messages, canSendMedia: member.permissions.can_send_media_messages }; } return {}; } ``` -------------------------------- ### Using Markup Type Builder with `toJSON()` Source: https://github.com/gramiojs/types/blob/main/_autodocs/10-advanced-topics.md Demonstrates how keyboard markups can be integrated with builder patterns by implementing a `toJSON()` method. This allows objects to be used where a specific markup type is expected. ```typescript // In generated params: reply_markup?: | TelegramInlineKeyboardMarkup | { toJSON(): TelegramInlineKeyboardMarkup } | TelegramReplyKeyboardMarkup | { toJSON(): TelegramReplyKeyboardMarkup } | // ... more markup types ``` ```typescript import { Keyboard } from "@gramio/keyboards" const keyboard = new Keyboard().text("Click").row().text("Me") // keyboard.toJSON() returns TelegramReplyKeyboardMarkup await api.sendMessage({ chat_id: 123, text: "Pick:", reply_markup: keyboard // Accepted via union }) ``` -------------------------------- ### SetWebhookParams Interface Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Parameters for setting up a webhook. Requires a `url` for receiving updates. Optionally provide `certificate`, `ip_address`, `max_connections`, `allowed_updates`, `drop_pending_updates`, and `secret_token` for advanced configuration. ```typescript export interface SetWebhookParams { url: string certificate?: TelegramInputFile ip_address?: string max_connections?: number allowed_updates?: Exclude[] drop_pending_updates?: boolean secret_token?: string } ``` -------------------------------- ### Running the Type Generation Script Source: https://github.com/gramiojs/types/blob/main/README.md Execute the 'bun generate' command to automatically generate the Telegram Bot API types based on the latest schema. The generated types will be placed in the 'out' folder. ```bash bun generate ``` -------------------------------- ### Integrating @gramio/keyboards with SendMessageParams Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Demonstrates how to use the @gramio/keyboards builder to create a reply markup for the sendMessage method, leveraging its toJSON() implementation. ```typescript import { Keyboard } from "@gramio/keyboards"; import type { SendMessageParams } from "@gramio/types/params"; const params: SendMessageParams = { chat_id: 12345, text: "Pick an option:", reply_markup: new Keyboard() .text("Option 1") .row() .text("Option 2") .text("Option 3") // The Keyboard builder implements toJSON(), so it works in the union type }; await api.sendMessage(params); ``` -------------------------------- ### GetUpdatesParams Interface Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Parameters for fetching updates. Use `offset` to specify the starting point and `limit` to control the number of updates returned. `timeout` sets a long polling timeout, and `allowed_updates` filters which update types are received. ```typescript export interface GetUpdatesParams { offset?: number limit?: number timeout?: number allowed_updates?: Exclude[] } ``` -------------------------------- ### Dynamic Parameter Lookup Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Explains how to use the `APIMethodParams` utility type to dynamically retrieve parameter types for any API method. ```APIDOC ## Dynamic Param Lookup Use the utility type `APIMethodParams` to extract params for any method: ```typescript import type { APIMethodParams } from "@gramio/types/utils"; // Get params type for sendMessage type Params = APIMethodParams<"sendMessage">; // = SendMessageParams // This works for any method: type GetParams = APIMethodParams<"getUpdates">; // = GetUpdatesParams ``` ``` -------------------------------- ### User Information Methods Source: https://github.com/gramiojs/types/blob/main/_autodocs/03-api-methods-reference.md Methods for retrieving and managing bot information and user details. ```APIDOC ## getMe ### Description Retrieves information about the bot itself. ### Method `getMe` ### Params None ### Returns `TelegramUser` ### Notes `CallAPIWithoutParams` ``` ```APIDOC ## getMyDescription ### Description Retrieves the bot's description. ### Method `getMyDescription` ### Params `GetMyDescriptionParams` (optional) ### Returns `TelegramBotDescription` ### Notes `CallAPIWithOptionalParams` ``` ```APIDOC ## setMyDescription ### Description Sets the bot's description. ### Method `setMyDescription` ### Params `SetMyDescriptionParams` (optional) ### Returns `true` ### Notes `CallAPIWithOptionalParams` ``` ```APIDOC ## getMyShortDescription ### Description Retrieves the bot's short description. ### Method `getMyShortDescription` ### Params `GetMyShortDescriptionParams` (optional) ### Returns `TelegramBotShortDescription` ### Notes `CallAPIWithOptionalParams` ``` ```APIDOC ## setMyShortDescription ### Description Sets the bot's short description. ### Method `setMyShortDescription` ### Params `SetMyShortDescriptionParams` (optional) ### Returns `true` ### Notes `CallAPIWithOptionalParams` ``` ```APIDOC ## getMyCommands ### Description Retrieves the list of bot commands. ### Method `getMyCommands` ### Params `GetMyCommandsParams` (optional) ### Returns `TelegramBotCommand[]` ### Notes `CallAPIWithOptionalParams` ``` ```APIDOC ## setMyCommands ### Description Sets the list of bot commands. ### Method `setMyCommands` ### Params `SetMyCommandsParams` ### Returns `true` ### Notes Requires at least `commands` param. ``` ```APIDOC ## deleteMyCommands ### Description Deletes the list of bot commands. ### Method `deleteMyCommands` ### Params `DeleteMyCommandsParams` (optional) ### Returns `true` ### Notes `CallAPIWithOptionalParams` ``` -------------------------------- ### Callback Query Methods Source: https://github.com/gramiojs/types/blob/main/_autodocs/03-api-methods-reference.md Methods for responding to callback queries, typically from inline keyboards. ```APIDOC ## answerCallbackQuery ### Description Respond to a button click in an inline keyboard. ### Method `answerCallbackQuery` ### Params `AnswerCallbackQueryParams` ### Returns `true` ``` -------------------------------- ### Answer Callback Query with GramioJS Source: https://github.com/gramiojs/types/blob/main/_autodocs/QUICK-REFERENCE.md Respond to user interactions with inline keyboard buttons using `answerCallbackQuery`. Optionally display a notification text. ```typescript await api.answerCallbackQuery({ callback_query_id: query.id, text: "Button clicked!", show_alert: false }) ``` -------------------------------- ### File Management Methods Source: https://github.com/gramiojs/types/blob/main/_autodocs/03-api-methods-reference.md Methods for retrieving file information and uploading files. ```APIDOC ## getFile ### Description Get information about a file for download. ### Method `getFile` ### Params `GetFileParams` ### Returns `TelegramFile` ``` ```APIDOC ## uploadStickerFile ### Description Upload a sticker image file. ### Method `uploadStickerFile` ### Params `UploadStickerFileParams` ### Returns `TelegramFile` ``` -------------------------------- ### Simple Message Sending with Type-Safe API Wrapper Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Shows how to create a basic message sending function using the APIMethods interface for type safety. Ensure the APIMethods interface is correctly implemented or mocked. ```typescript import type { APIMethods, TelegramMessage } from "@gramio/types"; const api = {} as APIMethods; async function sendMessage(chatId: number, text: string): Promise { return api.sendMessage({ chat_id: chatId, text: text, }); } // Usage const msg = await sendMessage(12345, "Hello, Telegram!"); console.log(msg.message_id, msg.text); ``` -------------------------------- ### Package.json Configuration for Publishing Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Configure the 'package.json' file to specify which files are published to npm. This ensures only the generated type definitions from the 'out/' directory are included in the published package. ```json { "files": ["out"], "types": "./out/index.d.ts", "typings": "./out/index.d.ts", "exports": { ".": { "types": "./out/index.d.ts" }, "./*": { "types": "./out/*.d.ts" } } } ``` -------------------------------- ### Markup Types with toJSON() in GramioJS Source: https://github.com/gramiojs/types/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how keyboard markup in GramioJS supports a builder pattern by accepting types with a toJSON() method, ensuring compatibility with various keyboard structures. ```typescript reply_markup: | TelegramInlineKeyboardMarkup | { toJSON(): TelegramInlineKeyboardMarkup } // ... more keyboard types ``` -------------------------------- ### Manual JSR Publish Command Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Publishes the package to JSR after running the JSR release script. Can be done via Deno CLI or JSR CLI. ```bash deno publish ``` ```bash jsr publish ``` -------------------------------- ### Run Generator and Linter Commands Source: https://github.com/gramiojs/types/blob/main/CLAUDE.md These bash commands are used to manage the code generation and linting processes within the repository. 'bun generate' runs the code generator, 'bun lint' checks for linting issues, 'bun lint:fix' automatically resolves them, 'bun cicd' handles CI/CD tasks like schema hashing and version bumping, and 'bun jsr' prepares for publishing to JSR. ```bash bun generate # Run the generator — writes to out/ bun lint # Biome lint check on src/ bun lint:fix # Auto-fix lint issues bun cicd # Hash-check schema, bump version, write GITHUB_OUTPUT (CI use) bun jsr # Prepare JSR publish: sync version + copy out/*.d.ts → source/*.ts ``` -------------------------------- ### Applied Prefixed Object Names Source: https://github.com/gramiojs/types/blob/main/_autodocs/10-advanced-topics.md Illustrates how the configured object prefix is applied during type generation to create unique and descriptive type names. ```typescript const name = OBJECTS_PREFIX + object.name // "Telegram" + "User" = "TelegramUser" ``` -------------------------------- ### Main Code Generation Logic Source: https://github.com/gramiojs/types/blob/main/_autodocs/06-code-generator-api.md The main entry point for the code generator. It fetches a schema, builds markup types, generates various definition files (objects, params), and writes them to the output path, formatted with Prettier. ```typescript // Fetch schema from @gramio/schema-parser const schema = await getCustomSchema() // Build markup type set const markupTypes = new Set( schema.objects .filter(o => o.semanticType === "markup") .map(o => o.name) ) // Generate all files const files: IGeneratedFile[] = [ { name: "objects.d.ts", lines: [header(...), imports, Objects.generateMany(schema.objects, markupTypes)] }, { name: "params.d.ts", lines: [header(...), imports, Params.generateMany(schema.methods, markupTypes)] }, // ... methods.d.ts, index.d.ts, utils.d.ts ] // Write files (formatted with Prettier) for (const file of files) { await fs.writeFile(`${OUTPUT_PATH}/${file.name}`, await prettier.format(file.lines.flat().join("\n"), PRETTIER_OPTIONS) ) } ``` -------------------------------- ### Markup Type Generation with toJSON() Source: https://github.com/gramiojs/types/blob/main/_autodocs/08-schema-parsing-and-validation.md Illustrates how markup types are generated to include a `toJSON()` builder pattern, enabling correct serialization for libraries like `@gramio/keyboards`. ```typescript // Instead of: reply_markup?: TelegramInlineKeyboardMarkup // Generated as: reply_markup?: | TelegramInlineKeyboardMarkup | { toJSON(): TelegramInlineKeyboardMarkup } ``` -------------------------------- ### Verify API Method and Object Types Source: https://github.com/gramiojs/types/blob/main/_autodocs/QUICK-REFERENCE.md Import APIMethods to verify types for API calls like getMe and getUpdates. Ensure types are correctly loaded for TelegramUser and TelegramUpdate. ```typescript import type { APIMethods } from "@gramio/types" // Verify types are loaded const api = {} as APIMethods const result = await api.getMe() // result is TelegramUser const updates = await api.getUpdates() // updates is TelegramUpdate[] ``` -------------------------------- ### Keyboard/Markup Parameters Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Parameter for attaching custom keyboards or reply interfaces to messages. ```APIDOC ## Keyboard/Markup ### Parameters - **reply_markup** (`Union of keyboard types`) - Optional - Specifies custom reply keyboards or inline keyboards. Union allows `{ toJSON() }` builder: ```typescript reply_markup?: | TelegramInlineKeyboardMarkup | { toJSON(): TelegramInlineKeyboardMarkup } | TelegramReplyKeyboardMarkup | { toJSON(): TelegramReplyKeyboardMarkup } | TelegramReplyKeyboardRemove | { toJSON(): TelegramReplyKeyboardRemove } | TelegramForceReply | { toJSON(): TelegramForceReply } ``` ``` -------------------------------- ### Fetch Telegram Bot API Schema Source: https://github.com/gramiojs/types/blob/main/_autodocs/08-schema-parsing-and-validation.md Imports and uses `getCustomSchema` from `@gramio/schema-parser` to fetch and parse the live Telegram Bot API documentation. ```typescript import { getCustomSchema } from "@gramio/schema-parser"; const schema = await getCustomSchema(); // Fetches live Telegram Bot API documentation and parses it ``` -------------------------------- ### Import Utility Types from @gramio/types/utils Source: https://github.com/gramiojs/types/blob/main/_autodocs/02-entry-points-and-imports.md Import utility types like APIMethodParams and APIMethodReturn for dynamically inferring method parameter and return types. These are essential for advanced type introspection. ```typescript import type { APIMethodParams, APIMethodReturn } from "@gramio/types/utils"; type GetMeReturn = APIMethodReturn<"getMe">; // TelegramUser type SendMessageParams = APIMethodParams<"sendMessage">; // SendMessageParams ``` -------------------------------- ### Media File Parameters Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Parameters for sending various types of media files. Files can be uploaded as binary data or referenced by their file ID. ```APIDOC ## Media Files ### Parameters - **photo** (`TelegramInputFile | string`) - Required - Photo file to send. - **audio** (`TelegramInputFile | string`) - Required - Audio file to send. - **document** (`TelegramInputFile | string`) - Required - Document to send. - **video** (`TelegramInputFile | string`) - Required - Video file to send. - **animation** (`TelegramInputFile | string`) - Required - Animation (e.g., GIF) to send. - **voice** (`TelegramInputFile | string`) - Required - Voice message to send. - **video_note** (`TelegramInputFile | string`) - Required - Video note to send. - **media** (`TelegramInputFile | string`) - Required (in `InputMedia*`) - Media for grouped messages or edits. - **thumbnail** (`TelegramInputFile | string`) - Optional - Custom thumbnail for media. **File upload pattern:** Accept either a file ID (string) or binary data (Blob): ```typescript // File ID await api.sendPhoto({ chat_id: 123, photo: "AgACAgIAAxkBAAI..." }); // Upload const file = new Blob([buffer], { type: "image/jpeg" }); await api.sendPhoto({ chat_id: 123, photo: file }); ``` ``` -------------------------------- ### CreateNewStickerSetParams Interface Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Parameters for creating a new sticker set. Requires `user_id`, `name`, `title`, `sticker_format`, and `stickers`. `source` and `needs_repainting` offer additional customization options. ```typescript export interface CreateNewStickerSetParams { user_id: number name: string title: string sticker_format: "static" | "mask" | "custom_emoji" stickers: TelegramInputSticker[] source?: string needs_repainting?: boolean } ``` -------------------------------- ### Inline Queries Parameters Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Parameter interfaces for handling inline queries. ```APIDOC ## AnswerInlineQueryParams ### Description Parameters for the `answerInlineQuery` method. ### Parameters #### Request Body - **inline_query_id** (string) - Required - Unique identifier for the answered inline query. - **results** (TelegramInlineQueryResult[]) - Required - A JSON-array of results for the inline query. - **cache_time** (number) - Optional - The maximum amount of time in seconds that the result of the inline query may be cached on the server side. - **is_personal** (boolean) - Optional - Pass True, if results may be cached on the server side only for the user that sent the query. - **next_offset** (string) - Optional - If passed, another result will not be sent, but instead a message with a button will be sent to the user, which will open the inline query with the specified `next_offset`. - **button** (TelegramInlineQueryResultsButton) - Optional - An object representing a button to be shown above inline query results. ``` -------------------------------- ### Stickers Parameters Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Parameter interfaces for sticker set management. ```APIDOC ## CreateNewStickerSetParams ### Description Parameters for the `createNewStickerSet` method. ### Parameters #### Request Body - **user_id** (number) - Required - User identifier of the sticker set owner. - **name** (string) - Required - Short name of the sticker set. Should be unique for the user. - **title** (string) - Required - Sticker set title, 1-64 characters. - **sticker_format** (string) - Required - Format of the added stickers. Can be "static", "mask", or "custom_emoji". - **stickers** (TelegramInputSticker[]) - Required - A JSON-array of 1-50 stickers to be added to the set. See the documentation for details on how to format this. - **source** (string) - Optional - Source for the sticker set. Can be a URL or a file ID. - **needs_repainting** (boolean) - Optional - Pass True if the stickers in the set are not flat images and require the background to be removed. ``` -------------------------------- ### Parameter Documentation Structure Source: https://github.com/gramiojs/types/blob/main/_autodocs/05-method-params-reference.md Details the structure and content of parameter documentation, including JSDoc comments, field descriptions, and links to the official Telegram Bot API. ```APIDOC ## Parameter Documentation Each `*Params` interface includes: - JSDoc comment referencing the method: `Params object for {@link APIMethods.methodName | methodName} method` - Field descriptions from official Telegram Bot API documentation - Links to relevant object definitions All params are documented in https://core.telegram.org/bots/api#available-methods ``` -------------------------------- ### Inline Query Methods Source: https://github.com/gramiojs/types/blob/main/_autodocs/03-api-methods-reference.md Methods for handling inline queries and responding to web app interactions. ```APIDOC ## answerInlineQuery ### Description Respond to an inline query. ### Method `answerInlineQuery` ### Params `AnswerInlineQueryParams` ### Returns `true` ``` ```APIDOC ## answerWebAppQuery ### Description Respond to a web app button interaction. ### Method `answerWebAppQuery` ### Params `AnswerWebAppQueryParams` ### Returns `TelegramSentWebAppMessage` ``` -------------------------------- ### CI/CD Script Note on Schema Path Source: https://github.com/gramiojs/types/blob/main/CLAUDE.md This note highlights a potential issue in 'scripts/cicd.ts' where it still imports from an old Rust-schema path. If the Rust submodule is removed, this script will need to be updated to hash a different source, such as the live schema version string. ```text > **Note:** `scripts/cicd.ts` still imports `SCHEMA_FILE_PATH` and `IBotAPI` from the old Rust-schema path. If the Rust submodule (`tg-bot-api/`) is fully dropped in favour of `@gramio/schema-parser`, this script needs updating to hash something else (e.g. the live schema version string). ``` -------------------------------- ### JSR Release Script Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Runs the JSR release script. This script syncs versions, prepares source files for JSR, and validates the format. ```bash bun jsr ``` -------------------------------- ### Advanced Topics Source: https://github.com/gramiojs/types/blob/main/_autodocs/MANIFEST.txt Explanations of advanced concepts like generic types, discriminated unions, FormattableString, and type transformations. ```APIDOC ## 10-advanced-topics.md ### Description This document delves into advanced topics including generic types, discriminated unions, the FormattableString, and builder patterns, as well as advanced type transformations. ### Content - Generic types and discriminated unions - FormattableString and builder patterns - Advanced type transformations ``` -------------------------------- ### JSR Configuration Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Configuration file for JSR. Specifies the package name, version, and the main export file. ```json { "name": "@gramio/types", "version": "10.1.0", "exports": "./src/index.ts" } ``` -------------------------------- ### Check Code Style with Bun Lint Source: https://github.com/gramiojs/types/blob/main/_autodocs/09-build-and-publish.md Use this command to check the code style of the generator source code in ./src/ using Biome. It identifies style violations based on the biome.json configuration. ```bash bun lint ``` -------------------------------- ### Types and Objects Reference Source: https://github.com/gramiojs/types/blob/main/_autodocs/MANIFEST.txt Documentation for all Telegram object types, including type variants, unions, and special type handling. ```APIDOC ## 04-types-and-objects.md ### Description This file details all Telegram object types supported by the library, covering type variants, unions, and specific handling for special types. ### Content - All Telegram object types - Type variants and unions - Special type handling ``` -------------------------------- ### Runtime Method Inspection with APIMethods Source: https://github.com/gramiojs/types/blob/main/_autodocs/07-usage-examples.md Inspects all available API method names at runtime and checks for their existence. Logs the type of the first five methods found. ```typescript import type { APIMethods } from "@gramio/types/methods"; // Get all method names const methods = Object.keys({} as APIMethods) as Array; // Check if method exists function hasMethod(name: string): name is keyof APIMethods { return methods.includes(name as any); } // Log method signatures for (const method of methods.slice(0, 5)) { const fn = ({} as APIMethods)[method]; console.log(`${method}: ${typeof fn}`); } ``` -------------------------------- ### Import APIMethods from @gramio/types/methods Source: https://github.com/gramiojs/types/blob/main/_autodocs/02-entry-points-and-imports.md Import the APIMethods interface to access all Telegram Bot API method signatures. This is useful for type checking or dynamic method calls. ```typescript import type { APIMethods } from "@gramio/types/methods"; type SendMessageFn = APIMethods["sendMessage"]; // (params: SendMessageParams) => Promise ```