{
  "name": "Rytm Studio: Telegram AI bot that answers and books classes",
  "nodes": [
    {
      "parameters": {
        "content": "## Setup\n1. **Telegram**: create a bot with @BotFather. Add its token as a Telegram credential in *Telegram Trigger*, *Show typing*, *Alert owner*, *Reply to client* and *Send reminder*.\n2. **Owner chat ID**: write to your bot once, open the *Telegram Trigger* output and copy `message.chat.id` into *Alert owner*.\n3. **OpenAI**: add an API key in *OpenAI Chat Model*.\n4. **Google Sheets**: one file with two tabs. Paste the file ID in *Free spots*, *Book class* and *Read bookings*.\n   - **Schedule**: Class time | Class | Capacity | Booked | Spots left. Booked: `=COUNTIFS(Bookings!E:E,A2,Bookings!H:H,\"Booked\")`, Spots left: `=C2-D2`.\n   - **Bookings**: Booked at | Name | Phone | Class | Class time | Language | Chat ID | Status.\n   - Format both Class time columns as plain text, like 2026-12-10 19:00.\n5. Put your classes, prices, address and rules into the *AI Agent* system message.\n6. Activate the workflow and write to your bot.\n\n*Chat memory* keeps the last 10 messages of each chat inside n8n and is cleared when n8n restarts. For queue mode, use Postgres or Redis chat memory instead.",
        "height": 560,
        "width": 520
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1001",
      "name": "Setup",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [-1200, -420]
    },
    {
      "parameters": {
        "updates": ["message"],
        "additionalFields": {}
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1002",
      "name": "Telegram Trigger",
      "type": "n8n-nodes-base.telegramTrigger",
      "typeVersion": 1.1,
      "position": [-600, 0],
      "webhookId": "4d8c2b6e-1f3a-4c5d-9e7b-8a2f6c1d3e01"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Take the text, chat and client name from the Telegram update.\nconst msg = $json.message || {};\nconst from = msg.from || {};\nlet text = String(msg.text || msg.caption || '').trim();\n\n// Menu language: Ukrainian for Cyrillic, Polish for Polish letters or words, otherwise English or the Telegram app language.\nconst appLang = String(from.language_code || '').slice(0, 2);\nlet lang = 'en';\nif (/[а-яёіїєґ]/i.test(text)) lang = 'uk';\nelse if (/[ąćęłńóśźż]/i.test(text) || /\\b(czy|jest|ile|jutro|zapisz|cennik|grafik|tak|nie)\\b/i.test(text)) lang = 'pl';\nelse if (!/\\b(the|is|how|what|when|where|book|price|hi|hello|yes|no)\\b/i.test(text) && ['pl', 'uk'].includes(appLang)) lang = appLang;\n\n// Non-text messages and /start become short notes for the agent.\nif (!text && msg.contact) text = `My phone number: ${msg.contact.phone_number}`;\nif (!text) text = '[The client sent a sticker, photo or voice message without text]';\nif (text === '/start') text = 'Hi! (The client has just opened the bot.)';\n\nreturn {\n  json: {\n    chatId: (msg.chat || {}).id,\n    firstName: from.first_name || '',\n    username: from.username || '',\n    text: text.slice(0, 1500),\n    lang\n  }\n};"
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1003",
      "name": "Prepare message",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [-380, 0]
    },
    {
      "parameters": {
        "operation": "sendChatAction",
        "chatId": "={{ $json.chatId }}",
        "action": "typing"
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1004",
      "name": "Show typing",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [-160, 0],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $('Prepare message').item.json.text }}",
        "options": {
          "systemMessage": "=You are the Telegram assistant of Rytm Studio, a pilates and yoga studio in Warsaw.\nNow: {{ $now.setZone('Europe/Warsaw').toFormat('cccc yyyy-MM-dd HH:mm') }} (Europe/Warsaw).\n\nStudio facts:\n- Classes: Pilates 55 min, Yoga 60 min, Stretching 50 min. Up to 10 people per class. Beginners are welcome in every class.\n- Prices: trial class (first visit) 25 PLN, single class 50 PLN, 8 classes within 30 days 290 PLN, unlimited month 390 PLN. Payment at the studio, by card or cash.\n- Address: ul. Przykładowa 12, Warsaw, 5 minutes from the metro. Changing rooms with showers, bike racks. Mats and towels are provided.\n- Free cancellation up to 12 hours before the class.\n\nRules:\n- Reply in the language of the client's last message: Polish, English or Ukrainian. Be short and friendly: 1 to 4 sentences or a short numbered list.\n- For times and free places, always call the \"Free spots\" tool. Offer at most 3 options that have Spots left above 0, numbered 1 to 3. Never invent times.\n- To book you need: the class, a Class time from the Schedule sheet, the client's name and phone number. Ask only for what is missing.\n- Before booking, repeat the class, day, time, name and phone, and ask the client to confirm.\n- After a clear yes: call \"Free spots\" again to check the place is still free, then call \"Book class\" once. Then confirm the booking and say a reminder comes the day before.\n- If you do not know the answer, or the client asks for a person, wants to cancel or complains: say the studio team will reply in this chat, and end your message with [[HANDOFF]].\n- Never ask for card details or passwords. Do not answer questions unrelated to the studio.",
          "maxIterations": 6,
          "returnIntermediateSteps": true
        }
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1005",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 2,
      "position": [80, 0]
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {
          "temperature": 0.3
        }
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1006",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [-80, 260]
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Prepare message').item.json.chatId }}",
        "contextWindowLength": 10
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1007",
      "name": "Chat memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [80, 260]
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Returns the Schedule sheet: Class time, Class, Capacity, Booked and Spots left for the coming days. Call it before offering times and again right before booking.",
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_GOOGLE_SHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Schedule"
        },
        "options": {}
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1008",
      "name": "Free spots",
      "type": "n8n-nodes-base.googleSheetsTool",
      "typeVersion": 4.6,
      "position": [240, 260]
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Saves a confirmed booking as a new row in the Bookings sheet. Call it once, only after the client clearly confirmed the class, time, name and phone.",
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_GOOGLE_SHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Bookings"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Booked at": "={{ $now.setZone('Europe/Warsaw').toFormat('yyyy-MM-dd HH:mm') }}",
            "Name": "={{ $fromAI('Name', 'Client name as the client gave it', 'string') }}",
            "Phone": "={{ $fromAI('Phone', 'Client phone number as the client gave it', 'string') }}",
            "Class": "={{ $fromAI('Class', 'Pilates, Yoga or Stretching', 'string') }}",
            "Class time": "={{ $fromAI('Class_time', 'Exactly as in the Class time column of the Schedule sheet, for example 2026-12-10 19:00', 'string') }}",
            "Language": "={{ $fromAI('Language', 'Language of the client: pl, en or uk', 'string') }}",
            "Chat ID": "={{ $('Prepare message').item.json.chatId }}",
            "Status": "Booked"
          },
          "matchingColumns": [],
          "schema": [
            { "id": "Booked at", "displayName": "Booked at", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "Name", "displayName": "Name", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "Phone", "displayName": "Phone", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "Class", "displayName": "Class", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "Class time", "displayName": "Class time", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "Language", "displayName": "Language", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "Chat ID", "displayName": "Chat ID", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "Status", "displayName": "Status", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1009",
      "name": "Book class",
      "type": "n8n-nodes-base.googleSheetsTool",
      "typeVersion": 4.6,
      "position": [400, 260]
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Read the agent's answer and its tool calls: was a class booked? Should a person reply?\nconst prep = $('Prepare message').item.json;\nconst raw = String($json.output || '');\nconst handoff = raw.includes('[[HANDOFF]]');\nconst reply = raw.replace(/\\[\\[HANDOFF\\]\\]/g, '').trim() || 'Sorry, could you write that again?';\n\n// \"Return Intermediate Steps\" is on in the AI Agent, so every tool call is listed here.\nconst steps = Array.isArray($json.intermediateSteps) ? $json.intermediateSteps : [];\nconst bookingStep = steps.find((step) => /book/i.test((step.action && step.action.tool) || ''));\n\nlet ownerText = '';\nif (bookingStep) {\n  const b = bookingStep.action.toolInput || {};\n  const saved = !/error/i.test(JSON.stringify(bookingStep.observation || ''));\n  ownerText = `${saved ? '🆕 New booking' : '⚠️ Booking was NOT saved, please check'}\\n🧘 ${b.Class || '?'} · ${b.Class_time || '?'}\\n👤 ${b.Name || prep.firstName} · ${b.Phone || '?'}\\n🗣 ${b.Language || prep.lang} · chat ${prep.chatId}`;\n} else if (handoff) {\n  const who = [prep.firstName, prep.username ? '@' + prep.username : ''].filter(Boolean).join(' ') || 'Client';\n  ownerText = `🙋 A client needs a person\\n💬 “${prep.text.slice(0, 400)}”\\n👤 ${who} · chat ${prep.chatId}\\n🗣 ${prep.lang}`;\n}\n\nconst menus = {\n  en: { prices: '💰 Prices', schedule: '📅 Schedule', book: '✍️ Book a class' },\n  pl: { prices: '💰 Cennik', schedule: '📅 Grafik', book: '✍️ Zapisz się' },\n  uk: { prices: '💰 Ціни', schedule: '📅 Розклад', book: '✍️ Записатися' }\n};\n\nreturn {\n  json: {\n    chatId: prep.chatId,\n    reply,\n    ownerText,\n    notifyOwner: ownerText !== '',\n    menu: menus[prep.lang] || menus.en\n  }\n};"
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1010",
      "name": "Check result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [440, 0]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "5f0c7a3e-2b1d-4e8f-9a6c-3d2e1f0a9b01",
              "leftValue": "={{ $json.notifyOwner }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1011",
      "name": "Owner needs to know?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [660, 0]
    },
    {
      "parameters": {
        "chatId": "YOUR_OWNER_CHAT_ID",
        "text": "={{ $json.ownerText }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1012",
      "name": "Alert owner",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [880, -120],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "chatId": "={{ $('Check result').item.json.chatId }}",
        "text": "={{ $('Check result').item.json.reply }}",
        "replyMarkup": "replyKeyboard",
        "replyKeyboard": {
          "rows": [
            {
              "row": {
                "buttons": [
                  { "text": "={{ $('Check result').item.json.menu.prices }}", "additionalFields": {} },
                  { "text": "={{ $('Check result').item.json.menu.schedule }}", "additionalFields": {} }
                ]
              }
            },
            {
              "row": {
                "buttons": [
                  { "text": "={{ $('Check result').item.json.menu.book }}", "additionalFields": {} }
                ]
              }
            }
          ]
        },
        "replyKeyboardOptions": {
          "resize_keyboard": true
        },
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1013",
      "name": "Reply to client",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [1100, 0]
    },
    {
      "parameters": {
        "content": "## Daily reminder\nEvery day at 18:00 (the workflow time zone is Europe/Warsaw, see Settings) each client with a booking for tomorrow gets a reminder in their language. Rows with another Status, for example Cancelled, are skipped.",
        "height": 220,
        "width": 520
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1014",
      "name": "Reminder note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [-1200, 520]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 18
            }
          ]
        }
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1015",
      "name": "Every day at 18:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [-600, 600]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_GOOGLE_SHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Bookings"
        },
        "options": {}
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1016",
      "name": "Read bookings",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.6,
      "position": [-380, 600]
    },
    {
      "parameters": {
        "jsCode": "// Keep active bookings for tomorrow and write a reminder in the client's language.\nconst tomorrow = $now.setZone('Europe/Warsaw').plus({ days: 1 }).toFormat('yyyy-MM-dd');\nconst names = {\n  pl: { Pilates: 'Pilates', Yoga: 'Joga', Stretching: 'Stretching' },\n  uk: { Pilates: 'Пілатес', Yoga: 'Йога', Stretching: 'Стретчинг' }\n};\nconst texts = {\n  pl: (time, cls) => `Przypomnienie: jutro o ${time} masz zajęcia ${cls} w Rytm Studio, ul. Przykładowa 12. Do zobaczenia!`,\n  uk: (time, cls) => `Нагадування: завтра о ${time} у вас заняття ${cls} у Rytm Studio, ul. Przykładowa 12. До зустрічі!`,\n  en: (time, cls) => `Reminder: ${cls} tomorrow at ${time} at Rytm Studio, ul. Przykładowa 12. See you there!`\n};\n\nreturn $input.all()\n  .map((item) => item.json)\n  .filter((row) => String(row['Class time'] || '').startsWith(tomorrow) && row.Status === 'Booked' && row['Chat ID'])\n  .map((row) => {\n    const lang = texts[row.Language] ? row.Language : 'en';\n    const time = String(row['Class time']).slice(11, 16);\n    const cls = (names[lang] && names[lang][row.Class]) || row.Class;\n    return { json: { chatId: row['Chat ID'], text: texts[lang](time, cls) } };\n  });"
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1017",
      "name": "Tomorrow's classes",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [-160, 600]
    },
    {
      "parameters": {
        "chatId": "={{ $json.chatId }}",
        "text": "={{ $json.text }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "id": "9e3f6a10-5b7c-4d2e-8f41-2a6c0b7d1018",
      "name": "Send reminder",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [60, 600],
      "onError": "continueRegularOutput"
    }
  ],
  "connections": {
    "Telegram Trigger": { "main": [[{ "node": "Prepare message", "type": "main", "index": 0 }]] },
    "Prepare message": { "main": [[{ "node": "Show typing", "type": "main", "index": 0 }]] },
    "Show typing": { "main": [[{ "node": "AI Agent", "type": "main", "index": 0 }]] },
    "OpenAI Chat Model": { "ai_languageModel": [[{ "node": "AI Agent", "type": "ai_languageModel", "index": 0 }]] },
    "Chat memory": { "ai_memory": [[{ "node": "AI Agent", "type": "ai_memory", "index": 0 }]] },
    "Free spots": { "ai_tool": [[{ "node": "AI Agent", "type": "ai_tool", "index": 0 }]] },
    "Book class": { "ai_tool": [[{ "node": "AI Agent", "type": "ai_tool", "index": 0 }]] },
    "AI Agent": { "main": [[{ "node": "Check result", "type": "main", "index": 0 }]] },
    "Check result": { "main": [[{ "node": "Owner needs to know?", "type": "main", "index": 0 }]] },
    "Owner needs to know?": {
      "main": [
        [{ "node": "Alert owner", "type": "main", "index": 0 }],
        [{ "node": "Reply to client", "type": "main", "index": 0 }]
      ]
    },
    "Alert owner": { "main": [[{ "node": "Reply to client", "type": "main", "index": 0 }]] },
    "Every day at 18:00": { "main": [[{ "node": "Read bookings", "type": "main", "index": 0 }]] },
    "Read bookings": { "main": [[{ "node": "Tomorrow's classes", "type": "main", "index": 0 }]] },
    "Tomorrow's classes": { "main": [[{ "node": "Send reminder", "type": "main", "index": 0 }]] }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Warsaw"
  }
}
