Use createForm to define a sequence of interactive steps (fields) for a user in a specific chat. A form can contain text fields (for free-form user input with optional Zod validation) or choice fields (for inline keyboard buttons).
To use a form, you must:
- Define the fields using
defineField to ensure type safety. - Initialize the form with
createForm(chatId, fields). - Register the form in the global
Forms registry using Forms.setForm(chatId, form). - Use
form.setActiveField(fieldName) to prompt the user for the next piece of data.
The bot automatically handles incoming message events for text fields and callback_query events for choice fields, triggering the respective handler functions defined in your fields.
import { createForm, defineField, Forms } from './utils/form';
import { z } from 'zod';
const chatId = 12345;
const form = createForm(chatId, {
userName: defineField({
type: 'text',
validation: z.string().min(3),
message: 'Please enter your username:',
handler: ({ value, msg }) => {
console.log(`User entered: ${value}`);
// Move to next field
form.setActiveField('age');
}
}),
age: defineField({
type: 'choice',
choices: [
{ key: 'young', title: 'Young' },
{ key: 'old', title: 'Old' }
],
message: 'Select your age group:',
handler: ({ value, query }) => {
console.log(`User chose: ${value}`);
Forms.resetForm(chatId);
}
})
});
// Register the form so the bot listeners can find it
Forms.setForm(chatId, form);
// Start the first step
form.setActiveField('userName');