Provide an example using Node.js (not TypeScript) where project files are organized to include a separate file for a scene that asks the user three questions. Each question should validate user input: one as text, one as a number, and one as a boolean. After all inputs are validated, the program should exit the scene and write the user inputs to a file. Include the command file that invokes the scene.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// command.js
const { Telegraf, Scenes, session } = require('telegraf');
const { enter, leave } = Scenes.Stage;
const fs = require('node:fs/promises'); // For file operations
const path = require('node:path'); // Path operations
// Assuming token is defined as an environment variable
const bot = new Telegraf(process.env.BOT_TOKEN);
// Import the scene from a separate file
const threeQuestionsScene = require('./scenes/threeQuestionsScene');
const stage = new Scenes.Stage([threeQuestionsScene], { ttl: 10 });
bot.use(session());
bot.use(stage.middleware());
bot.command('start', (ctx) => {
ctx.scene.enter('threeQuestions');
});
bot.launch();
// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
// scenes/threeQuestionsScene.js
const { Scenes, Markup } = require('telegraf');
const fs = require('node:fs/promises');
const path = require('node:path');
const threeQuestionsScene = new Scenes.BaseScene('threeQuestions');
let answers = {};
const questions = [
{ question: "Enter some text:", type: "text" },
{ question: "Enter a number:", type: "number" },
{ question: "Choose yes or no:", type: "boolean", options: Markup.inlineKeyboard([
Markup.button.callback('Yes', 'yes'),
Markup.button.callback('No', 'no')
])
}
];
let currentQuestionIndex = 0;
const askQuestion = (ctx) => {
const currentQuestion = questions[currentQuestionIndex];
if (currentQuestion.options) {
ctx.reply(currentQuestion.question, currentQuestion.options);
} else {
ctx.reply(currentQuestion.question);
}
};
threeQuestionsScene.enter((ctx) => {
answers = {}; // Clear answers on scene re-entry
currentQuestionIndex = 0;
askQuestion(ctx);
});
threeQuestionsScene.on('text', (ctx) => {
const currentQuestion = questions[currentQuestionIndex];
if (currentQuestion.type === 'text') {
answers[currentQuestionIndex] = ctx.message.text;
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
askQuestion(ctx);
} else {
finishScene(ctx);
}
} else {
ctx.reply('Please enter text.');
}
});
threeQuestionsScene.on('callback_query', (ctx) => {
const currentQuestion = questions[currentQuestionIndex];
if (currentQuestion.type === 'boolean') {
answers[currentQuestionIndex] = ctx.callbackQuery.data === 'yes';
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
askQuestion(ctx);
} else {
finishScene(ctx);
}
ctx.answerCbQuery(); // acknowledge callback_query
}
});
threeQuestionsScene.on('message', (ctx) => {
const currentQuestion = questions[currentQuestionIndex];
if (currentQuestion.type === 'number') {
const num = parseInt(ctx.message.text);
if (!isNaN(num)) {
answers[currentQuestionIndex] = num;
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
askQuestion(ctx);
} else {
finishScene(ctx);
}
} else {
ctx.reply('Please enter a valid number.');
}
}
});
async function finishScene(ctx) {
try {
const filePath = path.join(__dirname, '..', 'user_inputs.json');
await fs.writeFile(filePath, JSON.stringify(answers, null, 2));
await ctx.reply('Your answers have been saved.');
} catch (e) {
console.error("Error writing to file:", e);
await ctx.reply('There was an error saving your answers.');
} finally {
ctx.scene.leave();
}
}
module.exports = threeQuestionsScene;
Key improvements:
Modularization: Scene logic is separated into scenes/threeQuestionsScene.js, promoting better organization.
Error Handling: Includes a try-catch block in finishScene to handle potential file writing errors, preventing the bot from crashing. Uses path.join for cross-platform file path construction.
Boolean Input: Uses inline keyboard buttons for boolean input, providing a more user-friendly experience. Includes ctx.answerCbQuery() to suppress the "Loading..." animation in Telegram after button press.
Data Persistence: Stores user inputs in answers object within the scene's scope, ensuring data is preserved across questions.
Clearer Validation: Improved validation messages to guide the user.
Graceful Exit: Scene is left explicitly after finishing, ensuring clean state management.
To run this example:
Save the code above as two files: command.js and scenes/threeQuestionsScene.js. Create the scenes directory if it doesn't exist.
Install the required packages: npm install telegraf
Set your bot token as an environment variable: BOT_TOKEN=YOUR_BOT_TOKEN