{
  "id": "Mlrl2mzp2YtbMQMW",
  "name": "Auto-reply to Telegram messages using BrowserAct & Google Gemini",
  "tags": [],
  "nodes": [
    {
      "id": "6b2a7654-3d7d-4b93-ac03-0cceb7351369",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        -848,
        384
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "bd8d3616-6bdb-451e-8aa7-330fcb3d58e0",
      "name": "Structured Output",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -496,
        304
      ],
      "parameters": {
        "autoFix": true,
        "jsonSchemaExample": "{\n  \"name\": \"BrowserAct \ud83d\udc08\u200d\u2b1b\",\n  \"type\": \"answer\",\n  \"Answer\": \"Yes, BrowserAct \ud83d\udc08\u200d\u2b1b, I can certainly help you. What do you need?\\n\\n[This is an automated bot and will answer every 15 minutes]\"\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "304fd4f9-7381-475a-af67-7152c89b8421",
      "name": "Human Verification Switch",
      "type": "n8n-nodes-base.switch",
      "position": [
        -1824,
        400
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 3,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "cea414f0-feaa-4012-9826-9feaf49d3e40",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "finished"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 3,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "cf3a1ab6-d5dc-4641-b3d7-7e8471fe502a",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "paused"
                  }
                ]
              }
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.4
    },
    {
      "id": "fb70f68d-fae9-41dd-932f-ea33a366097f",
      "name": "Every 15 minutes",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -2224,
        400
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 15
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "4de3aa32-c759-4c4d-8b3b-623652d22373",
      "name": "Read Telegram Message",
      "type": "n8n-nodes-browseract.browserAct",
      "position": [
        -2048,
        400
      ],
      "parameters": {
        "type": "WORKFLOW",
        "workflowId": "69828791477180147",
        "workflowConfig": {
          "value": {},
          "schema": [
            {
              "id": "input-Telegram",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "description": "If left blank, the default value defined in BrowserAct will be used.",
              "displayName": "Telegram",
              "defaultMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "input-Telegram"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "open_incognito_mode": false
      },
      "credentials": {
        "browserActApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "5ec5dde5-f00f-409c-8eed-72d6be43f1b1",
      "name": "Give Time to Complete Verification",
      "type": "n8n-nodes-base.wait",
      "position": [
        -1600,
        288
      ],
      "parameters": {
        "unit": "minutes"
      },
      "typeVersion": 1.1
    },
    {
      "id": "8a63c0b3-4564-401c-a91d-3de73cc31e3a",
      "name": "Get Data From BrowserAct",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        -1376,
        288
      ],
      "parameters": {
        "url": "https://api.browseract.com/v2/workflow/get-task",
        "options": {},
        "sendQuery": true,
        "authentication": "predefinedCredentialType",
        "queryParameters": {
          "parameters": [
            {
              "name": "task_id",
              "value": "={{ $('Read Telegram Message').item.json.id }}"
            }
          ]
        },
        "nodeCredentialType": "browserActApi"
      },
      "credentials": {
        "browserActApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "c35ac544-95f4-4a40-aa03-4794aa6bf261",
      "name": "Splitting Extracted Items",
      "type": "n8n-nodes-base.code",
      "position": [
        -1152,
        384
      ],
      "parameters": {
        "jsCode": "// Get the JSON string using the exact path provided by the user.\nconst jsonString = $input.first().json.output.string;\n\nlet parsedData;\n\n// Check if the string exists before attempting to parse\nif (!jsonString) {\n    // Return an empty array or throw an error if no string is found\n    // Throwing an error is usually better to stop the workflow if data is missing.\n    throw new Error(\"Input string is empty or missing at the specified path: $input.first().json.output.string\");\n}\n\ntry {\n    // 1. Parse the JSON string into a JavaScript array of objects\n    parsedData = JSON.parse(jsonString);\n} catch (error) {\n    // Handle JSON parsing errors (e.g., if the string is malformed)\n    throw new Error(`Failed to parse JSON string: ${error.message}`);\n}\n\n// 2. Ensure the parsed data is an array\nif (!Array.isArray(parsedData)) {\n    throw new Error('Parsed data is not an array. It cannot be split into multiple items.');\n}\n\n// 3. Map the array of objects into the n8n item format { json: object }\n// Each element in this array will be treated as a new item by n8n, achieving the split.\nconst outputItems = parsedData.map(item => ({\n    json: item,\n}));\n\n// 4. Return the new array of items\nreturn outputItems;"
      },
      "typeVersion": 2
    },
    {
      "id": "89f4899a-ed8a-47fd-911e-1df12f6c25f7",
      "name": "Generate Answers for Messages",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -576,
        80
      ],
      "parameters": {
        "text": "=Name : {{ $json.Name }},\nLast Message : {{ $json.Last }},\nUser Chat history : {{ $json.UserHistory }}\nBot Rrsponse history :{{ $json.BotHistory }}",
        "options": {
          "systemMessage": "You are an automated response bot designed to process user messages and return structured JSON data.\n\n**Input Format:**\nYou will receive a JSON list containing an object with:\n- `Name`: The user's name.\n- `Last`: The latest message to answer.\n- `UserHistory`: Past user messages.\n- `BotHistory`: Past bot responses.\n\n**Task Instructions:**\n1. **Analyze Necessity:** Determine if the `Last` message requires a response.\n   - If `Last` contains text/questions: Set status to \"answer\".\n   - If `Last` is empty, null, or only whitespace: Set status to \"idle\".\n2. **Personalize:** If status is \"answer\", draft a helpful response. You **MUST** mention the user's `Name` explicitly within your response text (e.g., \"Hello [Name], I see you asked...\").\n3. **Add Disclaimer:** If status is \"answer\", append this exact footer to the end of your response text: \"\\n\\n[This is an automated bot and will answer every 15 minutes]\"\n4. **Handle Idle:** If status is \"idle\", leave the answer text empty or null.\n\n**Output Format:**\nYou must return ONLY a raw JSON object (valid JSON, no markdown code blocks) with exactly these three keys:\n1. `\"name\"`: The user's name (same as input).\n2. `\"type\"`: Either \"answer\" or \"idle\".\n3. `\"Answer\"`: Your personalized response text with the footer (or null if idle).\n\n**Example 1 (Standard Reply):**\n\n*Input:*\n[ { \"Name\": \"BrowserAct \ud83d\udc08\u200d\u2b1b\", \"Last\": \"Can you help me?\", \"UserHistory\": \"...\", \"BotHistory\": \"...\" } ]\n\n*Output:*\n{\n  \"name\": \"BrowserAct \ud83d\udc08\u200d\u2b1b\",\n  \"type\": \"answer\",\n  \"Answer\": \"Yes, BrowserAct \ud83d\udc08\u200d\u2b1b, I can certainly help you. What do you need?\\n\\n[This is an automated bot and will answer every 15 minutes]\"\n}\n\n**Example 2 (No Input / Idle):**\n\n*Input:*\n[ { \"Name\": \"BrowserAct \ud83d\udc08\u200d\u2b1b\", \"Last\": \"\", \"UserHistory\": \"...\", \"BotHistory\": \"...\" } ]\n\n*Output:*\n{\n  \"name\": \"BrowserAct \ud83d\udc08\u200d\u2b1b\",\n  \"type\": \"idle\",\n  \"Answer\": null\n}"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3
    },
    {
      "id": "41d3dd95-d1c9-49e5-819d-ed342283cd8d",
      "name": "Check If Message Requires Response",
      "type": "n8n-nodes-base.if",
      "position": [
        -224,
        80
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "160a47f6-dec9-46bf-94c7-59894437d851",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.output.type }}",
              "rightValue": "answer"
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.3
    },
    {
      "id": "2e396381-b0fe-43f7-9cf6-907a7264ea3e",
      "name": "Run Answering Workflow",
      "type": "n8n-nodes-browseract.browserAct",
      "position": [
        320,
        112
      ],
      "parameters": {
        "type": "WORKFLOW",
        "timeout": 7200,
        "workflowId": "69845607081621235",
        "workflowConfig": {
          "value": {
            "input-Name": "={{ $('Generate Answers for Messages').first().json.output.name }}",
            "input-Answer": "={{ $json.clean_message }}"
          },
          "schema": [
            {
              "id": "input-Telegram",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "description": "If left blank, the default value defined in BrowserAct will be used.",
              "displayName": "Telegram",
              "defaultMatch": true
            },
            {
              "id": "input-Name",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "description": "If left blank, the default value defined in BrowserAct will be used.",
              "displayName": "Name",
              "defaultMatch": true
            },
            {
              "id": "input-Answer",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "description": "If left blank, the default value defined in BrowserAct will be used.",
              "displayName": "Answer",
              "defaultMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "input-Name"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "open_incognito_mode": false
      },
      "credentials": {
        "browserActApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "1d597160-9bb9-42e4-81dc-5c335a99b85b",
      "name": "Human Verification Switch2",
      "type": "n8n-nodes-base.switch",
      "position": [
        528,
        112
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 3,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "cea414f0-feaa-4012-9826-9feaf49d3e40",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "finished"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 3,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "cf3a1ab6-d5dc-4641-b3d7-7e8471fe502a",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "paused"
                  }
                ]
              }
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.4
    },
    {
      "id": "51fe8b67-ed5a-4f61-bad8-992f41ad8c75",
      "name": "Give Time to Complete Verification2",
      "type": "n8n-nodes-base.wait",
      "position": [
        784,
        0
      ],
      "parameters": {
        "unit": "minutes"
      },
      "typeVersion": 1.1
    },
    {
      "id": "57d26f4f-644d-41ed-a46a-5b74c21af963",
      "name": "Get Data From BrowserAct2",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1008,
        0
      ],
      "parameters": {
        "url": "https://api.browseract.com/v2/workflow/get-task",
        "options": {},
        "sendQuery": true,
        "authentication": "predefinedCredentialType",
        "queryParameters": {
          "parameters": [
            {
              "name": "task_id",
              "value": "={{ $('Read Telegram Message').item.json.id }}"
            }
          ]
        },
        "nodeCredentialType": "browserActApi"
      },
      "credentials": {
        "browserActApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "35949fa1-894d-44a6-8da5-1baa58b633b4",
      "name": "Wait for Workflow Completion",
      "type": "n8n-nodes-base.wait",
      "position": [
        1360,
        96
      ],
      "parameters": {
        "unit": "minutes"
      },
      "typeVersion": 1.1
    },
    {
      "id": "411d2ba6-b510-45ce-b707-d659d39185e5",
      "name": "Google Gemini",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        -624,
        304
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "googlePalmApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "9aea2505-df97-4a68-b905-df2ef274097e",
      "name": "Cleaning Output Text",
      "type": "n8n-nodes-base.code",
      "position": [
        0,
        112
      ],
      "parameters": {
        "jsCode": "// Get the \"Answer\" string from the previous node\nconst rawAnswer = $input.first().json.output.Answer;\n// Fix the new lines: Replace literal \"\\n\" characters with real line breaks\nconst cleanText = rawAnswer.replace(/\\\\n/g, '\\n');\n\n// Output the clean text so the next node (Slack/Discord/Email) reads it perfectly\nreturn {\n  json: {\n    clean_message: cleanText\n  }\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "bc5a2d3b-0b3e-43df-9fd8-4320c7047401",
      "name": "Documentation",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2592,
        -272
      ],
      "parameters": {
        "width": 380,
        "height": 520,
        "content": "## \u26a1 Workflow Overview & Setup\n\n**Summary:** This automation acts as an always-on customer support agent for Telegram. It checks for new messages every 15 minutes, uses AI to draft personalized responses, and replies automatically via BrowserAct.\n\n### Requirements\n* **Credentials:** Telegram, BrowserAct, Google Gemini (PaLM).\n* **Mandatory:** BrowserAct API (Template: **Telegram Personal Assistant**)\n\n### How to Use\n1.  **Credentials:** Set up your Telegram, BrowserAct, and Google Gemini credentials in n8n.\n2.  **BrowserAct Template:** Ensure you have the **TTelegram Personal Assistant** template saved in your BrowserAct account.\n3.  **Operation:** The workflow runs automatically. It reads unread messages, drafts replies using AI, and sends them back to the user.\n\n### Need Help?\n[How to Find Your BrowserAct API Key & Workflow ID](https://docs.browseract.com)\n[How to Connect n8n to BrowserAct](https://docs.browseract.com)\n[How to Use & Customize BrowserAct Templates](https://docs.browseract.com)"
      },
      "typeVersion": 1
    },
    {
      "id": "2b8d1463-bf34-4baf-a28f-65393da1099c",
      "name": "Step 1 Explanation",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2176,
        128
      ],
      "parameters": {
        "color": 7,
        "width": 1132,
        "height": 124,
        "content": "### \ud83d\udce9 Step 1: Message Retrieval\n\nThe workflow triggers every 15 minutes to fetch the latest messages from Telegram via BrowserAct. It scrapes the chat history to understand the context of each user interaction."
      },
      "typeVersion": 1
    },
    {
      "id": "81769b9a-722e-4606-831b-557272c03f62",
      "name": "Step 2 Explanation",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -880,
        -64
      ],
      "parameters": {
        "color": 7,
        "width": 1004,
        "height": 108,
        "content": "### \ud83e\udde0 Step 2: AI Response Drafting\n\nAn AI agent analyzes the retrieved messages to determine if a response is needed. If the user asked a question, it drafts a personalized, helpful reply, ensuring to include a disclaimer that it is an automated bot."
      },
      "typeVersion": 1
    },
    {
      "id": "ed5b3990-a679-4648-9dd7-eebdef8984ce",
      "name": "Step 3 Explanation",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        320,
        -144
      ],
      "parameters": {
        "color": 7,
        "width": 1180,
        "height": 108,
        "content": "### \ud83e\udd16 Step 3: Automated Reply\n\nOnce a response is drafted and cleaned, BrowserAct is triggered again to type and send the message directly in the Telegram web interface, simulating a human agent's behavior."
      },
      "typeVersion": 1
    },
    {
      "id": "811257f4-8b38-4526-b7f2-32b27a82a395",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2176,
        -272
      ],
      "parameters": {
        "color": 6,
        "width": 640,
        "height": 368,
        "content": "@[youtube](iTp4LhhjCiQ)"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "2ef7d37b-2871-43dd-9742-2c5dcec52d44",
  "connections": {
    "Google Gemini": {
      "ai_languageModel": [
        [
          {
            "node": "Generate Answers for Messages",
            "type": "ai_languageModel",
            "index": 0
          },
          {
            "node": "Structured Output",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [],
        [
          {
            "node": "Generate Answers for Messages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every 15 minutes": {
      "main": [
        [
          {
            "node": "Read Telegram Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output": {
      "ai_outputParser": [
        [
          {
            "node": "Generate Answers for Messages",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Cleaning Output Text": {
      "main": [
        [
          {
            "node": "Run Answering Workflow",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Telegram Message": {
      "main": [
        [
          {
            "node": "Human Verification Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run Answering Workflow": {
      "main": [
        [
          {
            "node": "Human Verification Switch2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Data From BrowserAct": {
      "main": [
        [
          {
            "node": "Splitting Extracted Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Data From BrowserAct2": {
      "main": [
        [
          {
            "node": "Wait for Workflow Completion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Human Verification Switch": {
      "main": [
        [
          {
            "node": "Splitting Extracted Items",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Give Time to Complete Verification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Splitting Extracted Items": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Human Verification Switch2": {
      "main": [
        [
          {
            "node": "Wait for Workflow Completion",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Give Time to Complete Verification2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for Workflow Completion": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Answers for Messages": {
      "main": [
        [
          {
            "node": "Check If Message Requires Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check If Message Requires Response": {
      "main": [
        [
          {
            "node": "Cleaning Output Text",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Give Time to Complete Verification": {
      "main": [
        [
          {
            "node": "Get Data From BrowserAct",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Give Time to Complete Verification2": {
      "main": [
        [
          {
            "node": "Get Data From BrowserAct2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}