8
n8n 中文网amn8n.com

Telegram AI频道机器人 - 支持文本和图像响应的TGPT生成器

高级

这是一个自动化工作流,包含 22 个节点。主要使用 If, Set, Code, Switch, SplitOut 等节点。 使用GPT-4和TGPT在Telegram频道中生成文本和图像响应

前置要求
  • Telegram Bot Token
  • 可能需要目标 API 的认证凭证

分类

-
工作流预览
可视化展示节点连接关系,支持缩放和平移
导出工作流
复制以下 JSON 配置到 n8n 导入,即可使用此工作流
{
  "id": "NyILudHveZv2PCWA",
  "meta": {
    "instanceId": "5c7ce220523e8664f49208a8be668a8dc6fab5f747ce4de865fa1309727919f1"
  },
  "name": "Telegram AI 频道机器人 - 支持文本和图像响应的 TGPT 生成器",
  "tags": [],
  "nodes": [
    {
      "id": "b0b9e65b-b10b-4515-a0d1-7bddf468fe43",
      "name": "定时任务",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -1568,
        256
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "seconds",
              "secondsInterval": 10
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "1e9869bb-34b6-4446-acf7-7a7da358f842",
      "name": "配置",
      "type": "n8n-nodes-base.set",
      "position": [
        -1344,
        256
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "bot-token",
              "name": "bot_token",
              "type": "string",
              "value": "your_telegram_token"
            },
            {
              "id": "channel-id",
              "name": "channel_id",
              "type": "string",
              "value": "your_telegram_channel_id"
            },
            {
              "id": "last-offset",
              "name": "last_offset",
              "type": "number",
              "value": "={{ $getWorkflowStaticData('global').last_offset || 0 }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "56f197e8-0e2e-43e6-ba3b-d87ddcf47673",
      "name": "获取更新",
      "type": "n8n-nodes-base.httpRequest",
      "onError": "continueRegularOutput",
      "position": [
        -1120,
        256
      ],
      "parameters": {
        "url": "=https://api.telegram.org/bot{{ $json.bot_token }}/getUpdates",
        "options": {
          "timeout": 30000
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "allowed_updates",
              "value": "[\"channel_post\"]"
            },
            {
              "name": "timeout",
              "value": "3"
            },
            {
              "name": "offset",
              "value": "={{ $json.last_offset }}"
            },
            {
              "name": "limit",
              "value": "15"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "d6884a27-1999-4cea-9c83-427cdb507892",
      "name": "处理偏移量",
      "type": "n8n-nodes-base.code",
      "position": [
        -896,
        256
      ],
      "parameters": {
        "jsCode": "// Process Offset - Complete solution with time window and duplicate prevention\nconst results = items[0].json.result || [];\nconst staticData = $getWorkflowStaticData('global');\n\n// Initialize if needed\nif (!staticData.processed_ids) {\n  staticData.processed_ids = [];\n  staticData.last_offset = 0;\n}\n\n// Get previous offset\nconst previousOffset = staticData.last_offset || 0;\n\n// Current time (Unix timestamp)\nconst currentTime = Math.floor(Date.now() / 1000);\nconst timeWindowSeconds = 15; // Slightly larger window for delays\n\n// Debug info\nconsole.log('=== Process Offset Debug ===' );\nconsole.log('Previous offset:', previousOffset);\nconsole.log('Number of messages received:', results.length);\nconsole.log('Number of processed IDs:', staticData.processed_ids.length);\n\n// ALWAYS update offset if there are results\nif (results.length > 0) {\n  const maxUpdateId = Math.max(...results.map(r => r.update_id));\n  staticData.last_offset = maxUpdateId + 1;\n  console.log('Offset updated:', staticData.last_offset);\n}\n\n// Filter: only new messages + time window + not yet processed\nconst newMessages = results.filter(msg => {\n  // Check if already processed\n  if (staticData.processed_ids.includes(msg.update_id)) {\n    console.log(`Message ${msg.update_id} already processed, skipping`);\n    return false;\n  }\n  \n  // Check time window\n  const messageTime = msg.channel_post?.date || 0;\n  const timeDiff = currentTime - messageTime;\n  \n  if (timeDiff > timeWindowSeconds) {\n    console.log(`Message ${msg.update_id} too old (${timeDiff}s), skipping`);\n    return false;\n  }\n  \n  // Check if newer than previous offset\n  if (msg.update_id < previousOffset) {\n    console.log(`Message ${msg.update_id} older than offset ${previousOffset}, skipping`);\n    return false;\n  }\n  \n  console.log(`Message ${msg.update_id} will be processed (${timeDiff}s old)`);\n  return true;\n});\n\n// If there are new messages\nif (newMessages.length > 0) {\n  // Add processed IDs\n  newMessages.forEach(msg => {\n    staticData.processed_ids.push(msg.update_id);\n  });\n  \n  // Cleanup: keep only last 100 IDs\n  if (staticData.processed_ids.length > 100) {\n    staticData.processed_ids = staticData.processed_ids.slice(-100);\n  }\n  \n  console.log(`${newMessages.length} new messages to process`);\n  \n  // Return new messages WITH OFFSET\n  return newMessages.map(msg => ({\n    json: {\n      ...msg,\n      _current_offset: staticData.last_offset\n    }\n  }));\n} else {\n  console.log('No new messages within time window');\n  \n  // If no new messages, still return the offset\n  return [{\n    json: {\n      _no_new_message: true,\n      _current_offset: staticData.last_offset\n    }\n  }];\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "b241edda-7c4c-439f-923f-866ad1f7784f",
      "name": "分流",
      "type": "n8n-nodes-base.splitOut",
      "onError": "continueRegularOutput",
      "position": [
        -672,
        256
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "channel_post.text"
      },
      "typeVersion": 1
    },
    {
      "id": "f194dc72-3089-4461-9424-437ccab2d019",
      "name": "过滤器",
      "type": "n8n-nodes-base.if",
      "position": [
        -448,
        256
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "channel-check",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $('Process Offset').item.json.channel_post.chat.id.toString() }}",
              "rightValue": "={{ $('Config').item.json.channel_id.toString() }}"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "c266df6f-c97f-439f-86ce-77aa37b08c6b",
      "name": "清洁",
      "type": "n8n-nodes-base.code",
      "position": [
        224,
        0
      ],
      "parameters": {
        "jsCode": "const rawOutput = items[0].json.stdout || '';\n\nif (!rawOutput) {\n  console.log('Nincs kimenet az Execute node-tól');\n  return [{\n    json: {\n      humanReadableText: 'Hiba történt a válasz generálása során.'\n    }\n  }];\n}\n\nlet cleaned = rawOutput\n\nreturn [\n  {\n    json: {\n      humanReadableText: cleaned\n    }\n  }\n];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "66e7c7ac-7859-4ec3-a5e4-5163ff118b4e",
      "name": "切换",
      "type": "n8n-nodes-base.switch",
      "position": [
        -192,
        256
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "am",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "7831171b-9c57-4791-85cf-858817111370",
                    "operator": {
                      "type": "string",
                      "operation": "startsWith"
                    },
                    "leftValue": "={{ $('Split').item.json['channel_post.text'] }}",
                    "rightValue": "am# "
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "ami",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "e9588452-a020-43c9-b75b-c182b629e97d",
                    "operator": {
                      "type": "string",
                      "operation": "startsWith"
                    },
                    "leftValue": "={{ $('Split').item.json['channel_post.text'] }}",
                    "rightValue": "ami# "
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.2
    },
    {
      "id": "6ea51b7d-e8e5-4030-aedd-fa5dbec50a1f",
      "name": "执行 - 文本",
      "type": "n8n-nodes-base.executeCommand",
      "position": [
        0,
        0
      ],
      "parameters": {
        "command": "=addscriptifnotexists=$(apk add util-linux-misc)\naddcurlifnotexists=$(apk add curl)\n\nautomessage=\"{{ $('Split').item.json['channel_post.text'] }}\"\nprompt=$(echo \"$automessage\" | sed 's/am#//')\n\ngetpackagetgpt=$(curl -LO https://github.com/aandrew-me/tgpt/releases/download/v2.11.0/tgpt-linux-amd64)\nmv ./tgpt-linux-amd64 ./tgpt\nchmod +x ./tgpt\n\nrm -rf /tmp/response.txt\nscript -q -c \"./tgpt --model \\\"gtp-4\\\" --temperature \\\"0.3\\\" -q \\\"$prompt\\\" >> /tmp/response.txt\" /dev/null\n\ntput reset\ncat /tmp/response.txt | sed '/^\\r*@web_search/d'"
      },
      "typeVersion": 1,
      "continueOnFail": true
    },
    {
      "id": "8f038fc1-f7d7-45f0-8a54-76e423c3d05a",
      "name": "执行 - 图像",
      "type": "n8n-nodes-base.executeCommand",
      "position": [
        0,
        528
      ],
      "parameters": {
        "command": "=apk add util-linux-misc\nautomessage=\"{{ $('Split').item.json['channel_post.text'] }}\"\nprompt=$(echo \"$automessage\" | sed 's/ami#//')\ncurl -LO https://github.com/aandrew-me/tgpt/releases/download/v2.11.0/tgpt-linux-amd64\nmv ./tgpt-linux-amd64 ./tgpt\nchmod +x ./tgpt\nrm -rf /tmp/genimg.jpg\necho \"$prompt\"\nscript -q -c \"./tgpt  -image --height=1080 --width=1920 --out=/tmp/genimg.jpg --model \\\"gtp-4\\\" --temperature \\\"0.7\\\" \\\"$prompt\\\"\" /dev/null"
      },
      "typeVersion": 1,
      "continueOnFail": true
    },
    {
      "id": "66f1dc6c-f36e-41ca-857d-bc1cd9609c28",
      "name": "发送 Telegram 文本响应",
      "type": "n8n-nodes-base.telegram",
      "position": [
        448,
        0
      ],
      "webhookId": "469e6cfb-80c6-450f-a1ce-c1bf6cf15f64",
      "parameters": {
        "text": "={{ $json.humanReadableText }}",
        "chatId": "={{ $('Config').item.json.channel_id }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "id": "FUXl519hpM0FsK8j",
          "name": "Telegram account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "200f6f2b-5772-40a6-b6a5-4e7253cb6ebb",
      "name": "发送 Telegram 图像响应",
      "type": "n8n-nodes-base.telegram",
      "position": [
        448,
        528
      ],
      "webhookId": "1d13a0d3-6224-43c0-802f-7cdabb49ef98",
      "parameters": {
        "chatId": "={{ $('Config').item.json.channel_id }}",
        "operation": "sendPhoto",
        "binaryData": true,
        "additionalFields": {},
        "binaryPropertyName": "=genimg"
      },
      "credentials": {
        "telegramApi": {
          "id": "FUXl519hpM0FsK8j",
          "name": "Telegram account"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "8595bf68-1061-472c-9b65-f783fbc0ca8f",
      "name": "读取生成的图像",
      "type": "n8n-nodes-base.readWriteFile",
      "position": [
        224,
        528
      ],
      "parameters": {
        "options": {
          "fileName": "genimg.jpg",
          "dataPropertyName": "genimg"
        },
        "fileSelector": "=/tmp/genimg.jpg"
      },
      "typeVersion": 1
    },
    {
      "id": "a2c3e370-36e7-4d46-8f1d-639726c0439c",
      "name": "清空更新列表",
      "type": "n8n-nodes-base.httpRequest",
      "onError": "continueRegularOutput",
      "position": [
        -896,
        496
      ],
      "parameters": {
        "url": "=https://api.telegram.org/bot{{ $('Config').item.json.bot_token }}/getUpdates?offset={{ $json._current_offset }}",
        "options": {
          "timeout": 30000
        },
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "allowed_updates",
              "value": "[\"channel_post\"]"
            },
            {
              "name": "timeout",
              "value": "3"
            },
            {
              "name": "offset",
              "value": "={{ $json.last_offset }}"
            },
            {
              "name": "limit",
              "value": "15"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "f1188129-6ad5-4c29-8fa8-b03b7e440ebb",
      "name": "便签",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1968,
        -16
      ],
      "parameters": {
        "width": 492,
        "height": 248,
        "content": "## Telegram AI 频道机器人"
      },
      "typeVersion": 1
    },
    {
      "id": "ae0fe6cb-6c11-483c-9011-524f3c156e5e",
      "name": "便签1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1456,
        432
      ],
      "parameters": {
        "width": 320,
        "height": 276,
        "content": "## 需要配置"
      },
      "typeVersion": 1
    },
    {
      "id": "67494d2b-6e50-405f-a4be-9f2b3860b759",
      "name": "便签2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1120,
        -64
      ],
      "parameters": {
        "width": 340,
        "height": 292,
        "content": "## 消息轮询与处理"
      },
      "typeVersion": 1
    },
    {
      "id": "0a3b2b8c-294d-4277-8232-743fcc47c68a",
      "name": "便签3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -448,
        432
      ],
      "parameters": {
        "width": 348,
        "height": 208,
        "content": "## 过滤与消息路由"
      },
      "typeVersion": 1
    },
    {
      "id": "75b560d9-9698-4e46-a09f-fed0f645223c",
      "name": "便签4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        16,
        -208
      ],
      "parameters": {
        "width": 556,
        "height": 192,
        "content": "## 文本生成流水线"
      },
      "typeVersion": 1
    },
    {
      "id": "06cad956-9231-4216-b675-0ca3e3d3d11e",
      "name": "便签5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        0,
        704
      ],
      "parameters": {
        "width": 556,
        "height": 192,
        "content": "## 图像生成流水线"
      },
      "typeVersion": 1
    },
    {
      "id": "1b710ffd-80e0-4026-9420-b07dcac1c995",
      "name": "便签6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        528,
        192
      ],
      "parameters": {
        "width": 300,
        "height": 308,
        "content": "## TELEGRAM 凭据"
      },
      "typeVersion": 1
    },
    {
      "id": "81df46e8-10a8-4385-8121-8b40c00c26b7",
      "name": "便签7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1968,
        256
      ],
      "parameters": {
        "width": 340,
        "height": 224,
        "content": "## 使用命令"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "5405a7b9-8287-4ac9-bfef-fc1b83956ea6",
  "connections": {
    "Clean": {
      "main": [
        [
          {
            "node": "Send Telegram Text Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split": {
      "main": [
        [
          {
            "node": "Filter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config": {
      "main": [
        [
          {
            "node": "Get Updates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Execute - Text",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute - Image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Schedule": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Updates": {
      "main": [
        [
          {
            "node": "Process Offset",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute - Text": {
      "main": [
        [
          {
            "node": "Clean",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process Offset": {
      "main": [
        [
          {
            "node": "Split",
            "type": "main",
            "index": 0
          },
          {
            "node": "Clear Update List",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute - Image": {
      "main": [
        [
          {
            "node": "Read Generated Image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Generated Image": {
      "main": [
        [
          {
            "node": "Send Telegram Image Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
常见问题

如何使用这个工作流?

复制上方的 JSON 配置代码,在您的 n8n 实例中创建新工作流并选择「从 JSON 导入」,粘贴配置后根据需要修改凭证设置即可。

这个工作流适合什么场景?

高级

需要付费吗?

本工作流完全免费,您可以直接导入使用。但请注意,工作流中使用的第三方服务(如 OpenAI API)可能需要您自行付费。

工作流信息
难度等级
高级
节点数量22
分类-
节点类型11
难度说明

适合高级用户,包含 16+ 个节点的复杂工作流

外部链接
在 n8n.io 查看

分享此工作流