Please, if possible, give me a ready-made template for recognizing photos and screenshots by a Telegram bot. The scheme is as follows: Telegram Trigger - nodes that will recognize photos - AI agent node - Telegram response. I have been making different se

Please, if possible, give me a ready-made template for recognizing photos and screenshots by a Telegram bot. The scheme is as follows: Telegram Trigger - nodes that will recognize photos - AI agent node - Telegram response. I have been making different settings every day for 14 days, changing photo processing nodes, and nothing has worked out yet. The workflow is going well, but the Telegram bot replies that it does not recognize photos. Please help if anyone has already made such a template. Best regards, Alexander.

1 Like

{
“name”: “My workflow 55”,
“nodes”: [
{
“parameters”: {
“conditions”: {
“options”: {
“caseSensitive”: true,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 2
},
“conditions”: [
{
“id”: “a9e919bb-8d22-4855-a7b6-a9e5a9f39778”,
“leftValue”: “={{ $json.message.chat.username }}”,
“rightValue”: “={{ $json.message.from.username }}\n”,
“operator”: {
“type”: “string”,
“operation”: “notEquals”
}
}
],
“combinator”: “and”
},
“options”: {}
},
“type”: “n8n-nodes-base.if”,
“typeVersion”: 2.2,
“position”: [
220,
180
],
“id”: “6b2192eb-ce4c-4e0f-94da-45cde1738a84”,
“name”: “If”
},
{
“parameters”: {
“updates”: [
“message”
],
“additionalFields”: {}
},
“type”: “n8n-nodes-base.telegramTrigger”,
“typeVersion”: 1.1,
“position”: [
60,
180
],
“id”: “a0b0d8d1-c65d-4280-b062-4005a6ec8ff5”,
“name”: “Telegram Trigger1”,
“webhookId”: “b33d2025-01c2-4386-b677-206a87a1856b”,
“credentials”: {
“telegramApi”: {
“id”: “MTm6Q7tzELOcNlL7”,
“name”: “авто автоматик”
}
}
},
{
“parameters”: {
“resource”: “audio”,
“operation”: “transcribe”,
“options”: {}
},
“type”: “@n8n/n8n-nodes-langchain.openAi”,
“typeVersion”: 1.8,
“position”: [
240,
340
],
“id”: “94c3548b-078e-40a6-ab3b-de1ff5feddfc”,
“name”: “OpenAI”,
“credentials”: {
“openAiApi”: {
“id”: “BpxhpiEYc1Zu0k5g”,
“name”: “OpenAi account”
}
}
},
{
“parameters”: {
“resource”: “image”,
“operation”: “analyze”,
“modelId”: {
“__rl”: true,
“value”: “gpt-4o”,
“mode”: “list”,
“cachedResultName”: “GPT-4O”
},
“text”: “Your task is to provide an objective and detailed description of the product shown in the photograph for the Avito marketplace.\n\nRules:\n\nAlways identify and state the common, everyday name of the item shown in the photo (e.g., "suitcase," "bicycle," "table," "microwave") in the "Product name" field, even if there is no label or brand visible. Use the most obvious and simple term for the item based on its appearance.\n\nDescribe only what is clearly visible in the photo.\n\nIf there is a label, inscription, or marking in the image, indicate that it is a label/inscription and provide the full text.\n\nIf dimensions, weight, model, name, or technical specifications are visible in the photo, write them out exactly as they appear.\n\nIf size, weight, condition, or other parameters are not explicitly indicated, do not make them up or make assumptions.\n\nIf you see signs that may indicate size or condition, write: "Possibly, the photo shows [description], clarification from the user is required."\n\nDo not use words like "new," "used," "original," or other evaluations unless it is written on the label or clearly indicated in the photo.\n\nDo not add any information that is not present in the photo.\n\nIf information is not visible or is illegible, indicate: "Information is illegible/unavailable."\n\nDo not draw conclusions or generalize—only state facts from the photo.\n\nFormat the description in a structured way, for example:\n\nProduct name: …\nBrand/model: …\nLabel text: …\nVisible characteristics: …\nPackage contents: …\nSpecial notes: …\nRemarks: …\n\nIf there is anything that needs clarification from the user, add a separate section "Questions for clarification:" and list what needs to be asked.\n\nExample:\n\nProduct name: suitcase\nBrand/model: not specified\nLabel text: none visible\nVisible characteristics: light blue color, hard shell case, telescopic handle, four black wheels, ribbed texture\nPackage contents: not visible\nSpecial notes: none\nRemarks: information about size, brand, and condition is missing\nQuestions for clarification:\n\nWhat are the dimensions of the suitcase?\n\nWhat is the condition of the suitcase?\n\nIs there a brand or model information available?\n\nDescribe only what is actually visible in the photo and/or written on the label. Always provide the most obvious, simple name for the item in the Product name field.”,
“inputType”: “base64”,
“options”: {}
},
“type”: “@n8n/n8n-nodes-langchain.openAi”,
“typeVersion”: 1.8,
“position”: [
420,
500
],
“id”: “3027c08f-1a6c-4f26-ac4d-175b5bc38b6d”,
“name”: “OpenAI5”,
“credentials”: {
“openAiApi”: {
“id”: “BpxhpiEYc1Zu0k5g”,
“name”: “OpenAi account”
}
}
},
{
“parameters”: {
“operation”: “information”
},
“type”: “n8n-nodes-base.editImage”,
“typeVersion”: 1,
“position”: [
240,
500
],
“id”: “3affce57-e419-4c01-acf7-614539303c3d”,
“name”: “Get Image Info1”
},
{
“parameters”: {
“rules”: {
“values”: [
{
“conditions”: {
“options”: {
“caseSensitive”: true,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 2
},
“conditions”: [
{
“id”: “b982f2f8-9f79-4303-821b-4d82117edf09”,
“leftValue”: “={{ $json.message.photo }}”,
“rightValue”: “image”,
“operator”: {
“type”: “array”,
“operation”: “exists”,
“singleValue”: true
}
}
],
“combinator”: “and”
},
“renameOutput”: true,
“outputKey”: “Image”
},
{
“conditions”: {
“options”: {
“caseSensitive”: true,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 2
},
“conditions”: [
{
“leftValue”: “={{ $json.message.voice }}”,
“rightValue”: “text”,
“operator”: {
“type”: “object”,
“operation”: “exists”,
“singleValue”: true
}
}
],
“combinator”: “and”
},
“renameOutput”: true,
“outputKey”: “Audio”
},
{
“conditions”: {
“options”: {
“caseSensitive”: true,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 2
},
“conditions”: [
{
“id”: “1a52b406-1df9-4c47-85c7-1de7e4c5365e”,
“leftValue”: “={{ $json.message.text }}”,
“rightValue”: “audio”,
“operator”: {
“type”: “string”,
“operation”: “exists”,
“singleValue”: true
}
}
],
“combinator”: “and”
},
“renameOutput”: true,
“outputKey”: “Text”
}
]
},
“options”: {}
},
“type”: “n8n-nodes-base.switch”,
“typeVersion”: 3.2,
“position”: [
420,
180
],
“id”: “2efbe5bf-d670-4901-9c7a-8b48fec2eb23”,
“name”: “Switch1”
},
{
“parameters”: {
“resource”: “file”,
“fileId”: “={{ $json.message.photo[$json.message.photo.length - 1].file_id }}”
},
“type”: “n8n-nodes-base.telegram”,
“typeVersion”: 1.2,
“position”: [
60,
520
],
“id”: “0eb2853a-f700-4f8b-a3ae-6c679e8cfb5d”,
“name”: “Telegram5”,
“webhookId”: “9a8552f5-1ece-46a9-ab11-9c476af9b36d”,
“credentials”: {
“telegramApi”: {
“id”: “MTm6Q7tzELOcNlL7”,
“name”: “авто автоматик”
}
}
},
{
“parameters”: {
“resource”: “file”,
“fileId”: “={{ $json.message.voice.file_id }}”
},
“type”: “n8n-nodes-base.telegram”,
“typeVersion”: 1.2,
“position”: [
60,
360
],
“id”: “22eae171-57d5-4301-9700-3a3a35323dbd”,
“name”: “Telegram1”,
“webhookId”: “06849504-8197-467f-9284-cb2780746c26”,
“credentials”: {
“telegramApi”: {
“id”: “MTm6Q7tzELOcNlL7”,
“name”: “авто автоматик”
}
}
},
{
“parameters”: {
“jsCode”: “// ИСПРАВЛЕННЫЙ код для узла Code2 - стабильный sessionId\nconst inputData = $input.first().json;\n\nconsole.log(‘=== СОЗДАНИЕ СТАБИЛЬНОГО SESSION ID ===’);\n\n// Инициализируем переменные\nlet contentType = ‘text’;\nlet userMessage = ‘’;\nlet sessionId = ‘unknown’;\nlet messageId = ‘unknown’;\n\n// СПОСОБ 1: Получаем Telegram данные\ntry {\n const switchData = $(‘Switch1’).item.json;\n if (switchData && switchData.message && switchData.message.from) {\n // ВАЖНО: используем только USER ID для sessionId (БЕЗ messageId)\n sessionId = user_${switchData.message.from.id};\n messageId = switchData.message.message_id;\n console.log(‘:white_check_mark: СТАБИЛЬНЫЙ SESSION ID:’, sessionId);\n }\n} catch (error) {\n console.log(‘:cross_mark: Не удалось получить данные из Switch’);\n}\n\n// СПОСОБ 2: Если Switch не сработал, пробуем текущие данные\nif (sessionId === ‘unknown’ && inputData.message && inputData.message.from) {\n sessionId = user_${inputData.message.from.id};\n messageId = inputData.message.message_id;\n console.log(‘:white_check_mark: СТАБИЛЬНЫЙ SESSION ID из текущего INPUT:’, sessionId);\n}\n\n// СПОСОБ 3: Последний шанс - используем chat_id если есть\nif (sessionId === ‘unknown’ && inputData.message && inputData.message.chat) {\n sessionId = chat_${inputData.message.chat.id};\n messageId = inputData.message.message_id || Date.now();\n console.log(‘:white_check_mark: СТАБИЛЬНЫЙ SESSION ID из chat_id:’, sessionId);\n}\n\n// Определяем контент\nif (inputData.content) {\n userMessage = inputData.content;\n contentType = ‘image’;\n} else if (inputData.text) {\n userMessage = inputData.text;\n contentType = ‘audio’;\n} else if (inputData.message && inputData.message.text) {\n userMessage = inputData.message.text;\n contentType = ‘text’;\n} else {\n userMessage = ‘Контент не определен’;\n contentType = ‘unknown’;\n}\n\n// Очистка сообщения\nif (userMessage && typeof userMessage === ‘string’) {\n userMessage = userMessage\n .replace(/"/g, ‘\\"’)\n .replace(/\n/g, ’ ‘)\n .replace(/\r/g, ’ ‘)\n .trim();\n}\n\nconst result = {\n sessionId: sessionId,\n userMessage: userMessage,\n messageId: messageId,\n modal: contentType,\n timestamp: new Date().toISOString()\n};\n\nconsole.log(’=== FINAL STABLE RESULT ===’);\nconsole.log(‘sessionId (БЕЗ messageId):’, result.sessionId);\nconsole.log(‘messageId (отдельно):’, result.messageId);\nconsole.log(‘modal:’, result.modal);\nconsole.log(‘=============================’);\n\nreturn [{ json: result }];\n”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
620,
360
],
“id”: “326cccea-dd65-43df-b650-b4e2197a7bc6”,
“name”: “Code2”
},
{
“parameters”: {
“promptType”: “define”,
“text”: “=ДАННЫЕ СЕССИИ:\nSession ID: {{ $json.sessionId }}\nMessage ID: {{ $json.messageId }}\nТип контента: {{ $json.modal || ‘text’ }}\nВремя: {{ $json.timestamp }}\n\nАНАЛИЗИРУЕМЫЕ ДАННЫЕ:\n{{ $json.userMessage }}\n\nЗАДАЧА: Проанализируй данные товара и подготовь структурированную информацию для следующего агента по определению товара.\n”,
“options”: {
“systemMessage”: “={\n "name": "AI АНАЛИЗ ВХОДЯЩИХ с Session Memory",\n "type": "@n8n/n8n-nodes-langchain.agent",\n "parameters": {\n "promptType": "define",\n "text": "ВХОДЯЩИЕ ДАННЫЕ:{{ $json.userMessage }}",\n "options": {\n "systemMessage": "Ты — эксперт по анализу товаров для Avito с поддержкой сессий и контролем уточнений.\n\nКОНТРОЛЬ УТОЧНЕНИЙ:\n• Всегда проверяй поле isResponseToClarification из входных данных\n• Если isResponseToClarification=true - это ответ на предыдущее уточнение\n• Максимум 2 уточнения на товар\n\nЛОГИКА ОБРАБОТКИ УТОЧНЕНИЙ:\n1. ПРИ ПОЛУЧЕНИИ УТОЧНЕНИЯ:\n - Сохрани предыдущий анализ товара из памяти сессии\n - Дополни анализ НОВОЙ информацией из уточнения\n - НЕ создавай новый анализ с нуля\n - Обнови только недостающие характеристики\n\n2. ПРИ ПРЕВЫШЕНИИ ЛИМИТА (2 уточнения):\n - Заверши анализ с текущими данными\n - Верни ВСЕ имеющиеся характеристики товара\n\nФОРМАТ ОТВЕТА:\n{\n \"session_id\": \"{{ $json.sessionId }}\",\n \"clarification_count\": {{ $json.clarificationInfo.totalClarifications }},\n \"is_continuation\": {{ $json.clarificationInfo.isResponseToClarification }},\n \"previous_data\": {\n \"product_name\": \"…\",\n \"specifications\": {…}\n },\n \"updated_data\": {\n \"new_info\": \"…\",\n \"merged_specifications\": {…}\n },\n \"product_analysis\": {\n \"product_name\": \"полное название с учетом уточнения\",\n \"category\": \"обновленная категория\",\n \"specifications\": {\n \"dimensions\": \"размеры из уточнения\",\n \"condition\": \"состояние из уточнения\"\n }\n },\n \"session_status\": {\n \"missing_info\": […],\n \"readiness\": \"ready|needs_clarification|force_completed\"\n }\n}"\n }\n }\n}\n”
}
},
“type”: “@n8n/n8n-nodes-langchain.agent”,
“typeVersion”: 1.7,
“position”: [
820,
360
],
“id”: “ca62dd04-dd14-45c1-959d-c92fbd88b9ff”,
“name”: “AI АНАЛИЗ ВХОДЯЩИХ”
},
{
“parameters”: {
“sessionIdType”: “customKey”,
“sessionKey”: “={\n "parameters": {\n "sessionIdType": "customKey",\n "sessionKey": "={{ $json.sessionId }}",\n "contextWindowLength": 10\n }\n}\n”,
“contextWindowLength”: 10
},
“type”: “@n8n/n8n-nodes-langchain.memoryBufferWindow”,
“typeVersion”: 1.3,
“position”: [
920,
560
],
“id”: “43e28c02-9b08-47da-8891-d83389603633”,
“name”: “Simple Memory”
},
{
“parameters”: {
“model”: {
“__rl”: true,
“value”: “gpt-4.1-mini”,
“mode”: “list”,
“cachedResultName”: “gpt-4.1-mini”
},
“options”: {}
},
“type”: “@n8n/n8n-nodes-langchain.lmChatOpenAi”,
“typeVersion”: 1.2,
“position”: [
800,
560
],
“id”: “96f23a85-8566-4fd3-90c1-d89a13790827”,
“name”: “OpenAI Chat Model”,
“credentials”: {
“openAiApi”: {
“id”: “BpxhpiEYc1Zu0k5g”,
“name”: “OpenAi account”
}
}
},
{
“parameters”: {
“chatId”: “={{ $(‘Telegram Trigger1’).item.json.message.from.id }}”,
“text”: “={{ $json.telegram.text }}”,
“additionalFields”: {
“appendAttribution”: “={{ false }}”
}
},
“id”: “46644fc2-7384-4b76-8b59-f2fac4c6d490”,
“name”: “Respond to Me2”,
“type”: “n8n-nodes-base.telegram”,
“typeVersion”: 1.2,
“position”: [
1420,
360
],
“webhookId”: “cd45388a-451a-42a0-b4aa-94857c5cc9f2”,
“credentials”: {
“telegramApi”: {
“id”: “MTm6Q7tzELOcNlL7”,
“name”: “авто автоматик”
}
}
},
{
“parameters”: {
“jsCode”: “// Парсинг ответа агента для отправки в Telegram\nconst inputData = $json;\n\nconsole.log(‘=== ПАРСИНГ ОТВЕТА АГЕНТА ДЛЯ TELEGRAM ===’);\n\ntry {\n // Извлекаем JSON из поля output\n const rawOutput = inputData.output || "";\n \n if (!rawOutput) {\n throw new Error("Отсутствуют данные от агента");\n }\n \n // Парсим JSON ответ\n const agentResponse = JSON.parse(rawOutput);\n \n console.log(‘Тип ответа:’, agentResponse.response_type);\n console.log(‘Действие:’, agentResponse.next_action);\n \n // Извлекаем основные данные для Telegram\n const telegramData = {\n text: agentResponse.message.text || "Сообщение не найдено",\n parse_mode: agentResponse.message.parse_mode || "MarkdownV2",\n chat_id: null, // будет заполнено из входящих данных\n session_id: agentResponse.session_data?.session_id || "unknown",\n response_type: agentResponse.response_type || "unknown"\n };\n \n // Дополнительные данные для логики\n const processingData = {\n next_action: agentResponse.next_action,\n follow_up_needed: agentResponse.follow_up_needed || false,\n support_interaction: agentResponse.session_data?.support_interaction || false,\n issue_resolved: agentResponse.session_data?.issue_resolved || false\n };\n \n // Проверяем наличие упоминания автоматизации\n let automationMessage = null;\n if (agentResponse.automation_mention?.included) {\n automationMessage = agentResponse.automation_mention.message;\n }\n \n const result = {\n // Основные данные для Telegram\n telegram: telegramData,\n \n // Данные для управления процессом\n processing: processingData,\n \n // Дополнительная информация\n automation_mention: automationMessage,\n \n // Отладочная информация\n debug: {\n original_response_type: agentResponse.response_type,\n session_id: agentResponse.session_data?.session_id,\n timestamp: new Date().toISOString()\n }\n };\n \n console.log(‘:white_check_mark: Успешно распарсен ответ агента’);\n console.log(‘Текст сообщения (первые 100 символов):’, telegramData.text.substring(0, 100));\n console.log(‘Следующее действие:’, processingData.next_action);\n \n return { json: result };\n \n} catch (error) {\n console.error(‘:cross_mark: Ошибка парсинга ответа агента:’, error.message);\n \n // Возвращаем безопасный fallback ответ\n return {\n json: {\n telegram: {\n text: "Произошла ошибка при обработке ответа. Пожалуйста, повторите запрос.",\n parse_mode: "MarkdownV2",\n chat_id: null,\n session_id: "error",\n response_type: "error"\n },\n processing: {\n next_action: "error",\n follow_up_needed: false,\n support_interaction: true,\n issue_resolved: false\n },\n automation_mention: null,\n debug: {\n error_message: error.message,\n timestamp: new Date().toISOString()\n }\n }\n };\n}\n”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 2,
“position”: [
1240,
360
],
“id”: “6751d6f2-c524-4430-b4b8-4ea728ddd73e”,
“name”: “пробразователь1”
}
],
“pinData”: {},
“connections”: {
“If”: {
“main”: [
[
{
“node”: “Switch1”,
“type”: “main”,
“index”: 0
}
]
]
},
“Telegram Trigger1”: {
“main”: [
[
{
“node”: “If”,
“type”: “main”,
“index”: 0
}
]
]
},
“OpenAI”: {
“main”: [
[
{
“node”: “Code2”,
“type”: “main”,
“index”: 0
}
]
]
},
“OpenAI5”: {
“main”: [
[
{
“node”: “Code2”,
“type”: “main”,
“index”: 0
}
]
]
},
“Get Image Info1”: {
“main”: [
[
{
“node”: “OpenAI5”,
“type”: “main”,
“index”: 0
}
]
]
},
“Switch1”: {
“main”: [
[
{
“node”: “Telegram5”,
“type”: “main”,
“index”: 0
}
],
[
{
“node”: “Telegram1”,
“type”: “main”,
“index”: 0
}
],
[
{
“node”: “Code2”,
“type”: “main”,
“index”: 0
}
]
]
},
“Telegram5”: {
“main”: [
[
{
“node”: “Get Image Info1”,
“type”: “main”,
“index”: 0
}
]
]
},
“Telegram1”: {
“main”: [
[
{
“node”: “OpenAI”,
“type”: “main”,
“index”: 0
}
]
]
},
“Simple Memory”: {
“ai_memory”: [
[
{
“node”: “AI АНАЛИЗ ВХОДЯЩИХ”,
“type”: “ai_memory”,
“index”: 0
}
]
]
},
“OpenAI Chat Model”: {
“ai_languageModel”: [
[
{
“node”: “AI АНАЛИЗ ВХОДЯЩИХ”,
“type”: “ai_languageModel”,
“index”: 0
}
]
]
},
“Code2”: {
“main”: [
[
{
“node”: “AI АНАЛИЗ ВХОДЯЩИХ”,
“type”: “main”,
“index”: 0
}
]
]
},
“пробразователь1”: {
“main”: [
[
{
“node”: “Respond to Me2”,
“type”: “main”,
“index”: 0
}
]
]
},
“AI АНАЛИЗ ВХОДЯЩИХ”: {
“main”: [
[
{
“node”: “пробразователь1”,
“type”: “main”,
“index”: 0
}
]
]
}
},
“active”: false,
“settings”: {
“executionOrder”: “v1”
},
“versionId”: “b0c73f1d-6418-4a26-9eeb-fd1f448c1666”,
“meta”: {
“instanceId”: “997f08652b7c0d5f762977f2d7f728a949a9830379892e235312783fe9fa4476”
},
“id”: “cZrFRnHzPhaGs2ji”,
“tags”:
}