🚀 Chapter 13: Automated Marketing – The Ultimate Marketing Robot

Congratulations! You have reached the pinnacle of the Vibe Coding curriculum. Let’s recap the milestones we’ve conquered:

  • Astro & React: Created a glass‑morphism front‑end that feels like a living interface.
  • Car‑Camping‑Map: Implemented Leaflet map interactions and connected them to a Supabase database.
  • Line‑Punch‑Web: Built a FastAPI backend capable of handling thousands of concurrent requests while preventing cheating.
  • CrewAI: Assembled a squad of autonomous AI agents that browse the web, fetch data, and send emails.

Now your boss hands you the ultimate SaaS feature:

“I want the system to run at 2 a.m. every day, scan the database for campsites with low occupancy, automatically generate compelling promotional copy, and push it to VIP customers via Line or email at 9 a.m. tomorrow.”

This is a cross‑domain challenge that blends database querying, multi‑agent AI collaboration, and asynchronous automation. In this 6,000‑word final battle, we will not write boilerplate code by hand. Instead, we will use Vibe Prompt to command AI to stitch together these three systems into a single, self‑sustaining “money‑printing machine.”


🕒 Practical 1: Building a Python Scheduler (Cron Job) Trigger

What

A scheduler is the heartbeat of any automated system. It wakes the machine at a precise time, ensuring the marketing script runs without manual intervention.

Why

If the scheduler lives in the front‑end, it disappears when the browser closes. By placing it in the FastAPI backend, the job persists as long as the server is alive, guaranteeing 100 % uptime for your revenue‑generating process.

How – Step by Step

  1. Choose a Scheduler
    The most reliable Python scheduler for async workloads is APScheduler. It supports cron syntax, interval jobs, and integrates seamlessly with FastAPI’s event loop.

  2. Create an Async Scheduler

    from fastapi import FastAPI
    from apscheduler.schedulers.asyncio import AsyncIOScheduler
    from datetime import datetime
    
    app = FastAPI(title="Automated Marketing System")
    
    # Instantiate the async scheduler
    scheduler = AsyncIOScheduler()
    
  3. Define the Marketing Task

    async def auto_marketing_campaign():
        """Daily marketing engine that will be triggered by the scheduler."""
        print(f"\n[{datetime.now()}] 🚀 Starting daily marketing script...")
        # Placeholder for CrewAI launch logic
    
  4. Hook into FastAPI Lifecycle

    @app.on_event("startup")
    async def startup_event():
        print("⏰ Initializing scheduler...")
        # Schedule the job – everyday at 2 a.m.
        scheduler.add_job(auto_marketing_campaign, 'cron', hour=2, minute=0)
    
        # For quick testing: run every 10 seconds
        # scheduler.add_job(auto_marketing_campaign, 'interval', seconds=10)
    
        scheduler.start()
        print("✅ Scheduler started successfully!")
    
  5. Graceful Shutdown

    @app.on_event("shutdown")
    async def shutdown_event():
        scheduler.shutdown()
    
  6. Run the Server

    uvicorn main:app --host 0.0.0.0 --port 8000
    

Tip: Keep the scheduler logic in a separate module (scheduler.py) and import it into main.py for cleaner code organization.


🗄️ Practical 2: Database Detector – Finding Under‑Performing Camps

What

We need to pull data from Supabase to identify campsites that have more than 10 vacancies and have been inactive for the last three days.

Why

Targeting the “dead” inventory ensures we allocate marketing spend where it can generate the highest incremental revenue, improving ROI and customer satisfaction.

How – Step by Step

  1. Initialize Supabase Client

    from supabase import create_client, Client
    
    SUPABASE_URL = "https://<your-project>.supabase.co"
    SUPABASE_KEY = "YOUR_SUPABASE_SERVICE_ROLE_KEY"
    
    supabase_client: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
    
  2. Write an Async Query Function

    async def fetch_underperforming_camps() -> list[dict] | None:
        try:
            print("📊 Scanning Supabase for under‑performing camps...")
            response = supabase_client.table("camps") \
                .select("id, name, feature, price, vacancy_count") \
                .gte("vacancy_count", 10) \
                .eq("is_active", True) \
                .execute()
    
            camps = response.data
            if not camps:
                print("🎉 All camps are near full capacity. No marketing needed today.")
                return None
    
            print(f"⚠️ Found {len(camps)} camps with excess vacancies.")
            return camps
        except Exception as e:
            print(f"❌ Database query failed: {e}")
            return None
    
  3. Integrate with the Scheduler
    Replace the placeholder in auto_marketing_campaign with a call to fetch_underperforming_camps().

  4. Early Exit
    If the function returns None, the scheduler should simply return, avoiding unnecessary downstream processing.


🧠 Practical 3: CrewAI Mobilization – Custom Copy for Each Camp

What

For every under‑performing campsite, we’ll spawn a CrewAI team that crafts a unique, SEO‑optimized promotional message.

Why

Automated, personalized copy increases click‑through rates and conversion. A generic template feels stale; AI‑generated copy feels fresh and relevant to each customer segment.

How – Step by Step

  1. Define the CrewAI Runner
    Assume we have a helper function run_crewai_marketing(camp_info: dict) -> str that internally creates a CrewAI agent, feeds it the camp data, and returns a marketing copy string.

  2. Iterate Over Camps

    import asyncio
    
    async def auto_marketing_campaign():
        print(f"\n[{datetime.now()}] 🚀 Starting daily marketing script...")
    
        # 1. Pull camps needing promotion
        camps_to_promote = await fetch_underperforming_camps()
        if not camps_to_promote:
            return
    
        print("🤖 Summoning CrewAI marketing squad...")
        final_campaigns = []
    
        # 2. For each camp, generate copy
        for camp in camps_to_promote:
            print(f"✍️ Writing copy for '{camp['name']}'...")
            marketing_copy = run_crewai_marketing(camp)
    
            final_campaigns.append({
                "camp_id": camp["id"],
                "camp_name": camp["name"],
                "copy": marketing_copy
            })
    
            print(f"✅ Copy for '{camp['name']}' ready!")
            await asyncio.sleep(5)  # Rate‑limit guard
    
        print(f"🔥 Marketing squad finished: {len(final_campaigns)} copies generated.")
    
  3. Rate‑Limiting Strategy
    The asyncio.sleep(5) pause ensures we do not hit OpenAI’s 429 errors. Adjust the interval based on your API quota.

  4. Logging & Monitoring
    Emit structured logs (e.g., JSON) so you can ingest them into a log aggregator like Loki or Datadog.


📱 Practical 4: Final Blow – Line Notify Push

What

We need to deliver the generated copy to VIP customers via Line.

Why

Line is a ubiquitous messaging platform in many markets. Push notifications have a higher open rate than emails, especially for time‑sensitive offers.

How – Step by Step

  1. Create a Send Function

    import os
    import httpx
    
    async def send_to_line_notify(message: str):
        token = os.getenv("LINE_NOTIFY_TOKEN")
        if not token:
            print("❌ LINE_NOTIFY_TOKEN missing. Skipping send.")
            return
    
        headers = {"Authorization": f"Bearer {token}"}
        data = {"message": message}
    
        try:
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    "https://notify-api.line.me/api/notify",
                    headers=headers,
                    data=data
                )
            if response.status_code == 200:
                print("📲 Line message sent successfully!")
            else:
                print(f"❌ Line API error: {response.text}")
        except Exception as e:
            print(f"❌ Network error: {e}")
    
  2. Compose Final Messages

    for campaign in final_campaigns:
        final_message = (
            f"\n\n🔥【Last Chance for the Weekend】🔥\n"
            f"{campaign['copy']}\n\n"
            f"👉 Book now: https://my-punch.vercel.app/book/{campaign['camp_id']}"
        )
        await send_to_line_notify(final_message)
    
    print("\n🎉 All marketing messages dispatched. Boss is ready to see the numbers!")
    
  3. Error Handling & Retries
    Wrap the send call in a retry loop with exponential back‑off if you anticipate transient network issues.

  4. Security
    Store LINE_NOTIFY_TOKEN in a secrets manager (e.g., AWS Secrets Manager, GCP Secret Manager) and load it at runtime.


🏆 The Complete System – A CTO‑Level Architecture

| Layer | Responsibility | Typical Role | Cost (Monthly) | Automation | |-------|----------------|--------------|----------------|------------| | Trigger | Scheduler wakes the system | DevOps Engineer | $200 | Fully automated | | Sensor | Supabase query for low occupancy | Data Engineer | $300 | Fully automated | | Brain | CrewAI agents generate copy | Marketing Specialist | $400 | Fully automated | | Action | Line Notify push | Customer Success | $100 | Fully automated |

Total: ~$1,000 per month for human labor.
Automation: 100 % of the workflow runs without human intervention, freeing up talent for higher‑value tasks.


🎓 From Code to Prompt – The Final Transition

You have just built a self‑contained, end‑to‑end marketing engine that:

  1. Detects under‑performing inventory.
  2. Generates personalized, SEO‑rich copy using AI.
  3. Delivers the content to customers at the optimal time.

This is the epitome of a “prompt‑driven developer”: instead of writing every line of code, you articulate the problem, let the AI produce the solution, and weave the pieces together with minimal scaffolding.

Next Steps

  • Deploy the FastAPI service to a managed platform (e.g., Fly.io, Render, or AWS Lambda).
  • Secure the endpoints with JWT or OAuth2.
  • Monitor the scheduler and API calls using Prometheus + Grafana.
  • Iterate: add email notifications, A/B test copy variations, or integrate with a CRM.

You are now equipped to take any business process—whether it’s sales, support, or compliance—and automate it end‑to‑end with AI. The next chapter of your journey will be applying these skills to real‑world commercial projects, scaling from a single SaaS product to a portfolio of AI‑powered services.

Good luck, and may your automated marketing machine churn out revenue like a well‑tuned engine!

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!