如何用Node.js开发Telegram机器人实现问答链式表单功能?
Hey there! Let's work through that conversational form flow you need to build—great job getting the Google Sheets integration sorted already, that's a big win. Here's how to implement the step-by-step question chain when a user triggers the /form command:
Core Idea: Track Conversation State
The key here is keeping track of where each user is in the form process (e.g., waiting for their name, then age, etc.). You'll need a way to store this state per user—something like an in-memory dictionary, lightweight database, or your framework's built-in session storage will work perfectly.
Let's walk through a concrete example with pseudocode (this logic translates to most chat bot frameworks like Discord.py, Telegram Bot API, or custom Slack bots):
Initialize State & Form Structure
First, define the order of fields you need to collect, and set up storage for user states and temporary answers:# Track which step each user is on (key: user ID, value: step index) user_form_states = {} # Define the sequence of fields to collect FORM_FIELDS = ["name", "age", "email"] # Temporary storage for answers during the flow user_form_answers = {}Handle the
/formTrigger
When a user sends/form, reset their state and kick off the first question:def handle_form_command(user_id): # Reset the user's form progress user_form_states[user_id] = 0 user_form_answers[user_id] = {} # Send the first question send_message(user_id, "Could you please share your name?")Process User Responses
For every incoming message, check if the user is in the middle of the form flow, then act accordingly:def handle_user_message(user_id, message_content): # Check if user is active in the form flow if user_id in user_form_states: current_step = user_form_states[user_id] current_field = FORM_FIELDS[current_step] # Validate input (optional but recommended) if current_field == "age" and not message_content.isdigit(): send_message(user_id, "Whoops, please enter a valid number for your age!") return # Stay on the same step until valid input is received # Save the answer temporarily user_form_answers[user_id][current_field] = message_content # Move to next step or finish up next_step = current_step + 1 if next_step < len(FORM_FIELDS): # Update state and send next question user_form_states[user_id] = next_step next_field_label = { "name": "name", "age": "age", "email": "email" }[FORM_FIELDS[next_step]] send_message(user_id, f"Thanks! Now could you share your {next_field_label}?") else: # All fields collected—send to Google Sheets submit_to_google_sheets(user_form_answers[user_id]) # Clean up state del user_form_states[user_id] del user_form_answers[user_id] send_message(user_id, "Perfect! Your form has been submitted successfully.") else: # Handle non-form messages as usual send_message(user_id, "I don't recognize that command—try sending `/form` to start the questionnaire!")
Extra Tips for Smooth Flow
- Input Validation: Add checks for each field (e.g., valid email format, numeric age) to ensure data quality before saving.
- Exit Option: Let users cancel the form mid-flow (e.g., send
/cancel) by clearing their state and sending a confirmation. - Persistent Storage: If your bot restarts often, use a database (like SQLite or Firebase) instead of in-memory dictionaries to avoid losing user progress.
This state-tracking approach works across almost all chat platforms—once you've got the step-by-step logic down, you just need to adapt it to your specific bot framework's message handling methods.
内容的提问来源于stack exchange,提问作者Hennessy811

