{
  "name": "Telegram Notes to Notion with AI",
  "nodes": [
    {
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegramTrigger",
      "typeVersion": 1.2,
      "position": [
        -480,
        -96
      ],
      "id": "2e611889-5d54-452f-bf21-bd77ad4c760e",
      "name": "Telegram Trigger",
      "webhookId": "aec90e60-f9fb-41a4-bd3c-846926955abc",
      "credentials": {
        "telegramApi": {
          "id": "bFjsHGFg2wTqHaNG",
          "name": "Assistant"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "user-filter-condition",
              "leftValue": "={{ $json.message.from.id }}",
              "rightValue": 354573537,
              "operator": {
                "type": "number",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        -336,
        -96
      ],
      "id": "b9d96ded-cf6c-4de7-8103-9f09a54818da",
      "name": "Check User ID"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.message.text }}",
                    "rightValue": "",
                    "operator": {
                      "type": "string",
                      "operation": "exists",
                      "singleValue": true
                    },
                    "id": "ea01e283-d967-41b5-aaa9-bf44fb1fd011"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Text"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "4654449d-0e6f-4e24-9e23-a5d926cb5ad6",
                    "leftValue": "={{ $json.message.voice.file_id }}",
                    "rightValue": "",
                    "operator": {
                      "type": "string",
                      "operation": "exists",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Voice"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        -160,
        -96
      ],
      "id": "381bc95d-cd00-4a07-adc1-b677a2d124bb",
      "name": "Switch"
    },
    {
      "parameters": {
        "resource": "file",
        "fileId": "={{ $json.message.voice.file_id }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        16,
        32
      ],
      "id": "e0d15e63-9f14-4185-96b3-14d2a43095a4",
      "name": "Get a file",
      "webhookId": "6a69002c-f689-4665-bb64-1466feb4b629",
      "credentials": {
        "telegramApi": {
          "id": "bFjsHGFg2wTqHaNG",
          "name": "Assistant"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=User Message: {{ $json.messageText }}\\n\\nFull Content with Links:\\n{{ $json.fullContent }}\\n\\nExtract and return: Title, Type, Category, NoteContent (use fullContent above), Created At",
        "options": {
          "systemMessage": "## Role\\nYou are an assistant for capturing user notes. The user sends messages via Telegram. Treat each message as a note that should be saved in Notion.\\n\\n## Purpose\\nYou will analyze each note and extract the following:\\n1. **Type** – to define the note type. Possible values: *Question, Task, Idea, Observation, Research*.\\n2. **Category** – to define the note category. Possible values: *Customers, CRM, Marketing, Social Media, Personal, Offers, Projects*.\\n3. **Title** – generate a concise title based solely on the note content. Do NOT include dates in the title.\\n4. **Created At** – store the creation date in format YYYY-MM-DD.\\n5. **NoteContent** – YOU WILL RECEIVE THIS FIELD PRE-FORMATTED WITH LINKS in the user message as \\"Full Content with Links\\". Use it EXACTLY as provided.\\n\\n## CRITICAL Instructions\\n- The user message contains \\"Full Content with Links\\" - this is the complete NoteContent\\n- You MUST return the \\"NoteContent\\" field in your AddNote function call\\n- Use the fullContent exactly as provided - do NOT modify it\\n- ALWAYS include all 5 fields: Type, Category, Title, NoteContent, and Created At\\n\\nDo not ask for confirmation — simply prepare the data and save it using the AddNote tool."
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 2.2,
      "position": [
        624,
        -16
      ],
      "id": "0202bbb0-0ff7-4dd3-b3c8-5f176baf1d0c",
      "name": "AI Agent"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "typeVersion": 1,
      "position": [
        624,
        176
      ],
      "id": "0f2cfc88-b54f-4217-855a-0b6e66c8534b",
      "name": "Google Gemini Chat Model",
      "credentials": {
        "googlePalmApi": {
          "id": "n9vnvQ7O2MJ8djKt",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Форматируем красивый ответ для Telegram\\nfor (const item of $input.all()) {\\n  try {\\n    const output = item.json.output || '{}';\\n    let responseData;\\n    \\n    // Пытаемся распарсить ответ\\n    if (typeof output === 'string') {\\n      // Ищем JSON внутри строки\\n      const match = output.match(/\\\\[\\\\{.*\\\\}\\\\]/);\\n      if (match) {\\n        responseData = JSON.parse(match[0])[0];\\n      } else {\\n        responseData = JSON.parse(output);\\n      }\\n    } else {\\n      responseData = output;\\n    }\\n    \\n    // Формируем красивое сообщение\\n    const title = responseData.name || responseData.propertytitle || 'Без названия';\\n    const type = responseData.propertytype || responseData.type || '—';\\n    const category = responseData.propertycategory || responseData.category || '—';\\n    const url = responseData.url || '';\\n    \\n    let message = `✅ *Заметка сохранена!*\\\\n\\\\n`;\\n    message += `📝 *${title}*\\\\n\\\\n`;\\n    message += `🏷 Тип: ${type}\\\\n`;\\n    message += `📂 Категория: ${category}\\\\n`;\\n    \\n    if (url) {\\n      message += `\\\\n🔗 [Открыть в Notion](${url})`;\\n    }\\n    \\n    item.json.formattedMessage = message;\\n    \\n  } catch (error) {\\n    // Если не удалось распарсить - отправляем простое подтверждение\\n    item.json.formattedMessage = '✅ Заметка сохранена в Notion!';\\n  }\\n}\\n\\nreturn $input.all();"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        864,
        -16
      ],
      "id": "86c5442a-db9d-47fe-a00a-4afc4f378b10",
      "name": "Format Response"
    },
    {
      "parameters": {
        "chatId": "={{ $('Telegram Trigger').item.json.message.chat.id }}",
        "text": "={{ $json.formattedMessage }}",
        "additionalFields": {
          "appendAttribution": false,
          "parse_mode": "Markdown"
        }
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        1072,
        -16
      ],
      "id": "878d65ca-b7ea-4561-974b-d86af6ed46f1",
      "name": "Send a text message",
      "webhookId": "26b571f8-a79e-4461-acc6-ed49e8344f64",
      "credentials": {
        "telegramApi": {
          "id": "bFjsHGFg2wTqHaNG",
          "name": "Assistant"
        }
      }
    },
    {
      "parameters": {
        "resource": "databasePage",
        "databaseId": {
          "__rl": true,
          "value": "2a89188d-c2f2-8021-a06a-de7b0a2830a5",
          "mode": "list",
          "cachedResultName": "Notes",
          "cachedResultUrl": "<https://www.notion.so/2a89188dc2f28021a06ade7b0a2830a5>"
        },
        "title": "={{ $fromAI('Title', 'Note title', 'string') }}",
        "propertiesUi": {
          "propertyValues": [
            {
              "key": "=Category|select",
              "selectValue": "={{ $fromAI('Category', 'Notes category', 'string') }}"
            },
            {
              "key": "=Type|select",
              "selectValue": "={{ $fromAI('Type', 'Note Type', 'string') }}"
            },
            {
              "key": "=NoteContent|rich_text",
              "textContent": "={{ $fromAI('NoteContent', 'Full note content with links', 'string') }}"
            },
            {
              "key": "=Created At|date"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.notionTool",
      "typeVersion": 2.2,
      "position": [
        784,
        176
      ],
      "id": "de8c8b02-6d14-47b1-ae66-251c62f1acc7",
      "name": "AddNote",
      "credentials": {
        "notionApi": {
          "id": "wqPtVwbfmzOQiaEL",
          "name": "Notion account"
        }
      }
    },
    {
      "parameters": {
        "resource": "audio",
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.5-flash",
          "mode": "list",
          "cachedResultName": "models/gemini-2.5-flash"
        },
        "inputType": "binary",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1,
      "position": [
        208,
        32
      ],
      "id": "ba8e2053-e08d-4067-bb30-a007dfee1529",
      "name": "Transcribe a recording",
      "credentials": {
        "googlePalmApi": {
          "id": "n9vnvQ7O2MJ8djKt",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Extract text transcription from Google Gemini response\\nfor (const item of $input.all()) {\\n  try {\\n    let transcription;\\n    \\n    // Check for response structure variations\\n    if (item.json.response && item.json.response.candidates) {\\n      // Standard Gemini response structure\\n      const candidate = item.json.response.candidates[0];\\n      if (candidate.content && candidate.content.parts) {\\n        transcription = candidate.content.parts[0].text;\\n      }\\n    } else if (item.json.text) {\\n      // Direct text field\\n      transcription = item.json.text;\\n    } else if (typeof item.json === 'string') {\\n      // String response\\n      transcription = item.json;\\n    }\\n    \\n    if (transcription) {\\n      item.json = {\\n        messageText: transcription,\\n        fullContent: transcription\\n      };\\n    } else {\\n      // Fallback\\n      item.json = {\\n        messageText: 'Voice message transcription failed',\\n        fullContent: 'Voice message transcription failed'\\n      };\\n    }\\n    \\n  } catch (error) {\\n    item.json = {\\n      messageText: 'Error processing transcription',\\n      fullContent: 'Error processing transcription',\\n      error: error.message\\n    };\\n  }\\n}\\n\\nreturn $input.all();"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        400,
        32
      ],
      "id": "b47d783d-a29f-42f9-83a7-fddbb473f8de",
      "name": "Extract Transcription Text"
    },
    {
      "parameters": {
        "jsCode": "// Extract message text and format links\\nfor (const item of $input.all()) {\\n  const message = item.json.message;\\n  let messageText = message.text || '';\\n  let fullContent = messageText;\\n  \\n  // Process entities (links, mentions, etc.)\\n  if (message.entities && message.entities.length > 0) {\\n    const entities = [...message.entities].sort((a, b) => b.offset - a.offset);\\n    \\n    for (const entity of entities) {\\n      const entityText = messageText.substring(entity.offset, entity.offset + entity.length);\\n      \\n      if (entity.type === 'url') {\\n        // Replace URL with markdown link\\n        const before = fullContent.substring(0, entity.offset);\\n        const after = fullContent.substring(entity.offset + entity.length);\\n        fullContent = before + `[${entityText}](${entityText})` + after;\\n      } else if (entity.type === 'text_link') {\\n        // Replace text_link with markdown link\\n        const before = fullContent.substring(0, entity.offset);\\n        const after = fullContent.substring(entity.offset + entity.length);\\n        fullContent = before + `[${entityText}](${entity.url})` + after;\\n      }\\n    }\\n  }\\n  \\n  item.json = {\\n    messageText: messageText,\\n    fullContent: fullContent\\n  };\\n}\\n\\nreturn $input.all();"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        16,
        -208
      ],
      "id": "c251daa4-70d0-407d-aae1-e68ae619da84",
      "name": "Extract Links from Telegram"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n## Telegram Trigger\\nListens for ALL messages and voice notes from Telegram.\\nNo user filtering at trigger level.\\nOutputs: $json with message data",
        "height": 320,
        "color": 3
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -528,
        -128
      ],
      "typeVersion": 1,
      "id": "08a275ae-0f28-4b52-a05a-faba4d2b7ac0",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n## Check User ID\\nFilters messages by user ID 354573537.\\nOnly allows messages from this specific user.\\nRejects all other messages.",
        "height": 288,
        "width": 208,
        "color": 6
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -384,
        -144
      ],
      "typeVersion": 1,
      "id": "56ea3bb5-3e7c-417e-bc13-a1ff369bd3f1",
      "name": "Sticky Note User Filter"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n## Switch\\nRoutes execution based on message type:\\n- Text messages → Extract Links\\n- Voice messages → Get File\\nBased on presence of text or voice.file_id fields",
        "height": 336,
        "width": 224,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -208,
        -144
      ],
      "typeVersion": 1,
      "id": "c882b94d-2946-47a1-a3c8-8e7100afea97",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n## Extract Links\\nExtracts message text and converts Telegram entities (URLs, text_links) into markdown format.\\nOutput: messageText, fullContent (with markdown links)",
        "height": 320,
        "color": 6
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -32,
        -224
      ],
      "typeVersion": 1,
      "id": "93debc42-6be5-41ed-be48-241c93827133",
      "name": "Sticky Note Extract Links"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n## Get a File\\nRetrieves audio file from Telegram voice message.\\nInput: $json.message.voice.file_id\\nOutput: binary audio for transcription.",
        "height": 336,
        "width": 224,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -48,
        16
      ],
      "typeVersion": 1,
      "id": "0adbc904-d781-4524-9210-7e05c7f8ce2e",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n## Transcribe Audio\\nTranscribes audio message to text using Google Gemini.\\nInput: binary audio from 'Get a File'.\\nOutput: text transcription",
        "height": 368,
        "width": 208,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        176,
        16
      ],
      "typeVersion": 1,
      "id": "1a6a2920-222d-486d-80c6-6235ce3abda0",
      "name": "Sticky Note4"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n## Extract Transcription Text\\nExtracts transcription text from API response.\\nOutput: 'text' for AI Agent.",
        "height": 400,
        "width": 176,
        "color": 6
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        384,
        16
      ],
      "typeVersion": 1,
      "id": "1a9a1c66-aa09-4b04-a437-63f00d01b9e0",
      "name": "Sticky Note5"
    },
    {
      "parameters": {
        "content": "## AI Agent\\nProcesses extracted text with links to generate note metadata:\\n- title\\n- type\\n- category\\n- noteContent (with links)\\n- createdAt",
        "height": 336,
        "width": 256,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        608,
        -224
      ],
      "typeVersion": 1,
      "id": "dc602e05-9818-4803-a31d-ebbdc21f1a24",
      "name": "Sticky Note6"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n## Google Gemini Model\\nLanguage model used by AI Agent for processing notes.\\nProvides NLP capabilities for title, type, and category generation.",
        "height": 384,
        "width": 176
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        576,
        160
      ],
      "typeVersion": 1,
      "id": "0f27a3fa-a01a-4818-b432-c237503a6885",
      "name": "Sticky Note7"
    },
    {
      "parameters": {
        "content": "## Format Response\\nFormats AI Agent output into a beautiful Telegram message.\\nExtracts: title, type, category, URL\\nOutputs formatted Markdown message.",
        "height": 288,
        "width": 224,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        832,
        -144
      ],
      "typeVersion": 1,
      "id": "9a7bec14-9069-4a1d-999b-b94a5cc63b5b",
      "name": "Sticky Note Format"
    },
    {
      "parameters": {
        "content": "## Send Text\\nSends formatted message back to Telegram chat.\\nInput: $json.formattedMessage with Markdown.",
        "height": 288,
        "width": 224,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1024,
        -144
      ],
      "typeVersion": 1,
      "id": "f31d517a-0b0e-4f94-826a-ceb48d8e172a",
      "name": "Sticky Note8"
    },
    {
      "parameters": {
        "content": "\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n## Save to Notion\\nStores processed note into Notion database.\\nFields: title, type, category, noteContent (with links), createdAt",
        "height": 288,
        "width": 208,
        "color": 3
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        752,
        160
      ],
      "typeVersion": 1,
      "id": "8d8632cb-33b9-4f8f-b84c-773eeb32dcfe",
      "name": "Sticky Note9"
    },
    {
      "parameters": {
        "chatId": "={{ $('Telegram Trigger').item.json.message.chat.id }}",
        "text": "=Пішов на хуй",
        "replyMarkup": "forceReply",
        "forceReply": {},
        "additionalFields": {
          "appendAttribution": false,
          "parse_mode": "Markdown"
        }
      },
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        -256,
        288
      ],
      "id": "a9b9c632-e8af-476e-8a44-13dc3e7f9a70",
      "name": "Send a text message1",
      "webhookId": "26b571f8-a79e-4461-acc6-ed49e8344f64",
      "credentials": {
        "telegramApi": {
          "id": "bFjsHGFg2wTqHaNG",
          "name": "Assistant"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "Telegram Trigger": {
      "main": [
        [
          {
            "node": "Check User ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check User ID": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a text message1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Extract Links from Telegram",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Get a file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get a file": {
      "main": [
        [
          {
            "node": "Transcribe a recording",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Format Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Response": {
      "main": [
        [
          {
            "node": "Send a text message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AddNote": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Transcribe a recording": {
      "main": [
        [
          {
            "node": "Extract Transcription Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Transcription Text": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Links from Telegram": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "f6d1b487-a749-4fcb-86cb-7587fdcba8b3",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "1a116c5fad13389739c352c3250be914f65de4eef602fef22e849f0bbc98f0ac"
  },
  "id": "oJOk9iUMrgUzJwsd",
  "tags": []
}