很多团队已经在 Telegram 上与客户沟通。借助开源工作流自动化工具 n8n,无需开发完整的应用,就能搭建一个 Telegram 机器人:用 AI 模型回答问题、记住对话上下文、按照你设定的语气和范围作答,并在需要时转接人工。本文在服务器上通过 HTTPS 部署 n8n,创建机器人,并使用 Ollama 本地模型或 AI 服务商的 API 搭建工作流。
在 Telegram 中与 @BotFather 对话,发送 /newbot,设置名称和以“bot”结尾的用户名,然后复制 token。使用 /setdescription 和 /setuserpic 可以让机器人看起来更专业。请妥善保管 token,任何拿到它的人都能控制这个机器人。
n8n 运行在 Docker 中(参见我们的 Docker 安装教程)。请将域名和时区替换为你自己的。
docker volume create n8n_data
docker run -d --name n8n --restart always \
-p 127.0.0.1:5678:5678 \
--add-host=host.docker.internal:host-gateway \
-e N8N_HOST=n8n.example.com \
-e N8N_PROTOCOL=https \
-e WEBHOOK_URL=https://n8n.example.com/ \
-e GENERIC_TIMEZONE=Asia/Hong_Kong \
-e TZ=Asia/Hong_Kong \
-e N8N_PROXY_HOPS=1 \
-v n8n_data:/home/node/.n8n \
docker.n8n.io/n8nio/n8n
WEBHOOK_URL 必须是公网 HTTPS 地址,n8n 向 Telegram 注册 webhook 时会用到它。
server {
listen 443 ssl;
http2 on;
server_name n8n.example.com;
ssl_certificate /etc/letsencrypt/live/n8n.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/n8n.example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:5678;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_read_timeout 300s;
}
}
打开 https://n8n.example.com 并立即创建所有者(owner)账号。证书申请请参见使用 Certbot 或 acme.sh 申请免费 SSL 证书。
http://host.docker.internal:11434(Ollama 需按照使用 Ollama 运行本地大模型完成部署,包括允许 Docker 容器连接的步骤及其防火墙规则)。新建一个工作流并添加以下节点(不同 n8n 版本的节点名称可能略有差异):
qwen2.5:7b,或你的服务商的对话模型),以及一个以 chat ID 为键的记忆节点(Simple Memory),让每位客户都有各自独立的对话历史。节点字段中使用的表达式如下:
AI Agent - prompt (user message): {{ $json.message.text }}
Simple Memory - session key: {{ $('Telegram Trigger').item.json.message.chat.id }}
Telegram - chat ID: {{ $('Telegram Trigger').item.json.message.chat.id }}
Telegram - text: {{ $json.output }}
好的系统消息能让回答简短且不跑题,例如:
You are the customer service assistant of ACME Hosting.
Answer briefly and politely in the customer's language.
Only answer questions about our services, orders and technical support.
If you are not sure, or the customer asks for a refund or a person,
say that a colleague will reply soon. Never invent prices or promises.
保存并激活工作流,n8n 随后会向 Telegram 注册 webhook。给你的机器人发一条消息,如果没有任何反应,请检查 webhook 状态:
curl -s "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo"
url 应为你的 n8n 域名;last_error_message 会说明失败原因,例如证书问题或服务器无法访问。
{{ $json.message.chat.id }} 属于你团队成员的 chat ID 时才继续执行。每个机器人 token 只能设置一个 webhook,使用同一 token 的其他工作流、测试运行或脚本会将其覆盖。请检查 getWebhookInfo,每个机器人只保留一个激活的工作流,测试时使用单独的机器人。
在 CPU 上,较小的模型响应更快。保持系统消息简短,将记忆窗口限制为最近 10 条消息,并让模型在 Ollama 中常驻内存。
能做的还有很多。同一个工作流可以查询数据库中的订单、创建客服工单、向群组发帖或发送每日报告。n8n 的服务器配置要求请参见 Dify、n8n 与 AI Agent 服务器配置要求。
如果按以上步骤操作后问题仍未解决,请提交工单联系 IMIDC 7×24 技术支持,并附上服务器 IP、n8n 域名、getWebhookInfo 的输出以及 docker logs n8n 的输出,方便工程师快速定位。