Automating Event Flyers from Google Calendar to Telegram

Share
Automating Event Flyers from Google Calendar to Telegram

When a volunteer organization runs weekly public events across dozens of cities, producing consistent promotional flyers quickly becomes a repetitive bottleneck. This project automates the entire workflow: local coordinators simply add or update an event in a shared Google Calendar, and a background service generates a standardized 1080×1350px flyer and publishes it directly to the organization's Telegram group. It eliminates manual graphic editing while keeping every chapter's visuals, schedules, and updates in sync.


The Problem

Non-profit and grassroots organizations—such as animal rights or environmental advocacy groups—often coordinate dozens of local chapters from a single shared calendar. Creating flyers manually for every event introduces recurring operational issues:

  • Repetitive manual work: Every week, someone has to copy the city, street address, date, and time into a design tool, swap in the local chapter's photos, export the image, and upload it to chat channels.
  • Dependency on specific volunteers: If only a few people have access to the design templates or software, publishing stalls whenever they are unavailable.
  • Error-prone updates: When an event's meeting point or time changes a few days before it takes place, an updated flyer has to be manually recreated, reposted, and the old message deleted to avoid confusing volunteers.
  • Inconsistent formatting: Different people abbreviate street names differently, use inconsistent date/time formats across languages, or break the layout when a city or street name is unusually long.

The goal was to let coordinators use a single source of truth—the shared Google Calendar they were already maintaining—and remove manual graphic production from the weekly routine.


How the Workflow Works

From a non-technical coordinator's perspective, there is no separate dashboard to learn. Everything happens through Google Calendar and Telegram:

  1. Add or edit the event in Google Calendar
    A coordinator creates an event in the shared calendar with the chapter name in the title, the meeting location in the address field, the start/end time, and optionally a Facebook event URL in the description. If an event does not need a flyer, adding a simple skip keyword in the description excludes it automatically.
  2. Automatic sync (or on-demand check)
    Every 30 minutes (configurable via cron), the service reads upcoming events for the configured lookahead window. Authorized coordinators can also trigger an immediate sync directly from Telegram using /check.
  3. Flyer generation and Telegram publication
    For each new event, the service extracts and cleans the city and street address, combines the organization's base template with the local chapter's stored photos, renders the localized text, and posts the finished PNG to the target Telegram group or forum topic—automatically tagging the chapter's organizers and attaching the Facebook link if present.
  4. Automatic handling of changes
    If a coordinator later edits the date, time, location, or link on Google Calendar, the service detects the difference, regenerates the flyer, removes the outdated Telegram post when permitted, and publishes the updated version. Authorized admins can also manage chapter photos, organizers, language preferences, and city-to-chapter mappings directly via Telegram bot commands.

Architecture and Technical Choices

The application is a single-process Node.js 20 service written in strict TypeScript. Keeping the architecture compact—an embedded database, local filesystem storage for static assets, and a single PM2-managed process—keeps hosting costs low and maintenance predictable for a volunteer-run deployment.

Tech Stack

  • Runtime & Language: Node.js 20 (v20.19.4 via .nvmrc), TypeScript (strict: true).
  • Calendar Integration: googleapis (Google Calendar API v3) authenticated via OAuth2 with a read-only scope (calendar.readonly) and a refresh token.
  • Bot & Admin Interface: telegraf (Telegram Bot API), supporting supergroup forum topics (message_thread_id) and numeric Telegram user ID allowlists for administrative commands.
  • Persistence: better-sqlite3 with synchronous queries and an internal versioned schema migration system (currently at schema version 7).
  • Image Pipeline: sharp for high-speed resizing, cropping, and layer compositing, combined with canvas (node-canvas) for custom-font typography and vector graphics.
  • Scheduling & Localization: node-cron for calendar polling and biweekly statistics reports; date-fns and date-fns-tz for timezone-aware formatting across Italian (it), English (en), and German (de).
  • Geocoding: OpenStreetMap Nominatim via node-fetch, backed by a disk-persisted JSON cache.
  • Tooling & Testing: commander for a local CLI (generate command to preview flyers without running the bot) and jest + ts-jest across six test suites covering address parsing, calendar utilities, database migrations, stats generation, internal API endpoints, and historical regression cases.

Server-Side Flyer Generation

Each flyer is a 1080×1350px PNG assembled in memory without shelling out to headless browsers:

  1. Chapter photo preparation: When an admin uploads a 1080×1350px reference image through the bot (/upload_images), sharp validates the dimensions and automatically crops out the two right-hand photo slots (568×843px top, 568×507px bottom), saving them to disk and indexing the paths in SQLite.
  2. Base compositing: During generation, sharp resizes the base template and composites the chapter's two photos into fixed coordinates.
  3. Typography overlay: node-canvas creates a transparent 1080×1350px layer with custom registered fonts (Blocklyn Grunge, Blocklyn Condensed, and Libre Baskerville). To prevent overflow on real-world inputs:
    • City names longer than 15 characters with multiple words are automatically split across two lines at the space closest to the midpoint.
    • Street addresses longer than 25 characters (or containing parenthetical notes) are wrapped onto multiple lines using a | delimiter.
    • A measurement loop (getFitFontSize) iteratively shrinks the font size until the widest line fits inside the text column with horizontal margins.
    • Dates and time ranges adapt to the chapter's configured language (24-hour format for it/de, 12-hour AM/PM for en).
  4. Final merge: sharp composites the transparent text buffer onto the base image and returns a Buffer ready to stream to Telegram.

The same node-canvas stack also renders a biweekly 1080×1350px statistics graphic showing year-to-date and quarterly city/chapter leaderboards alongside a six-month bar chart, triggered either on schedule or on demand via /stats.

Handling Updates and Production Edge Cases

Most of the engineering complexity lives in dealing with messy real-world inputs and third-party API constraints:

  • Messy addresses and geocoding mismatches: Google Calendar autocomplete strings frequently contain Italian abbreviations (P.zza, V.le, S.), duplicated street names, written-out ordinals, or streets that share a name with a neighboring town in the same province. Before calling Nominatim, the address pipeline expands abbreviations, strips duplicate segments, and normalizes ordinals. Requests are throttled to 1 request/second to respect Nominatim's usage policy and cached to disk (data/geocoding-cache.json). Because Nominatim's top result can occasionally match an identical house number in a nearby town within the same province, the service fetches up to 10 results and filters them against the city and postal code extracted locally from the original string, preserving the organizer's stated house number and falling back to local regex parsing if the external API times out or returns no valid match.
  • Flexible chapter routing: Some local teams organize events in nearby cities that do not have their own chapter. An explicit city_group_mappings table in SQLite lets admins map a city name to a chapter, and the title parser prioritizes explicit mappings and longer/more specific group names (e.g., preventing a shorter city name from shadowing a wider regional chapter name).
  • Telegram's 48-hour message deletion limit: Every published event is stored in SQLite (processed_events) with its telegram_message_id. On subsequent runs, field-level change detection compares city, address, date, start/end time, and Facebook link. When an event changes, the bot attempts to delete the previous Telegram message before publishing the new one. If Telegram rejects the deletion because the message is older than 48 hours (message can't be deleted), the service flags the event in SQLite (deletion_failed, old_message_id) and sends a single structured alert—including a direct link to the stale message—to an admin channel. Before each sync cycle, a reconciliation job checks flagged messages and clears the flag automatically once an admin has removed the old post.
  • Operational visibility and internal integration: Runtime errors are forwarded by an ErrorLogger singleton to a dedicated Telegram chat/topic with truncated event metadata and stack traces. In addition, an optional loopback-only (127.0.0.1) Node HTTP endpoint (/api/internal/groups) protected by constant-time Bearer token comparison (crypto.timingSafeEqual) exposes active chapter metadata and organizer lists to other internal tools on the same host without opening extra public ports.

Deployment and CI/CD

Deployment is automated through a GitHub Actions workflow triggered on pushes to main (and manually via workflow_dispatch):

  1. Test and build in CI: On ubuntu-latest with Node.js 20, the pipeline installs dependencies, runs the full Jest test suite under TZ=Europe/Rome, and compiles TypeScript to dist/.
  2. Artifact transfer: Compiled output in dist/ is copied via SCP to a DigitalOcean VPS.
  3. Server update and secret injection: Over SSH, the workflow resets the working tree, pulls the latest commit, writes .env from GitHub Secrets and repository variables, activates the pinned Node version via NVM (.nvmrc), installs production dependencies (npm install --production), and runs npm rebuild so native C++ addons (better-sqlite3, sharp, canvas) match the target server runtime.
  4. Process reload: PM2 reloads the application (pm2 reload) and reports process status.

Get in Touch

If you are looking for a Senior Full-Stack or Mobile Engineer who enjoys taking systems from requirements to reliable production deployments—or if you coordinate a non-profit or advocacy organization and would like to explore volunteer technical collaboration to automate repetitive workflows—feel free to connect with me on LinkedIn:

linkedin.com/in/mircocipriani