8
n8n 中文网amn8n.com

为Telegram机器人添加用户授权层及管理员提醒

中级

这是一个Content Creation, Multimodal AI领域的自动化工作流,包含 11 个节点。主要使用 If, Code, Telegram, TelegramTrigger 等节点。 为Telegram机器人添加用户授权层及管理员提醒

前置要求
  • Telegram Bot Token
工作流预览
可视化展示节点连接关系,支持缩放和平移
导出工作流
复制以下 JSON 配置到 n8n 导入,即可使用此工作流
{
  "meta": {
    "instanceId": "82ee17baaf8f0713e544083c37cbe259962ad0fcd85204d3262a7dfafc166630",
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "572073b3-d68a-45cb-9c60-cdf3c697b151",
      "name": "便签 - 介绍",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3328,
        9664
      ],
      "parameters": {
        "color": 6,
        "width": 676,
        "height": 720,
        "content": "# 🛡️ BotGuard - 为什么需要这个"
      },
      "typeVersion": 1
    },
    {
      "id": "635277cb-fa42-4c8c-aaac-373132606208",
      "name": "便签 - 快速开始",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4064,
        9664
      ],
      "parameters": {
        "color": 4,
        "width": 520,
        "height": 720,
        "content": "# 🚀 快速开始"
      },
      "typeVersion": 1
    },
    {
      "id": "b321fe86-fbf9-4ec6-b7e5-d00735d951ef",
      "name": "便签 1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2432,
        9136
      ],
      "parameters": {
        "color": 5,
        "width": 853,
        "height": 1259,
        "content": "# 🛡️ BotGuard 授权系统"
      },
      "typeVersion": 1
    },
    {
      "id": "aa9b6109-3e51-4005-802e-29e43fa3e887",
      "name": "BotGuard 授权",
      "type": "n8n-nodes-base.code",
      "position": [
        3504,
        9168
      ],
      "parameters": {
        "jsCode": "// Configuration\nconst AllowedUsers = [\n  { userId: 8032941945, userName: 'ruslan_elishev_eu', subscriptionType: 'admin' },\n  { userId: 111111111, userName: 'john_doe', subscriptionType: 'basic' },\n  { userId: 222222222, userName: 'jane_smith', subscriptionType: 'premium' }\n];\n\nconst Administrators = [\n  { userId: 8032941945, userName: 'ruslan_elishev_eu', chatId: 8032941945 },\n  { userId: 333333333, userName: 'admin_user', chatId: 333333333 }\n];\n\nconst ProcessingRequests = [];\n\ntry {\n  const message = $input.item.json.message || {};\n  const userId = (message.from && message.from.id) || null;\n  const userName = (message.from && message.from.username) || (message.from && message.from.first_name) || 'Unknown';\n  const chatId = (message.chat && message.chat.id) || null;\n  const messageText = message.text || '';\n  const languageCode = (message.from && message.from.language_code) || 'en';\n\n  const isAuthorized = AllowedUsers.some(user => user.userId === userId);\n  const isAdmin = Administrators.some(admin => admin.userId === userId);\n  const isProcessingRequest = ProcessingRequests.some(req => req.userId === userId);\n  const isRequestCommand = messageText.toLowerCase() === '/request';\n\n  let allowEntry = isAuthorized || isAdmin;\n  let blockReason = '';\n  let userMessage = '';\n  let adminMessage = '';\n  let authorizedMessage = '';\n\n  const currentTime = new Date().toISOString();\n  const userInfo = AllowedUsers.find(user => user.userId === userId) || { subscriptionType: 'none' };\n\n  if (allowEntry) {\n    authorizedMessage = '✅ <b>Authorization Successful</b>\\n\\nWelcome back, ' + userName + '!\\nYour access level: ' + userInfo.subscriptionType + '\\n\\nProcessing your request...';\n  } else if (isProcessingRequest) {\n    blockReason = 'pending_approval';\n    const req = ProcessingRequests.find(r => r.userId === userId);\n    const reqTime = req && req.requestTime ? new Date(req.requestTime).toLocaleString() : 'Unknown';\n    userMessage = '⏳ <b>Access Pending</b>\\n\\nHello ' + userName + ',\\n\\nYour access request is currently being reviewed by an administrator. You will be notified once a decision has been made.\\n\\nRequest status: <code>PENDING</code>\\nSubmitted: ' + reqTime;\n  } else {\n    blockReason = 'not_authorized';\n    userMessage = '🚫 <b>Access Denied</b>\\n\\nHello ' + userName + ',\\n\\nYou are not authorized to use this bot. To request access, please use the /request command or contact an administrator.\\n\\nYour User ID: <code>' + userId + '</code>';\n    \n    if (!isRequestCommand) {\n      adminMessage = '🔔 <b>Unauthorized Access Attempt</b>\\n\\n<b>User Details:</b>\\n• Name: ' + userName + '\\n• User ID: <code>' + userId + '</code>\\n• Language: ' + languageCode + '\\n• Time: ' + currentTime + '\\n• Message: ' + messageText + '\\n\\n<b>Action Required:</b>\\nReview and approve/deny access';\n    }\n  }\n\n  const item = $input.item;\n  item.json.botGuard = {\n    allowEntry: allowEntry,\n    blockReason: blockReason,\n    userMessage: userMessage,\n    adminMessage: adminMessage,\n    authorizedMessage: authorizedMessage,\n    isProcessingRequest: isProcessingRequest,\n    isRequestCommand: isRequestCommand,\n    userId: userId,\n    userName: userName,\n    chatId: chatId,\n    messageText: messageText,\n    languageCode: languageCode,\n    accessAttemptTime: currentTime,\n    AllowedUsers: AllowedUsers,\n    Administrators: Administrators,\n    originalMessage: item.json.message,\n    userDetails: {\n      subscriptionType: userInfo.subscriptionType,\n      firstName: (message.from && message.from.first_name) || '',\n      lastName: (message.from && message.from.last_name) || '',\n      isBot: (message.from && message.from.is_bot) || false,\n      isPremium: (message.from && message.from.is_premium) || false\n    }\n  };\n\n  item.json.message = message;\n  return item;\n} catch (error) {\n  const item = $input.item;\n  item.json.botGuard = {\n    allowEntry: false,\n    blockReason: 'error',\n    userMessage: '❌ An error occurred during authorization. Please try again.',\n    adminMessage: '',\n    authorizedMessage: '',\n    error: error.message\n  };\n  return item;\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "2957eeff-698e-4166-9c16-600b3adb1a45",
      "name": "检查授权",
      "type": "n8n-nodes-base.if",
      "position": [
        3712,
        9168
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "auth-check",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $json.botGuard.allowEntry }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "b50e992a-4e69-4090-8859-68ca85338023",
      "name": "发送成功",
      "type": "n8n-nodes-base.telegram",
      "position": [
        3984,
        9152
      ],
      "webhookId": "4ed06f4b-fd2b-4f5f-a49f-2a145abff92f",
      "parameters": {
        "text": "={{ $json.botGuard.authorizedMessage }}",
        "chatId": "={{ $json.botGuard.chatId }}",
        "additionalFields": {
          "parse_mode": "HTML"
        }
      },
      "credentials": {
        "telegramApi": {
          "id": "j8EcZNDeFuDq9Cka",
          "name": "ElishevFamilyBot"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "a89c3bdf-8669-477d-a47b-0e8e8f1f6ed8",
      "name": "发送拒绝",
      "type": "n8n-nodes-base.telegram",
      "position": [
        3984,
        9328
      ],
      "webhookId": "4a8192ba-d5d0-4b32-9fe3-37ef8c163c52",
      "parameters": {
        "text": "={{ $json.botGuard.userMessage }}",
        "chatId": "={{ $json.botGuard.chatId }}",
        "additionalFields": {
          "parse_mode": "HTML"
        }
      },
      "credentials": {
        "telegramApi": {
          "id": "j8EcZNDeFuDq9Cka",
          "name": "ElishevFamilyBot"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "778d438c-d052-4a1a-a110-0f222f537bf9",
      "name": "检查管理员通知",
      "type": "n8n-nodes-base.if",
      "position": [
        4000,
        9488
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "has-admin-message",
              "operator": {
                "type": "string",
                "operation": "notEmpty"
              },
              "leftValue": "={{ $('Check Authorization').item.json.botGuard.adminMessage }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "97b78d57-a2ea-4fe0-9b93-7b6d1a08ebab",
      "name": "准备管理员通知",
      "type": "n8n-nodes-base.code",
      "position": [
        4208,
        9488
      ],
      "parameters": {
        "jsCode": "// Get data from Check Authorization node (before Telegram node)\nconst botGuardData = $('Check Authorization').item.json.botGuard;\nconst admins = botGuardData.Administrators;\nconst adminMessage = botGuardData.adminMessage;\n\n// Create output item for each admin\nconst items = admins.map(admin => ({\n  json: {\n    adminChatId: admin.chatId,\n    adminUserName: admin.userName,\n    adminMessage: adminMessage,\n    originalData: botGuardData\n  }\n}));\n\nreturn items;"
      },
      "typeVersion": 2
    },
    {
      "id": "aa0b65d3-0f22-4f5b-8a09-c146f9fe8a15",
      "name": "Telegram触发器",
      "type": "n8n-nodes-base.telegramTrigger",
      "position": [
        3312,
        9168
      ],
      "webhookId": "c4d1bcd6-c865-4b62-aa77-67aa9496f5c1",
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "credentials": {
        "telegramApi": {
          "id": "j8EcZNDeFuDq9Cka",
          "name": "ElishevFamilyBot"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "a9ad2dab-53e6-4381-a78c-7d1bb42e1b20",
      "name": "通知管理员",
      "type": "n8n-nodes-base.telegram",
      "position": [
        4400,
        9488
      ],
      "webhookId": "1245219a-33f7-46e9-9a41-c9eef1a52b40",
      "parameters": {
        "text": "={{ $json.adminMessage }}",
        "chatId": "={{ $json.adminChatId }}",
        "additionalFields": {
          "parse_mode": "HTML"
        }
      },
      "credentials": {
        "telegramApi": {
          "id": "j8EcZNDeFuDq9Cka",
          "name": "ElishevFamilyBot"
        }
      },
      "typeVersion": 1.2
    }
  ],
  "pinData": {},
  "connections": {
    "Telegram Trigger": {
      "main": [
        [
          {
            "node": "BotGuard Authorization",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Admin Notify": {
      "main": [
        [
          {
            "node": "Prepare Admin Notifications",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Authorization": {
      "main": [
        [
          {
            "node": "Send Success",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send Denied",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Admin Notify",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "BotGuard Authorization": {
      "main": [
        [
          {
            "node": "Check Authorization",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Admin Notifications": {
      "main": [
        [
          {
            "node": "Notify Admin",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
常见问题

如何使用这个工作流?

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

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

中级 - 内容创作, 多模态 AI

需要付费吗?

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

工作流信息
难度等级
中级
节点数量11
分类2
节点类型5
难度说明

适合有一定经验的用户,包含 6-15 个节点的中等复杂度工作流

作者
Ruslan Elishev

Ruslan Elishev

@relishev

Professional Product Director that cought vibe of Automaion and Solo Programming and Context Aware AI Vibe coding.

外部链接
在 n8n.io 查看

分享此工作流