### Initialize and Use chatMembers Middleware Source: https://grammy.dev/ref/chat-members/chatmembers This example shows how to initialize the chatMembers middleware with a memory adapter and register it with your bot. Ensure you enable the 'chat_member' update type in your bot's start configuration. ```typescript const bot = new Bot(""); const adapter = new MemorySessionStorage(); bot.use(chatMembers(adapter)); bot.start({ allowed_updates: ["chat_member"] }); ``` -------------------------------- ### Example Plugin Configuration Source: https://grammy.dev/ref/conversations/conversationconfig Demonstrates how to configure a plugin within a ConversationConfig. This example shows how to use a transformer with the API configuration. ```typescript plugins: [async (ctx, next) => { ctx.api.config.use(transformer) await next() }] ``` -------------------------------- ### Install Commands Flavor Source: https://grammy.dev/ref/commands/commands Installs the commands flavor into the context. This is a generic type parameter that extends the base Context. ```typescript import { Context } from "grammy"; import { commands, Command } from "@grammyjs/commands"; type MyContext = Context & { // ... }; const bot = new Bot("YOUR_BOT_TOKEN"); bot.use(commands()); // Example command definition const startCommand: Command = { name: "start", handler: async (ctx) => { await ctx.reply("Hello!"); }, }; bot.command("start", startCommand); bot.start(); ``` -------------------------------- ### Select Input Form Field with Custom Keyboard Example Source: https://grammy.dev/ref/conversations/conversationform Defines a form field that accepts one of several predefined string options. This is particularly useful with custom keyboards. The example demonstrates setting up a keyboard with options and handling the user's selection. ```typescript select(entries: E[], options?: FormOptions); const keyboard = new Keyboard() .text("A").text("B") .text("C").text("D") .oneTime() await ctx.reply("A, B, C, or D?", { reply_markup: keyboard }) const answer = await conversation.form.select(["A", "B", "C", "D"], { otherwise: ctx => ctx.reply("Please use one of the buttons!") }) switch (answer) { case "A": case "B": case "C": case "D": // ... } ``` -------------------------------- ### Match Only At Start Option Source: https://grammy.dev/ref/commands/commandoptions Determines if a command should only be matched at the beginning of a message. Defaults to true. ```typescript matchOnlyAtStart: boolean; ``` -------------------------------- ### Create a basic conversational menu Source: https://grammy.dev/ref/conversations/conversation Create an interactive inline keyboard menu. This example shows how to define text buttons that reply or close the menu. ```typescript const menu = conversation.menu() .text("Send message", ctx => ctx.reply("Hi!")) .text("Close", ctx => ctx.menu.close()) await ctx.reply("Menu message", { reply_markup: menu }) ``` -------------------------------- ### Select between Options with Action Source: https://grammy.dev/ref/conversations/conversation This example uses `form.select` to wait for a specific string input ('Yes' or 'No') and defines an `action` to be performed when a valid input is received, such as deleting the message. ```typescript const text = await conversation.form.select(["Yes", "No"], { action: ctx => ctx.deleteMessage() }) ``` -------------------------------- ### Chaining WaitUntil Calls Source: https://grammy.dev/ref/conversations/conversation This example illustrates chaining multiple `waitUntil` calls to sequentially filter updates, first for messages ending with 'grammY' and then for those matching a '::hashtag' query. ```typescript const ctx = await conversation.waitUntil(ctx => ctx.msg?.text?.endsWith("grammY")) .andFor("::hashtag") ``` -------------------------------- ### Hydrate Chat Member Example Source: https://grammy.dev/ref/chat-members/hydratechatmember Demonstrates how to use the hydrateChatMember transformer to check if a chat member is an administrator. ```typescript const bot = new Bot>(""); bot.api.config.use(hydrateChatMember()); bot.on("message", async (ctx) => { const author = await ctx.getAuthor(); if (author.is("admin")) { author.status; // "creator" | "administrator" } }); ``` -------------------------------- ### Wait for a Number using Form Field Source: https://grammy.dev/ref/conversations/conversation This example shows how to use the `form.number` field to wait for a numeric input from the user and then reply with its square. ```typescript // Wait for a number const n = await conversation.form.number() // Send back its square await ctx.reply(`The square of ${n} is ${n * n}!`) ``` -------------------------------- ### Get Registered Prefixes Source: https://grammy.dev/ref/commands/commandgroup A getter that returns an array of all registered command prefixes. This can be useful for understanding how commands are structured or for debugging. ```typescript get prefixes(): string[]; ``` -------------------------------- ### halt Source: https://grammy.dev/ref/conversations/conversation Terminates the conversation immediately after calling any installed exit handlers. This method never returns. ```APIDOC ## halt ### Description Terminates the conversation immediately after calling any installed exit handlers. This method never returns. By default, this will consume the update. Pass `{ next: true }` to make sure that downstream middleware is called. ### Method `halt(options?: HaltOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript conversation.halt({ next: true }); ``` ### Response #### Success Response (never) This method never returns. #### Response Example None ``` -------------------------------- ### Get Registered Commands Source: https://grammy.dev/ref/commands/commandgroup A getter that returns an array of all registered Command objects. This allows inspection of the commands managed by the group. ```typescript get commands(): Command[]; ``` -------------------------------- ### Halt Conversation Immediately Source: https://grammy.dev/ref/conversations/conversation Use `halt` to stop the conversation and trigger any installed exit handlers. Pass `{ next: true }` to allow downstream middleware to execute. ```typescript halt(options: HaltOptions): Promise; ``` -------------------------------- ### Interact with conversation from menu button handlers Source: https://grammy.dev/ref/conversations/conversation Handle user input within menu button callbacks to update conversation state. This example demonstrates setting and clearing a name using `conversation.form.text()`. ```typescript let name = "" const menu = conversation.menu() .text("Set name", async ctx => { await ctx.reply("What's your name?") name = await conversation.form.text() await ctx.editMessageText(name) }) .text("Clear name", ctx => { name = "" await ctx.editMessageText("No name") }) await ctx.reply("No name (yet)", { reply_markup: menu }) ``` -------------------------------- ### Filter for Bot Entering a Group Source: https://grammy.dev/ref/chat-members/mychatmemberfilter Use `myChatMemberFilter` to listen for updates when the bot enters a group or supergroup. This example filters for transitions from 'out' to 'in' status. ```typescript bot.chatType(['group', 'supergroup']).filter( myChatMemberFilter('out', 'in'), (ctx) => { const { old_chat_member: oldChatMember, new_chat_member: newChatMember } = ctx.myChatMember; // ... }, ); ``` -------------------------------- ### Get current timestamp once Source: https://grammy.dev/ref/conversations/conversation Use `now()` to get a timestamp that remains constant during replays. Prefer this over `Date.now()`. ```typescript now(); ``` -------------------------------- ### Get random number once Source: https://grammy.dev/ref/conversations/conversation Use `random()` to get a random number that remains constant during replays. Prefer this over `Math.random()`. ```typescript random(); ``` -------------------------------- ### Command Constructor with Handler Source: https://grammy.dev/ref/commands/command Initializes a new command with a name, description, and a handler. This command needs to be added to a CommandGroup to function. ```typescript Command( name: string | RegExp, description: string, handler: MaybeArray>>, options?: Partial, ); ``` -------------------------------- ### Create SetMyCommandsParams from CommandGroup Source: https://grammy.dev/ref/commands/mycommandparams Use the `from` static method to merge and serialize one or more `CommandGroup` instances into an array of commands parameters. This array can then be used to set the commands menu displayed to the user. ```typescript from(commands: CommandGroup[], chat_id: BotCommandScopeChat["chat_id"]) ``` -------------------------------- ### CommandGroup Constructor Source: https://grammy.dev/ref/commands/commandgroup Initializes a new CommandGroup instance. Options are partial and can configure command behavior. ```typescript new CommandGroup(options: Partial); ``` -------------------------------- ### Command Method: isApiCompliant Source: https://grammy.dev/ref/commands/command Checks if the command can be used with the `setMyCommands` API. Returns true if compliant, or an array with false and reasons if not. ```typescript isApiCompliant(language?: LanguageCode | "default"): [true] | [false, string[]]; ``` -------------------------------- ### Command Constructor Overload Source: https://grammy.dev/ref/commands/command An alternative constructor signature for initializing a command, potentially with a handler or options. ```typescript Command( name: string | RegExp, description: string, handlerOrOptions?: MaybeArray>> | Partial, options?: Partial, ); ``` -------------------------------- ### Command Method: middleware Source: https://grammy.dev/ref/commands/command Returns the middleware associated with this command. ```typescript middleware(); ``` -------------------------------- ### Static Method: findMatchingCommand Source: https://grammy.dev/ref/commands/command Finds a command that matches the provided input within the given context and options. ```typescript findMatchingCommand( command: MaybeArray, options: CommandOptions, ctx: Context, ): CommandMatch | null; ``` -------------------------------- ### commandMatch Source: https://grammy.dev/ref/commands/commandsflavor Provides information about the matched command and the remaining input. If the matched command is a regular expression, a `match` property will expose the result of the RegExp match. ```APIDOC ## commandMatch ### Description The matched command and the rest of the input. When matched command is a RegExp, a `match` property exposes the result of the RegExp match. ### Method (Property access) ### Parameters None ### Request Example ```typescript // Example usage const matchResult = bot.api.commandMatch; console.log(matchResult.command); console.log(matchResult.text); if (matchResult.match) { console.log(matchResult.match); } ``` ### Response #### Success Response - **CommandMatch**: An object containing the matched command and remaining text, potentially with RegExp match details. #### Response Example ```json { "example": { "command": "/greet", "text": "hello there", "match": ["hello there", "arg1", "arg2"] } } ``` ``` -------------------------------- ### Get Active Conversation Counts Source: https://grammy.dev/ref/conversations/conversationcontrols Returns an object detailing the number of active instances for each conversation identifier in the current chat. This helps in monitoring the state of parallel conversations. ```typescript { captcha: 3, settings: 1, } ``` -------------------------------- ### enter Source: https://grammy.dev/ref/conversations/conversationcontrols Enters a conversation with a specified identifier. This method initiates the conversation flow and runs it until the first wait call. Arguments passed to this method are JSON-serialized and stored, and will be available when the conversation is replayed. Be cautious as there is no type safety for conversation arguments. ```APIDOC ## enter ### Description Enters the conversation with the given identifier. By default, the name of the function is the identifier of the function. You can override this value when calling createConversation. Entering a conversation will make the conversation run partially until the first wait call is reached. The enter call will therefore return long before the conversation has returned. You can pass any number of arguments when entering a conversation. These arguments will be serialized to JSON and persisted in the storage as `string`. Whenever the conversation is replayed, this string is parsed back to objects and supplied to the conversation. This means that all arguments must be JSON-serializable. Be careful: There is no type safety for conversation arguments! You must annotate the correct types in the function signature of the conversation builder function, and you also have to make sure that you pass matching values to `enter`. This method will throw an error if the same or a different conversation has already been entered. If you want to enter a conversations in parallel to existing active conversations, you can mark it as parallel. This can be done by passig `{ parallel: true }` to createConversation. ### Method `enter(name: string, ...args: unknown[]): Promise` ### Parameters #### Path Parameters - **name** (string) - Required - The identifier of the conversation to enter. - **args** (unknown[]) - Optional - Any number of JSON-serializable arguments to pass to the conversation. ### Request Example ```typescript // Enters a conversation called "convo" upon a start command. bot.command("start", async ctx => { await ctx.conversation.enter("convo", 42, "cool", { args: [2, 1, 0] }) }) async function convo(conversation, ctx, num, str, { args }) { // ... } ``` ``` -------------------------------- ### Wait Until Message Ends with Specific Text Source: https://grammy.dev/ref/conversations/conversation This example shows how to use `waitUntil` with a predicate to wait for a message that ends with 'grammY', including an `otherwise` handler for invalid messages. ```typescript const ctx = await conversation.waitUntil(ctx => ctx.msg?.text?.endsWith("grammY"), { otherwise: ctx => ctx.reply("Send a message that ends with grammY!") }) ``` -------------------------------- ### Command Method: localize Source: https://grammy.dev/ref/commands/command Adds a new translation for the command, specifying the language code, name, and description. ```typescript localize( languageCode: LanguageCode, name: string | RegExp, description: string, ); ``` -------------------------------- ### Command Getter: hasCustomPrefix Source: https://grammy.dev/ref/commands/command A getter that returns a boolean indicating whether the command has a custom prefix defined. ```typescript get hasCustomPrefix(); ``` -------------------------------- ### Command Method: toObject Source: https://grammy.dev/ref/commands/command Converts the command into an object representation, suitable for JSON serialization. It includes command, description, and handler status. ```typescript toObject(languageCode: LanguageCode | "default"): Pick; ``` -------------------------------- ### Exit a Specific Parallel Conversation Instance Source: https://grammy.dev/ref/conversations/conversationcontrols Purges the state of a conversation with a given identifier at a specific chronological position in the current chat. For example, `exitOne("convo", 0)` exits the oldest active parallel "convo" conversation. Replays are not interrupted but their data won't be saved. ```typescript await ctx.conversation.exitOne("convo", 0) ``` -------------------------------- ### Command Prefix Option Source: https://grammy.dev/ref/commands/commandoptions Sets the prefix used to identify a command. Defaults to '/'. ```typescript prefix: string; ``` -------------------------------- ### select Source: https://grammy.dev/ref/conversations/conversationform Form field that validates if the incoming update contains text matching one of the predefined strings and returns the matched string. Useful with custom keyboards. ```APIDOC ## select ### Description Form field that checks if the incoming update contains a message or channel post with one of several predefined strings, and returns the actual text as string. Does not check captions. This is especially useful when working with custom keyboards. ### Parameters - **entries** (E[]) - Required - An array of predefined strings to select from. - **options** (FormOptions) - Optional - Configuration options for the select form field. ### Example ```typescript const keyboard = new Keyboard() .text("A").text("B") .text("C").text("D") .oneTime() await ctx.reply("A, B, C, or D?", { reply_markup: keyboard }) const answer = await conversation.form.select(["A", "B", "C", "D"], { otherwise: ctx => ctx.reply("Please use one of the buttons!") }) switch (answer) { case "A": case "B": case "C": case "D": // ... } ``` ### Source ```typescript select(entries: E[], options?: FormOptions); ``` ``` -------------------------------- ### Command Getter: stringName Source: https://grammy.dev/ref/commands/command A getter that returns the command's name as a string. ```typescript get stringName(); ``` -------------------------------- ### getNearestCommand Source: https://grammy.dev/ref/commands/commandsflavor Returns the nearest command to the user input based on a similarity algorithm. Returns `null` if no suitable command is found. ```APIDOC ## getNearestCommand ### Description Returns the nearest command to the user input. If no command is found, returns `null`. ### Method (Implied function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **commands** (CommandGroup | CommandGroup[]): The list of commands to search within. - **options** (Omit, "language">): Optional settings for the similarity comparison, excluding the language option. ### Request Example ```typescript // Example usage const nearest = await bot.api.getNearestCommand(availableCommands, { threshold: 0.8 }); ``` ### Response #### Success Response - **string | null**: The name of the nearest command, or null if no command is found. #### Response Example ```json { "example": "/start" } ``` ```json { "example": null } ``` ``` -------------------------------- ### BotCommand Array with Handler Flag Source: https://grammy.dev/ref/commands/setmycommandsparams An array of BotCommands, where each command can optionally include a boolean flag 'hasHandler' to indicate the presence of a handler. ```typescript commands: (BotCommand & { hasHandler?: boolean })[]; ``` -------------------------------- ### Command Constructor without Handler Source: https://grammy.dev/ref/commands/command Initializes a new command with a name and description, but no initial handler. Handlers can be added later. This command needs to be added to a CommandGroup to function. ```typescript Command( name: string | RegExp, description: string, options?: Partial, ); ``` -------------------------------- ### Command Getter: prefix Source: https://grammy.dev/ref/commands/command A getter that returns the prefix configured for this command. ```typescript get prefix(); ``` -------------------------------- ### Register Command with Handler Source: https://grammy.dev/ref/commands/commandgroup Registers a new command with a specified name, description, handler, and optional configuration. The handler can be a single middleware function or an array of middleware functions. ```typescript command( name: string | RegExp, description: string, handler: MaybeArray>>, options?: Partial, ): Command; ``` -------------------------------- ### waitForCommand Source: https://grammy.dev/ref/conversations/conversation Performs a filtered wait call that is defined by a command filter. It waits for an update and calls `skip` if the received context object does not contain the expected command. This uses the same logic as `bot.command`. An `otherwise` action can be specified if a context object is discarded. ```APIDOC ## waitForCommand ### Description Performs a filtered wait call that is defined by a command filter. It waits for an update and calls `skip` if the received context object does not contain the expected command. This uses the same logic as `bot.command`. An `otherwise` action can be specified if a context object is discarded. ### Method Signature `waitForCommand(command: MaybeArray, opts?: OtherwiseOptions): AndPromise>` ### Parameters #### Command - **command** (string | Array) - Required - The command to wait for. #### Options - **opts** (object) - Optional - Configuration options. - **otherwise** (function) - Optional - A function to execute if the context object does not contain the expected command. ### Example ```typescript const ctx = await conversation.waitForCommand("start", { otherwise: ctx => ctx.reply("Please send /start!") }) // Type inference works for deep links: const args = ctx.match ``` ### Chaining Calls to `waitForCommand` can be chained with other filtered wait calls. ```typescript const ctx = await conversation.waitForCommand("start") .andFor("message") ``` ``` -------------------------------- ### Me Property Source: https://grammy.dev/ref/conversations/contextbasedata Holds information about the bot itself. ```typescript me: UserFromGetMe; ``` -------------------------------- ### Create a conversational menu with submenus and navigation Source: https://grammy.dev/ref/conversations/conversation Define a conversational menu with navigation capabilities, including submenus and a back button. A menu identifier is used for seamless navigation. ```typescript const menu = conversation.menu("root") .submenu("Open submenu", ctx => ctx.editMessageText("submenu")) .text("Close", ctx => ctx.menu.close()) conversation.menu("child", { parent: "root" }) .back("Go back", ctx => ctx.editMessageText("Root menu")) await ctx.reply("Root menu", { reply_markup: menu }) ``` -------------------------------- ### Deno Custom Inspect Source: https://grammy.dev/ref/commands/commandgroup Replaces the default `toString` method for custom inspection in the Deno runtime environment. ```typescript [Symbol.for("Deno.customInspect")](); ``` -------------------------------- ### Api Property Source: https://grammy.dev/ref/conversations/contextbasedata Contains basic information used for constructing Api instances. ```typescript api: ApiBaseData; ``` -------------------------------- ### Serialize Commands to Detailed Objects Source: https://grammy.dev/ref/commands/commandgroup Serializes all registered commands into a detailed object format. This includes information like name, prefix, and language, and can be filtered by language. ```typescript toElementals(filterLanguage?: LanguageCode | "default"): BotCommandX[]; ``` -------------------------------- ### Register Command without Handler Source: https://grammy.dev/ref/commands/commandgroup Registers a new command with a name, description, and optional configuration, without an immediate handler. This overload is useful for commands that might have their handlers defined elsewhere or dynamically. ```typescript command( name: string | RegExp, description: string, options?: Partial, ): Command; ``` -------------------------------- ### File Update Handler Source: https://grammy.dev/ref/conversations/conversationform This function checks for file messages or channel posts, retrieves the file object using `ctx.getFile()`, and returns it. It accepts options for handling file reception and non-file updates. ```typescript file(options?: FormOptions); ``` -------------------------------- ### CommandGroup toString Method Source: https://grammy.dev/ref/commands/commandgroup Provides a string representation of the CommandGroup. This is a standard JavaScript method for object stringification. ```typescript toString(); ``` -------------------------------- ### waitFor Source: https://grammy.dev/ref/conversations/conversation Performs a filtered wait call that is defined by a filter query. It waits for an update and calls `skip` if the received context object does not match the filter query. This uses the same logic as `bot.on`. An `otherwise` action can be specified if a context object is discarded. ```APIDOC ## waitFor ### Description Performs a filtered wait call that is defined by a filter query. It waits for an update and calls `skip` if the received context object does not match the filter query. This uses the same logic as `bot.on`. An `otherwise` action can be specified if a context object is discarded. ### Method Signature `waitFor(query: Q | Q[], opts?: OtherwiseOptions): AndPromise>` ### Parameters #### Query - **query** (string | string[] | FilterQuery | FilterQuery[]) - Required - A filter query or an array of filter queries to match against. #### Options - **opts** (object) - Optional - Configuration options. - **otherwise** (function) - Optional - A function to execute if the context object does not match the query. ### Example ```typescript const ctx = await conversation.waitFor(":text", { otherwise: ctx => ctx.reply("Please send a text message!") }) // Type inference works: const text = ctx.msg.text; ``` ### Chaining Calls to `waitFor` can be chained with other filtered wait calls. ```typescript const ctx = await conversation.waitFor(":text").andFor("::hashtag") ``` ``` -------------------------------- ### Command Method: getLocalizedDescription Source: https://grammy.dev/ref/commands/command Retrieves the localized description of the command for a given language code, defaulting if not found. ```typescript getLocalizedDescription(languageCode: LanguageCode | "default"); ``` -------------------------------- ### getCommandEntities Source: https://grammy.dev/ref/commands/commandsflavor Extracts and returns command entities from a list of commands. ```APIDOC ## getCommandEntities ### Description Extracts and returns command entities from a list of commands. ### Method (Implied function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **commands** (CommandGroup | CommandGroup[]): The list of commands to process. ### Request Example ```typescript // Example usage const entities = await bot.api.getCommandEntities(myCommands); ``` ### Response #### Success Response - **BotCommandEntity[]**: An array of bot command entities. #### Response Example ```json { "example": [ { "offset": 0, "length": 10, "url": "" } ] } ``` ``` -------------------------------- ### Command Getter: description Source: https://grammy.dev/ref/commands/command A getter that returns the default description for this command. ```typescript get description(); ``` -------------------------------- ### ConversationContextStorage Adapter Source: https://grammy.dev/ref/conversations/conversationcontextstorage Specifies the underlying storage adapter used for reading and writing raw data. It must be an instance of VersionedStateStorage. ```typescript adapter: VersionedStateStorage; ``` -------------------------------- ### CommandGroup Middleware Method Source: https://grammy.dev/ref/commands/commandgroup Returns the middleware function for the CommandGroup. This can be used to integrate command handling into the bot's middleware pipeline. ```typescript middleware(); ``` -------------------------------- ### andForGameQuery Source: https://grammy.dev/ref/conversations/andextension Filters down the wait call using another game query check. Corresponds with Conversation.waitForGameQuery. ```APIDOC ## andForGameQuery ### Description Filters down the wait call using another game query check. Corresponds with Conversation.waitForGameQuery. ### Method N/A (TypeScript method signature) ### Endpoint N/A (TypeScript method signature) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript andForGameQuery(trigger: MaybeArray, opts?: AndOtherwiseOptions): AndPromise>; ``` ### Response #### Success Response (200) N/A (TypeScript method signature) #### Response Example N/A (TypeScript method signature) ``` -------------------------------- ### CommandNotFound Options Parameter Source: https://grammy.dev/ref/commands/commandnotfound The 'opts' parameter accepts partial JaroWinklerOptions, excluding the 'language' property. ```typescript opts: Omit, "language"> ``` -------------------------------- ### Wait Until with Type Predicate Source: https://grammy.dev/ref/conversations/conversation This snippet demonstrates using `waitUntil` with a type predicate to narrow down the context type, specifically waiting for a message with a text query. ```typescript const ctx = await conversation.waitUntil(Context.has.filterQuery(":text")) const text = ctx.msg.text; ``` -------------------------------- ### ConversationHandleOptions Source: https://grammy.dev/ref/conversations/conversationhandleoptions Configuration options for creating and managing conversation handles. ```APIDOC ## Interface: ConversationHandleOptions ### Description Options for creating a conversation handle. ### Properties #### maxMillisecondsToWait - **maxMillisecondsToWait** (number) - Optional - Default wait timeout. #### parallel - **parallel** (boolean) - Optional - `true` if this conversation can be entered while this or another conversation is already active, and `false` otherwise. Defaults to `false`. ### Methods #### onHalt - **onHalt**(): void | Promise - Callback for when the conversation is halted. ``` -------------------------------- ### Chain Waiters: Game Query and User Source: https://grammy.dev/ref/conversations/conversation Chains `waitForGameQuery` with `andFrom` to filter updates by both game query data and the originating user. ```typescript const ctx = await conversation.waitForGameQuery('data') .andFrom(ADMIN_USER_ID) ``` -------------------------------- ### Serialize Commands for Single Scope Source: https://grammy.dev/ref/commands/commandgroup Serializes commands for a specific scope, preparing them for `setMyCommands` calls. This is useful for applying commands to particular contexts like private chats or groups. ```typescript toSingleScopeArgs(scope: BotCommandScope); ``` -------------------------------- ### ConversationContextStorage Version Source: https://grammy.dev/ref/conversations/conversationcontextstorage An optional version for the data, which defaults to 0 if not specified. It can be a string or a number. ```typescript version?: string | number; ``` -------------------------------- ### Targeted Commands Option Source: https://grammy.dev/ref/commands/commandoptions Configures how commands targeting the bot's username are handled. Defaults to 'optional'. ```typescript targetedCommands: "ignored" | "optional" | "required"; ``` -------------------------------- ### ApiBaseData Token Property Source: https://grammy.dev/ref/conversations/apibasedata Represents the bot's authentication token, obtained from @BotFather. This is a required string. ```typescript token: string; ``` -------------------------------- ### Command Getter: names Source: https://grammy.dev/ref/commands/command A getter that returns all registered names for this command. ```typescript get names(); ``` -------------------------------- ### Log message on first reach Source: https://grammy.dev/ref/conversations/conversation Use `log()` to call `console.log` only on the first encounter. This prevents repeated logging during replays. ```typescript log(...data: unknown[]): Promise; ``` -------------------------------- ### ConversationForm Constructor Source: https://grammy.dev/ref/conversations/conversationform Constructs a new form based on wait and skip callbacks. This is used internally to manage conversation flow. ```APIDOC ## ConversationForm Constructor ### Description Constructs a new form based on wait and skip callbacks. ### Parameters - **conversation** (object) - Required - An object containing `wait` and `skip` methods for managing conversation flow. - **conversation.wait** (function) - Required - A function that waits for a specific condition or timeout. - **conversation.skip** (function) - Required - A function that skips the current step in the conversation. ### Source ```typescript ConversationForm(conversation: { wait: (opts: { maxMilliseconds?: number; collationKey?: string }) => Promise; skip: (opts: { next?: boolean }) => Promise }); ``` ``` -------------------------------- ### andForCommand Source: https://grammy.dev/ref/conversations/andextension Filters down the wait call using another command check. Corresponds with Conversation.waitForCommand. ```APIDOC ## andForCommand ### Description Filters down the wait call using another command check. Corresponds with Conversation.waitForCommand. ### Method N/A (TypeScript method signature) ### Endpoint N/A (TypeScript method signature) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript andForCommand(command: MaybeArray, opts?: AndOtherwiseOptions): AndPromise>; ``` ### Response #### Success Response (200) N/A (TypeScript method signature) #### Response Example N/A (TypeScript method signature) ``` -------------------------------- ### media Form Field Source: https://grammy.dev/ref/conversations/conversationform Detects either a photo or a video in messages and returns the corresponding media object. Use this for general media handling. Optional callbacks can be provided. ```typescript media(options?: FormOptions); ``` -------------------------------- ### build Source: https://grammy.dev/ref/conversations/conversationform A generic form field that can be used to build any other type of form field. This is heavily used internally and is generally not needed by users directly. ```APIDOC ## build ### Description Generic form field that can be used to build any other type of form field. This is heavily used internally. Most likely, you will not need this because there is a more convenient option. However, you can still use it if the type of form field you need is not supported out of the box. ### Parameters #### Overload 1 - **builder** (FormBuilderWithReason) - Required - The form builder configuration. #### Overload 2 - **builder** (FormBuilder) - Required - The form builder configuration. ### Returns - **Promise** - The result of the form building process. ### Source ```typescript // Overload 1 build(builder: FormBuilderWithReason): Promise; // Overload 2 build(builder: FormBuilder): Promise; ``` ``` -------------------------------- ### ApiBaseData Options Property Source: https://grammy.dev/ref/conversations/apibasedata Optional configuration settings for the API client. This allows customization of the underlying API request handling. ```typescript options?: ApiClientOptions; ``` -------------------------------- ### Command Method: addToScope (Generic) Source: https://grammy.dev/ref/commands/command Registers the command to a generic scope. Applies the provided middleware to the command handler. ```typescript addToScope( scope: BotCommandScope, middleware?: MaybeArray>, options?: Partial, ): this; ``` -------------------------------- ### Basic Conversation Wait Source: https://grammy.dev/ref/conversations/conversation This snippet demonstrates how to use the `wait` method of the conversation handle to pause execution and wait for the next update. ```typescript async function exmaple(conversation, ctx) { // ^ this is an instance of this class // This is how you can wait for updates: ctx = await conversation.wait() } ``` -------------------------------- ### Node.js Custom Inspect Source: https://grammy.dev/ref/commands/commandgroup Replaces the default `toString` method for custom inspection in the Node.js runtime environment. ```typescript [Symbol.for("nodejs.util.inspect.custom")](); ``` -------------------------------- ### Serialize Commands for setMyCommands Source: https://grammy.dev/ref/commands/commandgroup Serializes all registered commands into objects suitable for the `setMyCommands` API method. This can be scoped to a specific chat ID. ```typescript toArgs(chat_id?: BotCommandScopeChat["chat_id"]); ``` -------------------------------- ### Command Getter: name Source: https://grammy.dev/ref/commands/command A getter that returns the default name for this command. ```typescript get name(); ``` -------------------------------- ### ConversationKeyStorage Adapter Property Source: https://grammy.dev/ref/conversations/conversationkeystorage The underlying storage adapter responsible for reading and writing raw data. ```typescript adapter: VersionedStateStorage; ``` -------------------------------- ### UncompliantCommand Reasons Property Source: https://grammy.dev/ref/commands/uncompliantcommand An array of strings detailing the reasons why the command was considered uncompliant. ```typescript reasons: string[]; ``` -------------------------------- ### AutoRetryOptions Source: https://grammy.dev/ref/auto-retry/index This interface defines the configuration options for the auto-retry plugin. ```APIDOC ## AutoRetryOptions ### Description An interface that defines the available options for configuring the auto-retry plugin. ### Properties (No specific properties are detailed in the source text for this interface.) ``` -------------------------------- ### audio Source: https://grammy.dev/ref/conversations/conversationform Form field that checks for incoming audio messages and returns the audio object. ```APIDOC ## audio ### Description Form field that checks if the incoming update contains a message or channel post with an audio message, and returns the received audio object. Accepts an optional options object that lets you perform actions when an audio message is received, when a non-audio update is received, and more. ### Parameters - **options** (FormOptions) - Optional - Configuration options for the audio form field. ### Source ```typescript audio(options?: FormOptions); ``` ``` -------------------------------- ### CommandNotFound Type Parameter C Source: https://grammy.dev/ref/commands/commandnotfound Type parameter C represents the context, defaulting to a base Context. ```typescript C extends Context = Context ``` -------------------------------- ### Command Getter: languages Source: https://grammy.dev/ref/commands/command A getter that returns the registered languages for this command. ```typescript get languages(); ``` -------------------------------- ### Chain Waiters: Callback Query and User Source: https://grammy.dev/ref/conversations/conversation Chains `waitForCallbackQuery` with `andFrom` to filter updates by both callback query data and the originating user. ```typescript const ctx = await conversation.waitForCallbackQuery('data') .andFrom(ADMIN_USER_ID) ``` -------------------------------- ### Enter a Conversation with Arguments Source: https://grammy.dev/ref/conversations/conversationcontrols Enters a conversation and passes JSON-serializable arguments. These arguments are persisted and restored when the conversation is replayed. Ensure type safety by annotating the conversation function signature. ```typescript // Enters a conversation called "convo" upon a start command. bot.command("start", async ctx => { await ctx.conversation.enter("convo", 42, "cool", { args: [2, 1, 0] }) }) async function convo(conversation, ctx, num, str, { args }) { // ... } ``` -------------------------------- ### waitForHears Source: https://grammy.dev/ref/conversations/conversation Performs a filtered wait call that is defined by a hears filter. It waits for an update and calls `skip` if the received context object does not contain text that matches the given text or regular expression. This uses the same logic as `bot.hears`. An `otherwise` action can be specified if a context object is discarded. ```APIDOC ## waitForHears ### Description Performs a filtered wait call that is defined by a hears filter. It waits for an update and calls `skip` if the received context object does not contain text that matches the given text or regular expression. This uses the same logic as `bot.hears`. An `otherwise` action can be specified if a context object is discarded. ### Method Signature `waitForHears(trigger: MaybeArray, opts?: OtherwiseOptions): AndPromise>` ### Parameters #### Trigger - **trigger** (string | RegExp | Array) - Required - The text or regular expression to match against. #### Options - **opts** (object) - Optional - Configuration options. - **otherwise** (function) - Optional - A function to execute if the context object does not match the trigger. ### Example ```typescript const ctx = await conversation.waitForHears(["yes", "no"], { otherwise: ctx => ctx.reply("Please send yes or no!") }) // Type inference works: const answer = ctx.match ``` ### Chaining Calls to `waitForHears` can be chained with other filtered wait calls. ```typescript const ctx = await conversation.waitForHears(["yes", "no"]) .andFor("message:text") const text = ctx.message.text ``` ``` -------------------------------- ### Chain waitForCommand with andFor Source: https://grammy.dev/ref/conversations/conversation Chain `waitForCommand` with `andFor` to ensure commands are only received from text messages, excluding channel posts. ```typescript const ctx = await conversation.waitForCommand("start") .andFor("message") ``` -------------------------------- ### video_note Source: https://grammy.dev/ref/conversations/conversationform Processes incoming updates for video notes. It checks if the update contains a message or channel post with a video note and returns the video note object. Optional options can be provided to handle specific actions upon receiving a video note or other updates. ```APIDOC ## video_note ### Description Form field that checks if the incoming update contains a message or channel post with a video note, and returns the received video note object. ### Parameters #### Request Body - **options** (FormOptions) - Optional - An options object that lets you perform actions when a video note is received, when a non-video note update is received, and more. ``` -------------------------------- ### ConversationForm Constructor Source: https://grammy.dev/ref/conversations/conversationform Constructs a new form based on wait and skip callbacks. These callbacks are essential for managing the conversation flow and handling user input. ```typescript ConversationForm(conversation: { wait: (opts: { maxMilliseconds?: number; collationKey?: string }) => Promise; skip: (opts: { next?: boolean }) => Promise }); ``` -------------------------------- ### Add Existing Command Object Source: https://grammy.dev/ref/commands/commandgroup Registers a Command object that has already been created independently. This allows for modular command management. ```typescript add(command: Command | Command[]); ``` -------------------------------- ### ConversationKeyStorage Prefix Property Source: https://grammy.dev/ref/conversations/conversationkeystorage An optional prefix that can be prepended to the storage key. ```typescript prefix?: string; ``` -------------------------------- ### video Source: https://grammy.dev/ref/conversations/conversationform Processes incoming updates for videos. It checks if the update contains a message or channel post with a video and returns the video object. Optional options can be provided to handle specific actions upon receiving a video or other updates. ```APIDOC ## video ### Description Form field that checks if the incoming update contains a message or channel post with a video, and returns the received video object. ### Parameters #### Request Body - **options** (FormOptions) - Optional - An options object that lets you perform actions when a video is received, when a non-video update is received, and more. ``` -------------------------------- ### waitForReaction Source: https://grammy.dev/ref/conversations/conversation Performs a filtered wait call that is defined by a reaction filter. It waits for an update and calls `skip` if the received context object does not contain the expected reaction update. This uses the same logic as `bot.reaction`. An `otherwise` action can be specified if a context object is discarded. ```APIDOC ## waitForReaction ### Description Performs a filtered wait call that is defined by a reaction filter. It waits for an update and calls `skip` if the received context object does not contain the expected reaction update. This uses the same logic as `bot.reaction`. An `otherwise` action can be specified if a context object is discarded. ### Method Signature `waitForReaction(reaction: MaybeArray, opts?: OtherwiseOptions): AndPromise>` ### Parameters #### Reaction - **reaction** (string | ReactionType | Array) - Required - The reaction emoji or type to wait for. #### Options - **opts** (object) - Optional - Configuration options. - **otherwise** (function) - Optional - A function to execute if the context object does not contain the expected reaction update. ### Example ```typescript const ctx = await conversation.waitForReaction('πŸ‘', { otherwise: ctx => ctx.reply("Please upvote a message!") }) // Type inference works: const args = ctx.messageReaction ``` ### Chaining Calls to `waitForReaction` can be chained with other filtered wait calls. ```typescript const ctx = await conversation.waitForReaction('πŸ‘') .andFrom(ADMIN_USER_ID) ``` ``` -------------------------------- ### Chain waitForReaction with andFrom Source: https://grammy.dev/ref/conversations/conversation Chain `waitForReaction` with `andFrom` to filter reactions based on the sender's user ID. ```typescript const ctx = await conversation.waitForReaction('πŸ‘') .andFrom(ADMIN_USER_ID) ``` -------------------------------- ### external Source: https://grammy.dev/ref/conversations/conversation Runs a function outside of the replay engine, providing a safe way to perform side-effects like database operations or external API calls. Data returned must be serializable. ```APIDOC ## external ### Description Runs a function outside of the replay engine. This provides a safe way to perform side-effects such as database communication, disk operations, session access, file downloads, requests to external APIs, randomness, time-based functions, and more. It requires any data obtained from the outside to be serializable. ### Method `external(op: ExternalOp["task"] | ExternalOp): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **op** (ExternalOp["task"] | ExternalOp) - Required - The operation to perform outside the replay engine. This can be a function or an object with a `task` property. ### Request Example ```typescript // Read from database const data = await conversation.external(async () => { return await readFromDatabase() }); // Write to database await conversation.external(async () => { await writeToDatabase(data) }); // Read from session const sessionData = await conversation.external((ctx) => { return ctx.session.data }); // Custom serialization const largeNumber: bigint = await conversation.external({ task: () => fetchCoolBigIntFromTheInternet(), beforeStore: (largeNumber) => String(largeNumber), afterLoad: (str) => BigInt(str), }); ``` ### Response #### Success Response (R) Returns the data returned by the callback function. This data must be serializable. #### Response Example ```typescript // Example response based on the task function const result = await conversation.external(async () => { return { message: "Success" }; }); // result will be { message: "Success" } ``` ``` -------------------------------- ### paidMedia Source: https://grammy.dev/ref/conversations/conversationform Processes incoming updates for paid media. It checks if the update contains a message or channel post with paid media and returns the paid media object. Optional options can be provided to handle specific actions upon receiving paid media or other updates. ```APIDOC ## paidMedia ### Description Form field that checks if the incoming update contains a message or channel post with paid media, and returns the received paid media object. ### Parameters #### Request Body - **options** (FormOptions) - Optional - An options object that lets you perform actions when a paid media message is received, when a non-paid media update is received, and more. ``` -------------------------------- ### andForGameQuery: Filter wait calls with a game query check Source: https://grammy.dev/ref/conversations/andextension Filters down the wait call using another game query check. Corresponds with Conversation.waitForGameQuery. ```typescript andForGameQuery(trigger: MaybeArray, opts?: AndOtherwiseOptions): AndPromise>; ``` -------------------------------- ### video Form Field Source: https://grammy.dev/ref/conversations/conversationform Detects videos in messages and returns the video object. Suitable for handling video content. Optional callbacks can be provided for different scenarios. ```typescript video(options?: FormOptions); ``` -------------------------------- ### game Source: https://grammy.dev/ref/conversations/conversationform Processes incoming updates for games. It checks if the update contains a message or channel post with a game and returns the game object. Optional options can be provided to handle specific actions upon receiving a game or other updates. ```APIDOC ## game ### Description Form field that checks if the incoming update contains a message or channel post with a game, and returns the received game object. ### Parameters #### Request Body - **options** (FormOptions) - Optional - An options object that lets you perform actions when a game is received, when a non-game update is received, and more. ``` -------------------------------- ### media Source: https://grammy.dev/ref/conversations/conversationform Processes incoming updates for photos or videos. It checks if the update contains a message or channel post with a photo or video and returns the media object. Optional options can be provided to handle specific actions upon receiving media or other updates. ```APIDOC ## media ### Description Form field that checks if the incoming update contains a message or channel post with a photo or video, and returns the received media object. ### Parameters #### Request Body - **options** (FormOptions) - Optional - An options object that lets you perform actions when a media is received, when a non-media update is received, and more. ``` -------------------------------- ### Enter a Conversation Source: https://grammy.dev/ref/conversations/conversationcontrols Enters a conversation with a specified identifier. The bot will run the conversation until the first wait call is reached. Arguments passed will be JSON-serialized and persisted. ```typescript bot.command("start", async ctx => { await ctx.conversation.enter("convo") }) ``` -------------------------------- ### setMyCommands Source: https://grammy.dev/ref/commands/commandsflavor Sets the provided commands for the current chat. This method cannot be called on updates that do not have a `chat` property. Calling this method with upper-cased command names registered will result in an error. ```APIDOC ## setMyCommands ### Description Sets the provided commands for the current chat. Cannot be called on updates that don’t have a `chat` property. [!IMPORTANT] Calling this method with upperCased command names registered, will throw ### Method (Implied asynchronous function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **commands** (CommandGroup | CommandGroup[]): The commands to set. - **options** (SetBotCommandsOptions): Optional settings for setting commands. ### Request Example ```typescript // Example usage (assuming 'bot' is an instance of grammY) await bot.api.setMyCommands(myCommands, { scope: 'chat', chatId: 123 }); ``` ### Response #### Success Response - **void**: This method does not return a value upon success. #### Response Example None ``` -------------------------------- ### Register Commands with Telegram API Source: https://grammy.dev/ref/commands/commandgroup Registers all commands with the Telegram API, making them visible to clients. This method iterates through all scopes and languages to call `setMyCommands` appropriately. Note that uppercase command names will cause an error. ```typescript setCommands({ api }: { api: Api }, options?: Partial): Promise; ``` -------------------------------- ### checkpoint Source: https://grammy.dev/ref/conversations/conversation Creates a new checkpoint at the current point of the conversation, which can be used later with the `rewind` method. ```APIDOC ## checkpoint ### Description Creates a new checkpoint at the current point of the conversation. This checkpoint can be passed to `rewind` in order to go back in the conversation and resume it from an earlier point. ### Method `checkpoint(): Checkpoint` ### Parameters None ### Request Example ```typescript const check = conversation.checkpoint(); ``` ### Response #### Success Response (Checkpoint) Returns a `Checkpoint` object representing the current conversation state. #### Response Example ```typescript // check will be of type Checkpoint const check = conversation.checkpoint(); ``` ```