### Install and Extend GramIO Bot with Prompt Source: https://context7.com/gramiojs/prompt/llms.txt This snippet demonstrates how to install and extend the GramIO bot with the prompt plugin. It initializes the bot with the plugin and starts it. ```typescript import { Bot } from "gramio"; import { prompt } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .onStart(console.log); bot.start(); ``` -------------------------------- ### Basic Prompt Usage: Collect User Name and Age Source: https://context7.com/gramiojs/prompt/llms.txt This example shows basic usage of the prompt() method to collect user's name and age. It sends messages to the user and waits for text responses, then sends a welcome message. ```typescript import { Bot, format, bold } from "gramio"; import { prompt } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("register", async (context) => { const nameAnswer = await context.prompt( "message", format`What's your ${bold`name`}?` ); const ageAnswer = await context.prompt( "message", "How old are you?" ); return context.send( `✨ Welcome ${nameAnswer.text}! You are ${ageAnswer.text} years old.` ); }); bot.start(); ``` -------------------------------- ### Wait for Next User Event without Prompt Source: https://context7.com/gramiojs/prompt/llms.txt This example uses the wait() method to listen for the next user event without sending an initial prompt message. It echoes back any message received from the user. ```typescript import { Bot } from "gramio"; import { prompt } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("echo", async (context) => { await context.send("Send me any message and I'll echo it back:"); const answer = await context.wait(); return context.send(`You said: ${answer.text}`); }); bot.start(); ``` -------------------------------- ### Multi-Step Form with Error Handling in TypeScript Source: https://context7.com/gramiojs/prompt/llms.txt Build complex forms with validation and error recovery. This example demonstrates a three-step form where each input is validated, and timeouts are handled gracefully. It uses the 'prompt' and 'PromptCancelError' from '@gramio/prompt'. ```typescript import { Bot } from "gramio"; import { prompt, PromptCancelError } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt({ defaults: { timeout: 120000 } })) .command("form", async (context) => { try { await context.send("📋 Let's fill out a form. You have 2 minutes for each question."); const name = await context.prompt( "message", "Step 1/3: What's your name?", { validate: (ctx) => (ctx.text?.length || 0) >= 2, onValidateError: (ctx) => ctx.send("❌ Name too short. Try again:") } ); const email = await context.prompt( "message", "Step 2/3: What's your email?", { validate: (ctx) => /^[^s@]+@[^s@]+.[^s@]+$/.test(ctx.text || ""), onValidateError: "❌ Invalid email format. Please try again:" } ); const [phone, confirmMsg] = await context.waitWithAction( "message", () => context.send("Step 3/3: What's your phone number?"), { validate: (ctx) => /^\+?[\d\s-()]+$/.test(ctx.text || ""), onValidateError: (ctx, msg) => ctx.send("❌ Invalid phone. Use digits, spaces, +, -, () only:", { reply_to_message_id: msg.message_id }) } ); return context.send( `✅ Form submitted!\n\n` + `Name: ${name.text}\n` + `Email: ${email.text}\n` + `Phone: ${phone.text}` ); } catch (error) { if (error instanceof PromptCancelError) { return context.send("❌ Form cancelled due to timeout."); } throw error; } }); bot.start(); ``` -------------------------------- ### Configure Timeout Strategy for Prompts (TypeScript) Source: https://context7.com/gramiojs/prompt/llms.txt This example demonstrates how to configure global and per-prompt timeout strategies. The `timeoutStrategy` option can be set to 'on-timer' to automatically reject prompts when the timeout expires. You can also override the default timeout for specific prompts. ```typescript import { Bot } from "gramio"; import { prompt, PromptCancelError } from "@gramio/prompt"; // Using "on-timer" strategy - automatically rejects when timeout expires const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt({ timeoutStrategy: "on-timer", // or "on-answer" (default) defaults: { timeout: 60000 // 60 seconds default timeout } })) .command("quiz", async (context) => { try { const answer = await context.prompt( "message", "Quick! What's 2 + 2?", { timeout: 10000 } // Override default: 10 seconds ); if (answer.text === "4") { return context.send("✅ Correct!"); } return context.send("❌ Wrong answer!"); } catch (error) { if (error instanceof PromptCancelError && error.type === "timeout") { return context.send("⏱️ Time's up!"); } throw error; } }); bot.start(); ``` -------------------------------- ### Perform Action and Wait for User Response (TypeScript) Source: https://context7.com/gramiojs/prompt/llms.txt The `waitWithAction` method allows you to send a message and simultaneously wait for a specific user response. It can validate the input and provide feedback if validation fails. This is useful for guided interactions. ```typescript import { Bot } from "gramio"; import { prompt } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("poll", async (context) => { const [userAnswer, pollMessage] = await context.waitWithAction( "message", () => context.send("Please answer: What's your favorite color?", { reply_markup: { keyboard: [[{ text: "Red" }, { text: "Blue" }, { text: "Green" }]], one_time_keyboard: true } }), { validate: (ctx) => ["Red", "Blue", "Green"].includes(ctx.text || ""), onValidateError: "❌ Please choose Red, Blue, or Green" } ); return context.send(`You chose ${userAnswer.text}! Message ID: ${pollMessage.message_id}`); }); bot.start(); ``` -------------------------------- ### Custom Async Validation with @gramio/prompt in TypeScript Source: https://context7.com/gramiojs/prompt/llms.txt Validate user input against external data sources using asynchronous operations. This example shows how to check if a chosen username is already taken before registering it. It includes checks for length, allowed characters, and an asynchronous call to simulate a database lookup. ```typescript import { Bot } from "gramio"; import { prompt } from "@gramio/prompt"; // Simulated async username check async function isUsernameTaken(username: string): Promise { // In real app, check database await new Promise(resolve => setTimeout(resolve, 500)); return ["admin", "root", "test"].includes(username.toLowerCase()); } const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("username", async (context) => { const answer = await context.prompt( "message", "Choose your username:", { validate: async (ctx) => { const username = ctx.text || ""; if (username.length < 3) return false; if (!/^[a-zA-Z0-9_]+$/.test(username)) return false; return !(await isUsernameTaken(username)); }, onValidateError: async (ctx) => { const username = ctx.text || ""; if (username.length < 3) { return ctx.send("❌ Username must be at least 3 characters"); } if (!/^[a-zA-Z0-9_]+$/.test(username)) { return ctx.send("❌ Use only letters, numbers, and underscores"); } return ctx.send("❌ Username already taken. Try another:"); }, timeout: 30000 } ); return context.send(`✅ Username @${answer.text} is now registered!`); }); bot.start(); ``` -------------------------------- ### Handle Button Clicks with Callback Query Prompts (TypeScript) Source: https://context7.com/gramiojs/prompt/llms.txt This snippet shows how to use `prompt` to handle `callback_query` updates, typically triggered by inline keyboard buttons. It allows you to prompt the user for a selection via an inline keyboard and process their choice based on the callback data. ```typescript import { Bot, InlineKeyboard } from "gramio"; import { prompt } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("choose", async (context) => { const keyboard = new InlineKeyboard() .text("Option A", "opt_a") .text("Option B", "opt_b"); const answer = await context.prompt( "callback_query", "Choose an option:", { reply_markup: keyboard } ); await answer.answerCallbackQuery(); return context.send(`You selected: ${answer.data}`); }); bot.start(); ``` -------------------------------- ### Transform User Responses to Custom Data Structures (TypeScript) Source: https://context7.com/gramiojs/prompt/llms.txt The `prompt` method supports a `transform` option to convert raw user input into custom data structures. This is useful for parsing and organizing data like user profiles or registration details. It also includes validation for input correctness. ```typescript import { Bot } from "gramio"; import { prompt } from "@gramio/prompt"; interface UserData { name: string; email: string; timestamp: number; } const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("signup", async (context) => { const nameData = await context.prompt( "message", "Enter your full name:", { validate: (ctx) => (ctx.text?.length || 0) >= 2, transform: (ctx) => ({ name: ctx.text || "", email: "", timestamp: Date.now() }), onValidateError: "Name must be at least 2 characters" } ); const userData = await context.prompt( "message", "Enter your email:", { validate: (ctx) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ctx.text || ""), transform: (ctx) => ({ ...nameData, email: ctx.text || "" }), onValidateError: "Please enter a valid email address" } ); return context.send( `✅ Registration complete!\nName: ${userData.name}\nEmail: ${userData.email}\nRegistered at: ${new Date(userData.timestamp).toISOString()}` ); }); bot.start(); ``` -------------------------------- ### Wait for Specific Event with Filtering and Transformation Source: https://context7.com/gramiojs/prompt/llms.txt This snippet demonstrates using wait() with event filtering to specifically listen for photo messages and transforming the response to extract the file ID. It sends a message asking for a photo and then replies with the photo's file ID. ```typescript import { Bot } from "gramio"; import { prompt } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("photo", async (context) => { await context.send("Please send me a photo:"); const answer = await context.wait("message", { validate: (ctx) => !!ctx.photo, transform: (ctx) => ctx.photo?.[0]?.file_id }); return context.send(`Got photo with file_id: ${answer}`); }); bot.start(); ``` -------------------------------- ### Prompt with Custom Validation for Age Source: https://context7.com/gramiojs/prompt/llms.txt This snippet illustrates how to use the prompt() method with custom validation to ensure the user's age is between 18 and 120. It includes error handling for invalid input and timeouts. ```typescript import { Bot } from "gramio"; import { prompt } from "@gramio/prompt"; const bot = new Bot(process.env.BOT_TOKEN!) .extend(prompt()) .command("age", async (context) => { try { const answer = await context.prompt( "message", "Please enter your age (must be 18 or older):", { validate: (ctx) => { const age = Number.parseInt(ctx.text || "0"); return age >= 18 && age <= 120; }, onValidateError: "❌ Invalid age. Please enter a number between 18 and 120.", timeout: 30000 } ); return context.send(`✅ Thanks! Your age is ${answer.text}`); } catch (error) { return context.send("⏱️ Prompt timed out. Please try again."); } }); bot.start(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.