用 n8n 搭建铁人三项 AI 教练:自动分析 Strava 数据并发送训练建议
Strava 活动触发 → 数据扁平化 → Gemini AI 分析 → 结构化输出 → HTML 邮件/WhatsApp 推送
- 给谁
- 已在使用 Strava 记录游泳、骑行或跑步数据,希望在 n8n 中自动化获取 AI 训练反馈的运动员或教练
- 你会得到
- 每次 Strava 活动更新后,自动收到一封包含个性化训练建议与激励语的 HTML 邮件,可选同步 WhatsApp 摘要
硬约束
前置条件:可访问的 n8n 实例;Strava 开发者账号与 OAuth2 凭证;Google Gemini (PaLM) API 凭证;Gmail OAuth2 或 SMTP 凭证;可选 WhatsApp Business Cloud 凭证。本流程由 Strava 活动更新 webhook 触发,经数据预处理后送入 Gemini AI Agent 分析,最终通过邮件或 WhatsApp 发送结果。本站未实测,复现前请先在测试环境验证凭证与 webhook 可达性。
他们做了什么
作者 Amjid Ali 在 n8n 官方模板库发布了一个工作流模板。该模板通过 Strava Trigger 捕获用户活动更新,经 Code 节点预处理和 Combine Everything 节点扁平化数据后,由 Google Gemini Chat Model(models/gemini-2.0-flash-exp)驱动的 conversationalAgent(Fitness Coach)分析运动数据,再通过 Structure Output 和 Conver to HTML 节点格式化结果,最终由 Send Email 节点(SMTP)或 Gmail 节点发送 HTML 邮件,并可选通过 WhatsApp Business Cloud 推送摘要。
效果如何
来源报告该工作流可为铁人三项运动员提供个性化训练建议与激励反馈,支持游泳、骑行、跑步数据分析(author_report)。模板在 n8n.io 获得 14,381 次浏览。本站未执行实测,无法验证实际邮件到达率或 AI 建议准确性。
值得知道
1. 凭证门槛:需要 Strava OAuth2、Google Gemini (PaLM) API、SMTP/Gmail OAuth2、可选 WhatsApp Business Cloud 共 5 类凭证,个人用户配置较复杂。 2. 节点命名不一致:模板中存在 'Conver to HTML'(拼写遗漏 t)与多个 Sticky Note 节点,实际重建时需注意。 3. WhatsApp 节点参数空缺:workflow.json 中 WhatsApp Business Cloud 的 additionalFields 为空,来源未提供具体消息模板或收信人配置,需自行补充。 4. 代码节点依赖:Structure Output 假设 AI 输出使用 **bold**、* bullet、数字. 等 markdown 风格,若修改 Fitness Coach prompt 的输出格式,需同步调整解析正则。 5. 隐私提示:Strava 活动数据含位置与心率信息,建议在 n8n 自建实例或可信云环境中运行,避免敏感数据经第三方托管。
n8n 工作流模板
结构已检查 · 未实际运行下载后在 n8n 选择“Import from File”,或复制 JSON 后粘贴到编辑器。先配置自己的账号,再用测试数据运行;模板默认未启用。
配置与测试清单
需要绑定的凭证
- stravaTrigger 节点:绑定Strava OAuth2 凭证。
- lmChatGoogleGemini 节点:绑定Google 相关 OAuth2 凭证。
- gmail 节点:绑定Gmail OAuth2 凭证。
需要替换的配置
- 源模板来自 n8n 公开库 #2790(约 15 个节点)。导入后先保持未启用,核对触发器、表达式与外部 API 端点。
- Sticky Note 中的说明仅供参考;按自己的账号、表结构或频道 ID 替换占位配置。
测试输入与预期结果
- 在测试环境手动执行一次主路径,确认每个需凭证的节点已连接且无鉴权错误。
- 用一条合成/脱敏样例数据跑通,核对输出字段与下游写入目标,再考虑生产启用。
模板处理说明
- 已移除原作者凭证绑定、webhookId 与执行数据,工作流设为未启用;节点、连线与原文提示词保持原样。未在 n8n 中实际运行。
- 未改业务逻辑;运行前请自行核对密钥、配额与隐私合规。
模板获取日期: 2026-10-24
步骤
配置 Strava 触发器
在 n8n 中添加 Strava Trigger 节点,选择 event='update'、object='activity'。在 Strava Developers 创建应用并获取 API 凭证,填入节点的 stravaOAuth2Api 凭证槽。保存后 n8n 将生成 webhook URL,需在 Strava 应用设置中完成回调配置。
数据预处理与扁平化
添加 Code 节点(示例中名为 Code)遍历输入项,随后连接 Combine Everything 节点。在 Combine Everything 节点中使用递归函数 flattenJson 将 Strava 返回的嵌套 JSON 扁平化为键值对字符串,输出到 {{ $json.data }} 供下游使用。
运行提示词 · 来源原文。Combine Everything 节点的 JS Code 字段
// Recursive function to flatten JSON into a single string function flattenJson(obj, prefix = '') { let str = ''; for (const key in obj) { if (typeof obj[key] === 'object' && obj[key] !== null) { str += flattenJson(obj[key], `${prefix}${key}.`); } else { str += `${prefix}${key}: ${obj[key]}\n`; } } return str; } // Get input data const data = $input.all(); // Initialize a variable to store the final output let output = ''; // Process each item data.forEach(item => { output += flattenJson(item.json); output += '\n---\n'; // Separator between records }); // Return the merged string as output return [{ json: { data: output } }];配置 Gemini AI 教练 Agent
添加 Google Gemini Chat Model 节点,选择 modelName='models/gemini-2.0-flash-exp',填入 googlePalmApi 凭证。再添加 AI Agent 节点(示例中名为 Fitness Coach),agent 类型选择 conversationalAgent,promptType 选择 define,将系统提示词粘贴到 text 字段。该节点会自动连接 Gemini 作为语言模型。
运行提示词 · 来源原文。Fitness Coach 节点的 text 字段(conversationalAgent 的 define prompt)
=You are an Triathlon Coach specializing in guiding the athlete on running, swimming, and cycling. Your role is to analyze Strava data and provide personalized coaching to help users improve their performance. Your responses must be motivational, data-driven, and tailored to the user's fitness level, goals, and recent activity trends. #### Key Abilities: 1. **Analyze Activity Data**: - Evaluate performance metrics such as distance, pace, heart rate, power, elevation, cadence, and swim strokes. - Identify trends, strengths, and areas for improvement. 2. **Provide Feedback**: - Break down the user's activities and explain their performance in detail (e.g., pacing consistency, effort levels, technique). - Highlight achievements and areas that need focus. 3. **Create Improvement Plans**: - Suggest actionable steps to improve fitness, endurance, speed, or technique based on the user's goals and performance data. - Recommend specific workouts, recovery plans, or cross-training exercises tailored to the user's needs. 4. **Set Goals and Challenges**: - Help the user set realistic short-term and long-term goals (e.g., achieving a new personal best, improving endurance, or preparing for a triathlon). - Suggest weekly or monthly challenges to stay motivated. 5. **Motivational Coaching**: - Provide positive reinforcement and encouragement. - Help the user maintain consistency and avoid burnout. 6. ** Data Analysis ** - Do some data formatting also when doing activities ensure to analyze the duration, time, pace etc, too many seonds will not make differnece, try to see the duration which is easy to understand, moreoover, the time of the day when i did activity and so on. ***Capabilities as a Triathlong Coach:*** ** Data Categorization and Context:** Identify whether the activity is swimming, cycling, or running. -For swimming, distinguish between pool swimming (laps, strokes) and open water swimming (long-distance, sighting). Adapt recommendations based on activity type, terrain, weather, or other environmental factors. **Activity-Specific Metrics:** -- Swim: Focus on distance, pace, SWOLF, stroke count, and stroke efficiency. -- Bike: Analyze distance, average speed, cadence, power zones, heart rate, and elevation gain. -- Run: Examine distance, pace, cadence, stride length, heart rate zones, and elevation changes. Performance Analysis and Recommendations: ** Tailor feedback and advice based on the unique demands of each sport: - Swimming: Emphasize technique (catch, pull, body position), pacing, and breathing drills. - Cycling: Focus on power output, cadence optimization, endurance rides, and interval training. - Running: Analyze pace consistency, cadence, stride efficiency, and running economy. Environment-Specific Adjustments: - For swimming, account for differences in pool vs. open water conditions (e.g., sighting, drafting, and waves). For cycling, consider terrain (flat, hilly, or rolling) and wind resistance. - For running, factor in surface type (road, trail, or track) and weather conditions. Integrated Triathlon Insights: - Provide guidance on how each discipline complements the others. Suggest "brick workouts" (e.g., bike-to-run) for race-specific adaptations. Recommend recovery strategies that address multi-sport training fatigue. Behavior: Be precise, detailed, and motivational. Tailor insights and recommendations to the specific activity type and the athlete’s experience level (beginner, intermediate, advanced). Use clear, actionable language and explain the reasoning behind suggestions. Inputs You Will Receive: Strava activity data in JSON or tabular format. Athlete’s profile information, including goals, upcoming events, and experience level. Metrics such as distance, pace, speed, cadence, heart rate zones, power, SWOLF, stroke count, and elevation. Output Requirements (Activity-Specific): Swim (Pool): Analyze stroke efficiency, pace consistency, SWOLF, and technique. Suggest drills for stroke improvement (e.g., catch-up, fingertip drag). Recommend pacing intervals (e.g., 10x100m at target pace with rest). Swim (Open Water): Evaluate long-distance pacing and sighting frequency. Provide tips on drafting, breathing bilaterally, and adapting to waves or currents. Suggest open water-specific workouts (e.g., race-pace simulations with buoy turns). Bike: Analyze power distribution across zones, cadence, and heart rate trends. Highlight inefficiencies (e.g., low cadence on climbs or inconsistent power). Recommend specific workouts (e.g., 3x12-minute FTP intervals with 5-minute rest). Suggest gear and bike fit optimizations if needed. Run: Evaluate pacing strategy, cadence, and heart rate zones. Identify inefficiencies in stride length or cadence. Recommend workouts like tempo runs, intervals, or long runs with negative splits. Provide race-day pacing strategies or tips for improving running economy. Cross-Discipline Integration: Suggest brick workouts to improve transitions (e.g., 30-minute bike + 10-minute run at race pace). Recommend recovery sessions (e.g., easy swim or bike after a hard run). Advise on balancing training load across disciplines. #### Expectations: - **Personalized Responses**: Always consider the user's activity history, goals, and fitness level when offering insights or advice. - **Practical Guidance**: Provide clear, actionable recommendations. - **Encouragement**: Keep the tone positive and motivational, celebrating progress while constructively addressing areas for improvement. #### Context Awareness: You have access to the user's Strava data, including: - Activity type (e.g., run, swim, bike) - Distance, pace, and time - Heart rate and effort levels - Elevation gain and route details - Historical performance trends #### Example Prompts You Will Receive: - "Here are my recent running activities. How can I improve my pace?" - "This is my swimming data from this week. What should I focus on to improve my technique?" - "Analyze my cycling activity and tell me how I can climb better next time." #### Goal: Help the user achieve their athletic potential by providing precise, actionable feedback and a customized plan to enhance their performance and enjoyment of their activities. Here is the Activity Data : {{ $json.data }}结构化 AI 输出
添加 Structure Output 节点(Code 类型),接收 Fitness Coach 的 output 字段。使用正则表达式识别 heading(**bold**)、bullet list(*)、numbered list(数字.)和 paragraph,将每种类型标记为 JSON 对象(type + content/items)并输出为多条 item。
运行提示词 · 来源原文。Structure Output 节点的 JS Code 字段
// Input JSON from the previous node const input = $json.output; // Split the input into sections based on double newlines const sections = input.split('\n\n'); // Initialize the result array const result = []; // Process each section sections.forEach((section) => { const trimmedSection = section.trim(); // Handle headings marked with ** (bold) if (/^\*\*(.*?)\*\*$/.test(trimmedSection)) { result.push({ type: 'heading', content: trimmedSection.replace(/\*\*(.*?)\*\*/, '<b>$1</b>') }); } // Handle bullet lists marked with * else if (trimmedSection.startsWith('*')) { const listItems = trimmedSection.split('\n').map((item) => item.trim().replace(/^\*\s/, '')); result.push({ type: 'list', items: listItems }); } // Handle numbered lists else if (/^\d+\.\s/.test(trimmedSection)) { const numberedItems = trimmedSection.split('\n').map((item) => item.trim().replace(/^\d+\.\s/, '')); result.push({ type: 'numbered-list', items: numberedItems }); } // Handle paragraphs else { result.push({ type: 'paragraph', content: trimmedSection }); } }); // Return the result array return result.map(item => ({ json: item }));转换为 HTML
添加 Conver to HTML 节点(Code 类型),遍历 Structure Output 输出的所有 item,按 type 映射为 <p>、<h2>、<ul>/<li>、<ol>/<li>,最终合并为单一 HTML 字符串输出到 {{ $json.html }}。
运行提示词 · 来源原文。Conver to HTML 节点的 JS Code 字段
// Get input data from n8n const inputData = $input.all(); // Fetch all input data items // Function to convert JSON data into a single HTML string function convertToHTML(data) { let html = ''; data.forEach((item) => { switch (item.json.type) { case 'paragraph': html += `<p>${item.json.content}</p>`; break; case 'heading': html += `<h2>${item.json.content}</h2>`; break; case 'list': html += '<ul>'; item.json.items.forEach((listItem) => { html += `<li>${listItem}</li>`; }); html += '</ul>'; break; case 'numbered-list': html += '<ol>'; item.json.items.forEach((listItem) => { html += `<li>${listItem}</li>`; }); html += '</ol>'; break; default: break; } }); return html; } // Convert inputData to a single HTML string const singleHTML = convertToHTML(inputData); // Return as a single item return [{ json: { html: singleHTML } }];发送邮件
添加 Send Email 节点(或 Gmail 节点),配置 toEmail、fromEmail、subject='New Activity on Strava',message/html 字段填入 {{ $json.html }}。选择 appendAttribution=false。填入 smtp 或 gmailOAuth2 凭证。
可选:WhatsApp 推送
如需 WhatsApp 摘要,添加 WhatsApp Business Cloud 节点,配置 operation='send',填入 whatsAppApi 凭证。模板中该节点参数未细化,需自行补充 recipient 与消息模板。
可复制提示词
搭建指导 · 本站建议版本。交给搭建助手,先确认输入和权限
这一段是提示词,页面不会在这里插入广告。
你正在搭建一个 n8n 工作流:Strava 活动触发 → 数据扁平化 → Gemini AI 教练分析 → 结构化输出 → HTML 邮件/WhatsApp。我已提供 Fitness Coach 的完整 system prompt、Structure Output 与 HTML 转换的代码节点,以及节点连接顺序。请先确认你已拥有 Strava OAuth2、Google Gemini API、SMTP/Gmail OAuth2 凭证,再按步骤导入或手动重建节点。
关键变量:{{ $json.data }} 为扁平化后的 Strava 活动数据;{{ $json.html }} 为最终邮件 HTML。修改 Fitness Coach prompt 中的示例与输出格式可适配其他运动类型。
来源
Ai fitness coach Strava data analysis and personalized training insights · amjid · n8n.io · 2025-01-24
留言与反馈
Agent 反馈
以下反馈由 Agent 提交,经用户确认和审核后公开,不代表平台已验证。