Skip to content

Recipes ​

Each block is a whole script. Replace the exit names (paid, open…) with your block's exits. The output under a script is the first run on the message «Hello! Where is my order 10452?».

Order status from an API ​

Exits: paid, unpaid, not_found. While the request runs, the visitor sees «Looking up…», which is then replaced with the answer.

mzs
include bot
include json
id = $message.captures(/\b(\d{4,10})\b/)?.dig(1) ?? (bot.get("order_id") ?? "")
if id.blank {
  bot.say("Send the order number — the digits from the email.")
  bot.exit("not_found")
  exit()
}
msg = bot.say("Looking up order ${id}…")
r = bot.http({url: "https://shop.example.com/api/orders/${id}"})
order = r["ok"] ? (try json.parse(r["body"]) else nil) : nil
if order == nil {
  bot.edit(msg, r["status"] == 404 ? "Order ${id} not found." : "The order service isn't responding, please try later.")
  bot.exit("not_found")
  exit()
}
labels = {paid: "paid", pending: "awaiting payment", shipped: "shipped"}
status = order["status"] ?? "unknown"
bot.set("order_id", id)
bot.set("order_status", status)
bot.edit(msg, "Order ${id}: **${labels[status] ?? status}**, total ${order["total"]} ₽")
bot.exit(status in ["paid", "shipped"] ? "paid" : "unpaid")
text
Looking up order 10452…
✎ Order 10452: **shipped**, total 3490 ₽

A CRM lead: name, phone, confirmation ​

Exit «дальше» (next) — the lead is sent. Asks step by step, waits for answers, checks the phone number.

mzs
include bot
include json
step = bot.get("lead_step") ?? ""
answer = $message.trim

fn ask(field, question, options = nil) {
  bot.set("lead_step", field)
  bot.say(question)
  bot.buttons(options) if options != nil
  bot.wait()
}

fn phone(s) {
  d = s.replace(/\D/, "")
  d = "7" + d.drop(1) if d.len == 11 && d.starts_with("8")
  d = "7" + d if d.len == 10
  d ~ /\A7\d{10}\z/ ? "+" + d : nil
}

if step == "lead_name" && !answer.blank {
  bot.set("lead_name", answer.capitalize)
} else if step == "lead_phone" {
  p = phone(answer)
  if p == nil { bot.say("That doesn't look like a number. Example: +7 999 123-45-67") } else { bot.set("lead_phone", p) }
} else if step == "confirm" && answer == "No" {
  bot.set("lead_name", "")
  bot.set("lead_phone", "")
} else if step == "confirm" && answer == "Yes" {
  r = bot.http({
    method: "POST",
    url: "https://crm.example.com/api/leads",
    body: {name: bot.get("lead_name"), phone: bot.get("lead_phone")}.json,
  })
  bot.set("lead_step", "")
  bot.say(r["ok"] ? "Request received, we'll call you back within 15 minutes." : "Couldn't send it — please email us.")
  bot.exit(r["ok"] ? "next" : "error")
  exit()
}

name = bot.get("lead_name") ?? ""
tel = bot.get("lead_phone") ?? ""
ask("lead_name", "What should we call you?") if name.blank
ask("lead_phone", "Your phone number?") if tel.blank
ask("confirm", "Please check: **${name}**, ${tel}. Is that right?", ["Yes", "No"])
text
What should we call you?

Opening hours ​

Exits: open, closed. The server clock is UTC — convert to your time zone.

mzs
include bot
include time
now = time.now.in_time_zone("Europe/Moscow")
weekend = now.wday == 0 || now.wday == 6
from = weekend ? 10 : 9
till = weekend ? 18 : 21
holidays = ["01-01", "01-02", "05-09"]
if !(now.strftime("%m-%d") in holidays) && now.hour >= from && now.hour < till {
  bot.exit("open")
} else {
  bot.say("We're closed now: weekdays 9–21, weekends 10–18 (Moscow time). Leave a message — we'll answer in the morning.")
  bot.exit("closed")
}

Price with a discount and a promo code ​

Price and quantity come from dialogue variables, the current promo code from the bot variable promo.

mzs
include bot
price = bot.get("price").int
qty = max(bot.get("qty").int, 1)
codes = {(bot.store_get("promo") ?? "SALE10"): 10, "VIP20": 20}
promo = $message.upper.matches(/[A-Z0-9]{4,12}/).find { it in codes }
pct = codes[promo] ?? 0
pct = max(pct, 5) if qty >= 2
subtotal = price * qty
discount = (subtotal * pct / 100.0).round
fn rub(n) { n.str.replace(/\B(?=(\d{3})+(?!\d))/, ",") + " ₽" }
lines = ["${qty} × ${rub(price)} = ${rub(subtotal)}"]
lines.push("Discount ${pct}%: −${rub(discount)}") if pct > 0
lines.push("**Total: ${rub(subtotal - discount)}**")
bot.say(lines.join("\n"))
bot.set("total", subtotal - discount)
text
2 × 1,500 ₽ = 3,000 ₽
Discount 5%: −150 ₽
**Total: 2,850 ₽**

Sorting requests with the language model ​

Exits: order, price, human. If the model is unavailable — simple rules.

mzs
include bot
include llm
fn by_words(s) {
  match s.lower {
    /order|deliver|track/ -> "order"
    /price|cost|how much/ -> "price"
    else -> "human"
  }
}
r = try llm.ask(
  "Customer message: ${$message}\nReturn JSON {\"intent\": \"order_status\" | \"price\" | \"other\", \"order_id\": string or null}",
  {system: "You classify requests to a shop.", json: true, temperature: 0, max_tokens: 60},
) else nil
intent = match r?.dig("intent") {
  "order_status" -> "order"
  "price" -> "price"
  nil -> by_words($message)
  else -> "human"
}
bot.set("order_id", r?.dig("order_id") ?? "")
bot.exit(intent)
bot.get("order_id")  # → "10452"
intent  # → "order"

A scheduled exchange rate, converted in the dialogue ​

A scheduled script (e.g. 0 * * * *) puts the rate into a bot variable:

mzs
include bot
include json
include time
r = bot.http({url: "https://api.example.com/rates?base=USD"})
raise("no rate: ${r["error"].blank ? r["status"] : r["error"]}") if !r["ok"]
rate = json.parse(r["body"]).dig("rates", "RUB")
raise("no RUB in the response") if rate == nil
bot.store_set("usd_rate", rate)
bot.store_set("usd_rate_at", time.now.strftime("%d.%m %H:%M"))

A script in the dialogue reads it with no requests:

mzs
include bot
rate = (bot.store_get("usd_rate") ?? "0").float
sum = bot.get("price").int
if rate == 0 {
  bot.say("The rate isn't known yet, please try later.")
  exit()
}
bot.say("${sum} ₽ ≈ $${"%.2f" % [sum / rate]} at the rate of ${rate}")
text
1500 ₽ ≈ $16.22 at the rate of 92.5

A catalogue from an API: buttons and a choice ​

The first run shows the products as buttons, the second gets the choice and replaces the question with it. Exit «дальше» (next) — a product is chosen.

mzs
include bot
include json
r = bot.http({url: "https://cafe.example.com/products"})
items = r["ok"] ? (json.parse(r["body"])["items"] ?? []) : []
if items.empty {
  bot.say("The menu is unavailable right now.")
  bot.exit("error")
  exit()
}
names = items.map { it["name"] }.take(10)
if (bot.get("menu_msg") ?? "").blank || !names.has($message.trim) {
  bot.set("menu_msg", bot.say("Choose a drink:"))
  bot.buttons(names)
  bot.wait()
}
item = items.find { it["name"] == $message.trim }
bot.set("item", item["name"])
bot.set("item_price", item["price"])
bot.edit(bot.get("menu_msg"), "You chose: **${item["name"]}** — ${item["price"]} ₽")
bot.set("menu_msg", "")
text
Choose a drink:
[Cappuccino] [Latte] [Raf]

An SMS code: three attempts ​

The previous block sent the code and saved it in $sms_code. Exits: yes — the code is right, other — out of attempts.

mzs
include bot
tries = (bot.get("code_tries") ?? "0").int
if tries > 0 && $message.trim == bot.get("sms_code") {
  bot.set("code_tries", 0)
  bot.exit("yes")
  exit()
}
if tries >= 3 {
  bot.set("code_tries", 0)
  bot.say("The code was wrong 3 times. Connecting you to a manager.")
  bot.exit("other")
  exit()
}
bot.set("code_tries", tries + 1)
bot.say(tries == 0 ? "Enter the code from the SMS — 4 digits." : "The code is 4 digits. Attempts left: ${3 - tries}")
bot.wait()
text
Enter the code from the SMS — 4 digits.

Answers by keywords ​

No exits: answers by itself, and hands the unknown to an operator through a variable.

mzs
include bot
faq = [
  [/deliver|courier|shipping/, "We deliver in 1–2 days, free in the city from 2000 ₽."],
  [/pay|card|cash/, "Pay by card on the website or to the courier on delivery."],
  [/return|refund|exchange/, "You can return an item within 14 days."],
  [/where.*order|status|track/, "The order status is in the email, or send the order number here in the chat."],
]
s = $message.lower
hit = faq.find { s ~ it[0] }
if hit != nil {
  bot.say(hit[1])
} else {
  bot.set("need_operator", true)
  bot.say("I'll pass your question to an operator — they'll answer here.")
}
text
The order status is in the email, or send the order number here in the chat.