// 問題卡: the bot asks the person with a card instead of a paragraph of questions. // // One call carries up to MAX_QUESTIONS questions; the card steps through them one at a time. // A question has choices (pick one, or several with `multiple`), or none at all — then it is a // field to type in, which may arrive already filled (`default`) for the person to correct: a // form. Every question takes an answer in the person's own words too. // // The card travels as an approval of kind Question whose `reason` is the questions as JSON, so // the window, a screen of another brain and the phone all draw the same thing; the answer comes // back as ApprovalAnswer::Answered with one string per question. use serde_json::{json, Value}; pub const TOOL: &str = "ask_person"; pub const MAX_QUESTIONS: usize = 6; pub const MAX_OPTIONS: usize = 8; /// Between several picks of one question, in the answer string. pub const JOIN: &str = "、"; #[derive(Clone, Debug, PartialEq, Default)] pub struct Question { pub question: String, pub options: Vec, pub multiple: bool, /// What the field (or the pick) starts as. pub default: String, } pub fn spec() -> Value { json!({"name": TOOL, "description": "Ask the person with a card in the chat and wait for the answer, instead of writing questions as text. Use it when you need a decision or a detail before going on: which of a few options, yes or no, several things to pick, or a short form (name, date, address…). Up to 6 questions in one call; the card shows them one at a time. Give `options` when the answers are known (2–8 short ones; the person can always type their own instead); leave `options` out for a field to type in, and put what you already know in `default` so they only correct it. Don't repeat the questions in your message. Don't ask for passwords, card numbers or codes here (use the vault tools or hand over the computer), and don't ask what you can find out yourself. When nobody is at the app (a message from a channel such as Slack or Telegram, or a routine), ask in words instead: the card only shows in AnyBot. The result lists each answer; if the person skipped the card or wrote a message instead, do what that says.", "parameters": {"type": "object", "properties": { "questions": {"type": "array", "items": {"type": "object", "properties": { "question": {"type": "string", "description": "One short question in the person's language."}, "options": {"type": "array", "items": {"type": "string"}, "description": "The choices, each a few words. Leave out for a typed answer."}, "multiple": {"type": "boolean", "description": "true when several options may be picked."}, "default": {"type": "string", "description": "What the field starts as (a typed answer), or the option picked to begin with."}}, "required": ["question"]}}}, "required": ["questions"]}}) } fn short(s: &str, max: usize) -> String { let s = s.trim(); if s.chars().count() <= max { s.to_string() } else { s.chars().take(max).collect::() + "…" } } /// The questions of a call (or of a card's `reason`), tidied: empty ones dropped, lengths capped. pub fn parse(args: &str) -> Result, String> { let v: Value = serde_json::from_str(args).unwrap_or(Value::Null); let list = match &v { Value::Array(a) => a.clone(), _ => v["questions"].as_array().cloned().unwrap_or_default(), }; let mut out = vec![]; for q in list.iter().take(MAX_QUESTIONS) { // A bare string is a question with a typed answer. let question = short(q.as_str().or_else(|| q["question"].as_str()).unwrap_or(""), 300); if question.is_empty() { continue; } let mut options: Vec = vec![]; for o in q["options"].as_array().into_iter().flatten() { let o = short(o.as_str().unwrap_or(""), 80); if !o.is_empty() && !options.contains(&o) && options.len() < MAX_OPTIONS { options.push(o); } } out.push(Question { question, multiple: q["multiple"].as_bool().unwrap_or(false) && options.len() > 1, default: short(q["default"].as_str().unwrap_or(""), 500), options }); } if out.is_empty() { return Err("請在 questions 裡至少寫一個問題(question)。".into()); } Ok(out) } /// The card's `reason`: what every screen draws from. pub fn to_json(qs: &[Question]) -> String { Value::Array(qs.iter().map(|q| json!({"question": q.question, "options": q.options, "multiple": q.multiple, "default": q.default})).collect()).to_string() } /// The answers as they travel back: a JSON list, one string per question. pub fn answers_of(text: &str) -> Vec { serde_json::from_str::>(text).unwrap_or_else(|_| vec![text.to_string()]) } /// What the bot reads once the person has answered. pub fn result(qs: &[Question], answers: &[String]) -> String { let mut out = String::from("使用者的回答:"); for (i, q) in qs.iter().enumerate() { let a = answers.get(i).map(|a| a.trim()).unwrap_or(""); out.push_str(&format!("\n{}. {} → {}", i + 1, q.question, if a.is_empty() { "(沒有回答)" } else { a })); } out } pub const SKIPPED: &str = "使用者略過了這張問題卡,沒有回答。不要再問同樣的問題:照你最合理的判斷繼續,或說明沒有答案就做不了哪一部分。"; pub const WROTE_INSTEAD: &str = "使用者沒有回答問題卡,而是傳了訊息(就在下面)。照他說的做。"; /// One line for the list of steps: the first question. pub fn describe(args: &str) -> String { match parse(args) { Ok(qs) if qs.len() > 1 => format!("{}(共 {} 題)", short(&qs[0].question, 40), qs.len()), Ok(qs) => short(&qs[0].question, 40), Err(_) => String::new(), } } /// The person's side of one card: which question is up and what is picked or typed so far. #[derive(Clone, Debug, Default)] pub struct Form { pub call_id: String, pub step: usize, /// Per question: the options ticked. pub picks: Vec>, /// Per question: the field (a typed answer, or 「自己回答」 beside the options). pub typed: Vec, } impl Form { pub fn new(call_id: &str, qs: &[Question]) -> Self { let mut f = Form { call_id: call_id.to_string(), step: 0, picks: vec![vec![]; qs.len()], typed: vec![String::new(); qs.len()] }; for (i, q) in qs.iter().enumerate() { match q.options.iter().position(|o| *o == q.default) { Some(at) => f.picks[i].push(at), None if q.options.is_empty() => f.typed[i] = q.default.clone(), None => {} } } f } /// Tick or untick an option (one at a time unless the question takes several). pub fn pick(&mut self, q: &Question, at: usize) { let picks = &mut self.picks[self.step]; if q.multiple { match picks.iter().position(|p| *p == at) { Some(i) => { picks.remove(i); } None => picks.push(at), } } else { *picks = vec![at]; self.typed[self.step].clear(); } } /// The answer to question `i`: what is typed wins over a single pick and joins several. pub fn answer(&self, qs: &[Question], i: usize) -> String { let q = &qs[i]; let typed = self.typed[i].trim(); let mut parts: Vec = if q.multiple || typed.is_empty() { let mut p = self.picks[i].clone(); p.sort(); p.iter().filter_map(|at| q.options.get(*at).cloned()).collect() } else { vec![] }; if !typed.is_empty() { parts.push(typed.to_string()); } parts.join(JOIN) } pub fn answered(&self, qs: &[Question], i: usize) -> bool { !self.answer(qs, i).is_empty() } /// All the answers, as they travel back. pub fn send(&self, qs: &[Question]) -> String { Value::Array((0..qs.len()).map(|i| Value::String(self.answer(qs, i))).collect()).to_string() } } #[cfg(test)] mod tests { use super::*; #[test] fn questions_are_tidied() { let qs = parse(r#"{"questions":[{"question":" 幾點出發? ","options":["早上","早上","下午",""],"multiple":true},{"question":""},"姓名?",{"question":"只有一個選項","options":["好"],"multiple":true}]}"#).unwrap(); assert_eq!(qs.len(), 3); assert_eq!(qs[0], Question { question: "幾點出發?".into(), options: vec!["早上".into(), "下午".into()], multiple: true, default: String::new() }); assert!(qs[1].options.is_empty() && qs[1].question == "姓名?"); // Several of one makes no sense. assert!(!qs[2].multiple); assert!(parse("{}").is_err()); assert!(parse(r#"{"questions":[]}"#).is_err()); // The card's own JSON reads back the same. assert_eq!(parse(&to_json(&qs)).unwrap(), qs); let many = json!({"questions": (0..20).map(|i| json!({"question": format!("q{i}")})).collect::>()}).to_string(); assert_eq!(parse(&many).unwrap().len(), MAX_QUESTIONS); } #[test] fn a_form_arrives_filled_and_is_corrected() { let qs = parse(r#"{"questions":[{"question":"收件人","default":"王小明"},{"question":"尺寸","options":["S","M","L"],"default":"M"},{"question":"配料","options":["蔥","蒜","辣"],"multiple":true}]}"#).unwrap(); let mut f = Form::new("c1", &qs); assert_eq!(f.answer(&qs, 0), "王小明"); assert_eq!(f.answer(&qs, 1), "M"); assert!(!f.answered(&qs, 2)); f.typed[0] = "王大明".into(); f.step = 1; f.pick(&qs[1], 2); assert_eq!(f.answer(&qs, 1), "L"); // 自己回答 replaces a single pick… f.typed[1] = "XL".into(); assert_eq!(f.answer(&qs, 1), "XL"); // …and picking again drops what was typed. f.pick(&qs[1], 0); assert_eq!(f.answer(&qs, 1), "S"); f.step = 2; f.pick(&qs[2], 2); f.pick(&qs[2], 0); f.pick(&qs[2], 1); f.pick(&qs[2], 1); f.typed[2] = "香菜".into(); // In the card's order, with the person's own after them. assert_eq!(f.answer(&qs, 2), "蔥、辣、香菜"); let sent = f.send(&qs); assert_eq!(answers_of(&sent), vec!["王大明", "S", "蔥、辣、香菜"]); assert_eq!(result(&qs, &answers_of(&sent)), "使用者的回答:\n1. 收件人 → 王大明\n2. 尺寸 → S\n3. 配料 → 蔥、辣、香菜"); assert!(result(&qs, &["a".into()]).contains("3. 配料 → (沒有回答)")); } }