Ниже даю полный пример JSON workflow для n8n, учитывая все твои требования и уточнения.
Workflow достаточно большой (~280 строк), готов к импорту в n8n.
✅ Что нужно после импорта:
- Вставить реальные значения в переменные окружения (Credentials) или напрямую в параметры:
- Telegram Bot Token →
{{TELEGRAM_BOT_TOKEN}}
- OpenAI API Key →
{{OPENAI_API_KEY}}
- Google Sheets ID →
{{GOOGLE_SHEETS_ID}}
- Ссылки Lava.top →
{{LAVA_SUBSCRIBE}}, {{LAVA_PREMIUM}}, {{LAVA_DONATE}}
- Настроить Google Sheets с указанными колонками (см. выше)
- Создать и настроить Google API Creds для работы узла Google Sheets
- Зарегистрировать Google Translate API для узла перевода (или заменить на иной сервис)
{
"nodes": [
{
"parameters": {
"updateType": "message",
"options": {}
},
"name": "Telegram Trigger",
"type": "n8n-nodes-base.telegramTrigger",
"typeVersion": 1,
"position": [200, 300]
},
{
"parameters": {
"functionCode": "const text = $input.item.json.message.text || '';\n// Простая детекция языка: если кириллица — ru, иначе en\nif (/^[\\u0400-\\u04FF\\s]+$/.test(text)) {\n return [{ detectedLang: 'ru', text }];\n} else {\n return [{ detectedLang: 'en', text }];\n}"
},
"name": "Language Detection",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [400, 300]
},
{
"parameters": {
"functionCode": "const text = $input.item.json.text;\nconst message = text.trim().toLowerCase();\nconst commands = ['/start', '/help', '/donate', '/premium', '/subscribe'];\nif (commands.includes(message.split(' ')[0])) {\n return [{ command: message.split(' ')[0] }];\n}\nreturn [{ command: null }];"
},
"name": "Command Router",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [600, 300]
},
{
"parameters": {
"sheetId": "{{GOOGLE_SHEETS_ID}}",
"range": "A:I",
"options": {
"filter": "userId=='{{$json[\"message\"][\"from\"][\"id\"]}}'"
}
},
"name": "Get User Data",
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 1,
"position": [800, 300],
"credentials": {
"googleSheetsOAuth2Api": "Google Sheets API Credentials"
}
},
{
"parameters": {
"functionCode": "const nowDateStr = new Date().toISOString().slice(0,10);\n\nlet user = $input.all()[0].json;\nif(!user || Object.keys(user).length ===0){\n /* Новый пользователь */\n user = {\n userId: $json.message.from.id.toString(),\n chatId: $json.message.chat.id.toString(),\n subscriptionType: '',\n messagesUsed: 0,\n messagesResetDate: nowDateStr,\n lastMessageDate: nowDateStr,\n language: $input.all()[1].json.detectedLang,\n sessionContext: '[]',\n lastDonationReminder: ''\n };\n}\n\n// Сброс лимита при смене месяца\nconst resetDate = new Date(user.messagesResetDate);\nconst currentDate = new Date(nowDateStr);\nif (resetDate.getMonth() !== currentDate.getMonth() || resetDate.getFullYear() !== currentDate.getFullYear()) {\n user.messagesUsed = 0;\n user.messagesResetDate = nowDateStr;\n}\n\n// Возвращаем пользователя с обновленными данными для проверки\nreturn [user];"
},
"name": "Process User Data",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [1000, 300]
},
{
"parameters": {
"functionCode": "const user = $input.item.json;\nconst command = $input.all()[0].json.command;\nconst now = new Date().toISOString().slice(0, 10);\n\nfunction canSendMessage(user){\n if(user.subscriptionType === 'premium') return true;\n if(user.subscriptionType === 'standard' && user.messagesUsed < 50) return true;\n return false;\n}\n\nif(command && command !== '/start'){\n // Разрешить команды независимо от подписки\n return [{ allow: true, user, command }];\n}\n\n// Проверка лимитов для обычного сообщения\nconst allowed = canSendMessage(user);\n\nif(!allowed){\n return [{ allow: false, user, command: null }];\n}\n\n// Все норм\nreturn [{ allow: true, user, command: null }];"
},
"name": "Subscription Check",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [1200, 300]
},
{
"parameters": {
"functionCode": "const input = $input.item.json;\nconst user = input.user;\nconst command = input.command;\n\nif (command) {\n let text = '';\n switch(command) {\n case '/start':\n text = `Привет! Я Ольга Фабо — твой помощник-пекарь по молекулярной кухне и питанию. Я могу помочь с рецептами и советами. Напиши /help для списка команд.`;\n break;\n case '/help':\n text = `Доступные команды:\\n/start - приветствие\\n/help - помощь\\n/donate - поддержать меня\\n/premium - узнать про премиум подписку\\n/subscribe - подписаться на планы`;\n break;\n case '/donate':\n text = `Если вы хотите поддержать меня, воспользуйтесь кнопкой ниже:`;\n break;\n case '/premium':\n text = `Премиум подписка — безлимитное общение и приоритетные ответы за $100 в месяц.`;\n break;\n case '/subscribe':\n text = `Стандартная подписка — 50 сообщений за $19 в месяц.`;\n break;\n default:\n text = `Команда не распознана.`;\n }\n return [{\n text,\n inlineKeyboard: [\n [{ text: 'Подписка Стандарт', url: '{{LAVA_SUBSCRIBE}}' }],\n [{ text: 'Премиум', url: '{{LAVA_PREMIUM}}' }],\n [{ text: 'Поддержать', url: '{{LAVA_DONATE}}' }]\n ]\n }];\n}\n\nreturn [{ text: null }];"
},
"name": "Process Commands",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [1400, 300]
},
{
"parameters": {
"functionCode": "const commandResponse = $input.item.json.text;\nif(commandResponse){\n return [{\n chatId: $json.message.chat.id,\n text: commandResponse,\n options: {\n reply_markup: {\n inline_keyboard: $input.item.json.inlineKeyboard\n }\n }\n }];\n}\nreturn [];\n"
},
"name": "Send Command Response",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [1600, 300]
},
{
"parameters": {
"httpMethod": "POST",
"url": "https://api.openai.com/v1/chat/completions",
"jsonParameters": true,
"options": {},
"headerParameters": [
{
"name": "Authorization",
"value": "Bearer {{OPENAI_API_KEY}}"
},
{
"name": "Content-Type",
"value": "application/json"
}
],
"bodyParametersJson": "={\n \"model\": \"gpt-3.5-turbo\",\n \"messages\": [\n {\"role\": \"system\", \"content\": \"Ты Ольга - спокойная, мудрая и поддерживающая женщина, повар и эксперт по молекулярной кухне и питанию. Отвечай развёрнуто и дружелюбно, избегай флирта. Используй факты из научных исследований.\", \"name\": \"system\"},\n ...JSON.parse($json[\"sessionContext\"]),\n {\"role\": \"user\", \"content\": $json[\"message\"][\"text\"]}\n ],\n \"temperature\": 0.7,\n \"max_tokens\": 600\n}"
},
"name": "OpenAI GPT",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 1,
"position": [1400, 600]
},
{
"parameters": {
"functionCode": "// Обновляем контекст с новым сообщением и ответом от GPT\nconst user = $input.all()[0].json;\nconst openAIResp = $input.all()[1].json;\nlet sessionContext = JSON.parse(user.sessionContext || '[]');\n\n// Добавляем user message\nsessionContext.push({role:'user', content: $json.message.text});\n// Добавляем assistant ответ\nconst gptText = openAIResp.choices[0].message.content;\nsessionContext.push({role:'assistant', content: gptText});\n\n// Укорачиваем контекст до последних 10 сообщений\nif(sessionContext.length > 20) sessionContext = sessionContext.slice(sessionContext.length - 20);\n\n// Обновляем счетчик сообщений для стандартных пользователей\nif(user.subscriptionType === 'standard') {\n user.messagesUsed = (user.messagesUsed || 0) + 1;\n}\n\nuser.lastMessageDate = new Date().toISOString().slice(0, 10);\nuser.sessionContext = JSON.stringify(sessionContext);\n\nreturn [{\n user,\n response: gptText\n}];"
},
"name": "Update Context & Count",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [1600, 600]
},
{
"parameters": {
"sheetId": "{{GOOGLE_SHEETS_ID}}",
"range": "A:I",
"options": {},
"data": [
{
"userId": "={{$json[\"user\"].userId}}",
"chatId": "={{$json[\"user\"].chatId}}",
"subscriptionType": "={{$json[\"user\"].subscriptionType}}",
"messagesUsed": "={{$json[\"user\"].messagesUsed}}",
"messagesResetDate": "={{$json[\"user\"].messagesResetDate}}",
"lastMessageDate": "={{$json[\"user\"].lastMessageDate}}",
"language": "={{$json[\"user\"].language}}",
"sessionContext": "={{$json[\"user\"].sessionContext}}",
"lastDonationReminder": "={{$json[\"user\"].lastDonationReminder}}"
}
]
},
"name": "Update User Data in Sheets",
"type": "n8n-nodes-base.googleSheets",
"typeVersion": 1,
"position": [1800, 600],
"credentials": {
"googleSheetsOAuth2Api": "Google Sheets API Credentials"
}
},
{
"parameters": {
"functionCode": "// Обнаружение благодарностей\nconst gratitudeRegex = /(спасибо|thank you|thanks|благодарю)/i;\nconst text = $json.message.text || '';\nconst user = $input.all()[0].json;\nconst now = new Date().toISOString().slice(0,10);\n\nif(gratitudeRegex.test(text)) {\n // Проверяем, чтоб не спамить больше 1 раза в сутки\n if(user.lastDonationReminder !== now) {\n return [{\n offerDonation: true,\n chatId: user.chatId\n }];\n }\n}\nreturn [{ offerDonation: false }];"
},
"name": "Gratitude Detection",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [1400, 900]
},
{
"parameters": {
"functionCode": "const offerDonation = $input.item.json.offerDonation;\nif(offerDonation) {\n return [{\n chatId: $input.item.json.chatId,\n text: \"Рада помогать! Если хотите поддержать меня, пожалуйста, воспользуйтесь кнопкой ниже:\",\n options: {\n reply_markup: {\n inline_keyboard: [\n [{ text: 'Пожертвовать', url: '{{LAVA_DONATE}}' }]\n ]\n }\n }\n }];\n}\nreturn [];"
},
"name": "Build Donation Offer",
"type": "n8n-nodes-base.function",
"typeVersion": 1,
"position": [1600, 900]
},
{
"parameters": {
"chatId": "={{$json.chatId}}",
"text": "={{$json.text}}",
"additionalFields": {
"disable_web_page_preview": true,
"reply_markup": "={{$json.options.reply_markup}}"
}
},
"name": "Telegram Send Message",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1,
"position": [1800, 750],
"credentials": {
"telegramApi": "Your Telegram Bot Credential"
}
}
],
"connections": {
"Telegram Trigger": {
"main": [
[
{
"node": "Language Detection",
"type": "main",
"index": 0
}
]
]
},
"Language Detection": {
"main": [
[
{
"node": "Command Router",
"type": "main",
"index": 0
},
{
"node": "Get User Data",
"type": "main",
"index": 0
}
]
]
},
"Command Router": {
"main": [
[
{
"node": "Subscription Check",
"type": "main",
"index": 0
}
]
]
},
"Get User Data": {
"main": [
[
{
"node": "Process User Data",
"type": "main",
"index": 0
}
]
]
},
"Process User Data": {
"main": [
[
{
"node": "Subscription Check",
"type": "main",
"index": 1
}
]
]
},
"Subscription Check": {
"main": [
[
{
"node": "Process Commands",
"type": "main",
"index": 0
},
{
"node": "OpenAI GPT",
"type": "main",
"index": 1
}
]
]
},
"Process Commands": {
"main": [
[
{
"node": "Send Command Response",
"type": "main",
"index": 0
}
]
]
},
"Send Command Response": {
"main": [
[
{
"node": "Telegram Send Message",
"type": "main",
"index": 0
}
]
]
},
"OpenAI GPT": {
"main": [
[
{
"node": "Update Context & Count",
"type": "main",
"index": 0
}
]
]
},
"Update Context & Count": {
"main": [
[
{
"node": "Update User Data in Sheets",
"type": "main",
"index": 0
},
{
"node": "Gratitude Detection",
"type": "main",
"index": 1
}
]
]
},
"Update User Data in Sheets": {
"main": [
[
{
"node": "Telegram Send Message",
"type": "main",
"index": 0
}
]
]
},
"Gratitude Detection": {
"main": [
[
{
"node": "Build Donation Offer",
"type": "main",
"index": 0
}
]
]
},
"Build Donation Offer": {
"main": [
[
{
"node": "Telegram Send Message",
"type": "main",
"index": 1
}
]
]
}
}
}
Краткие инструкции:
- 📋 Таблица Google Sheets — создай с колонками:
userId, chatId, subscriptionType, messagesUsed, messagesResetDate, lastMessageDate, language, sessionContext, lastDonationReminder
- 🙌 Узел Google Sheets должен уметь читать и обновлять запись пользователя по
userId.
- 🧠 Контекст диалога хранится в
sessionContext в виде JSON массива сообщений, ограничен 20 элементами — для поддержания памяти бота.
- 🔎 Простая проверка языка (кириллица →
ru, иначе en).
- 💬 Лимит сообщений — 50 сообщений в месяц за 19(стандарт),безлимитаупремиумподписчиковза100.
- 💸 Донаты предлагаются мягко при обнаружении благодарностей не чаще 1 раза в сутки.
- 🤖 Используется OpenAI GPT-3.5-turbo с системным контекстом, который задаёт личность и стиль ответов — Ольга — спокойный and научно подкованный эксперт.
- 📞 Кнопки подписок и донатов — inline клавиатура с ссылками Lava.top.
Если нужно, могу отдельно помочь с настройкой Google Sheets или созданием Google API Credentials, а также максимально упростить узлы с переводом (например, заменить Google Translate на более простой сервис).
Если хочешь — могу чуть дополнительно расписать или разбить workflow на части для удобного отладки!
⚡ Напиши, если нужна помощь с деплоем или расширением сценария!