Witty AI Telegram Bot with OpenRouter and User Analytics - n8n Workflow

Deploy an advanced n8n workflow for Telegram. Create a witty AI bot using OpenRouter, offering jokes, roasts, scheduled posts, and managing user statistics in a Postgres database. Use these comprehensive n8n templates.

Workflow Preview

Ready to automate?

Download this n8n workflow template and start using it instantly.

Who is this best for?

Community Managers needing an engaging, autonomous bot for their Telegram group.
Developers looking for advanced n8n templates integrating Langchain AI Agents and custom database logic.
Automation Specialists wanting to deploy a fun, production-ready AI solution using n8n.
Users seeking a complete n8n workflow example for chat automation, analytics, and scheduling.

Overview

Building an engaging chat bot requires more than simple keyword responses—it needs persistence, context, and intelligence. This advanced n8n workflow solves this by merging real-time communication (Telegram) with the flexible, low-latency AI models available through OpenRouter, backed by a robust Postgres database (ideal for Supabase).

This workflow manages user authentication, conversation history, activity logging, and scheduling, making it a professional, ready-to-deploy solution. Every interaction is recorded, providing data for /stats and /top leaderboards. The core intelligence relies on specialized AI nodes, ensuring the bot's tone—witty, slightly ironic, and concise—is consistent across all commands and mentions. This specific n8n workflow demonstrates how to handle complex routing, database interactions, and specialized AI formatting requirements efficiently within the n8n environment.

How it Works

This automation operates primarily on two parallel paths, starting with distinct n8n trigger nodes.

1. User Interaction Flow (Telegram Trigger)


  1. Trigger: The Webhook Telegram n8n trigger captures all incoming messages, commands, or mentions.

  2. Logging: The Log message + statistics Postgres n8n node instantly stores the message and updates the user's message count and last activity timestamp in the user_stats table.

  3. Routing: A Switch n8n node inspects the message text to determine if it is an AI command (/joke, /roast), an info command (/stats, /top, /help), or a direct mention (@GiggleGPTBot).

  4. Context Retrieval: For AI interactions, the Chat history Postgres n8n node fetches the last 15 messages to provide relevant context to the AI model.

  5. Data Preparation: The Mention Analysis Code n8n node parses the command type, user metadata, current time context, and conversation history.

  6. Information Commands: If an info command is detected, the workflow retrieves specific data using Postgres (e.g., Get user statistics, Get top users). The Generating an information response Code n8n node formats this data into a human-readable reply. A Log command Postgres n8n node increments the command count.

  7. AI Generation: If an AI command or mention is detected, the workflow branches to either AI response to command or AI response to mention. Both Langchain Agent n8n nodes use OpenRouter to generate the witty, concise reply based on strict system prompts.

  8. Delivery & Persistence: The resulting text is saved via the Save Bot Response Postgres n8n node and then sent back to the user using a Telegram Send n8n node.

2. Scheduled Content Flow (Schedule Trigger)


  1. Trigger: The Schedule n8n trigger runs every hour (using a cron expression).

  2. Lookup: The Get scheduled posts Postgres n8n node queries the database for posts scheduled for the current hour.

  3. Content Generation: If a scheduled post is found, the AI post generation Langchain Agent n8n node uses OpenRouter to create the appropriate content (e.g., a morning joke or daily motivation).

  4. Posting: The content is logged by Save Bot Response2 and immediately delivered to the target Telegram chat via the Submit scheduled post Telegram n8n node.

Installation Guide

To utilize this complex n8n workflow template, follow these steps:


  1. Import the n8n Workflow: Copy the provided JSON data and paste it into your n8n instance using the 'New' menu -> 'Import from JSON'.

  2. Configure Credentials: You will need to set up three primary credentials:

Telegram API: Create a bot via BotFather and use the token to configure the Telegram API credentials in n8n.
Postgres: Set up credentials pointing to your PostgreSQL database (e.g., Supabase, RDS). This database is essential for stats and logging.
* OpenRouter API: Obtain an API key from OpenRouter and configure the credentials in n8n. This key powers the AI generation nodes.

  1. Initialize Database: Locate the Init Database n8n node and execute it manually once. This creates all necessary tables (usermessages, userstats, botresponses, etc.).

  2. Seed Schedule (Optional): If you wish to use the scheduled posting feature, execute the Adding a schedule n8n node once to insert initial cron entries for morning jokes and daily motivations. Remember to adjust the chatid parameter within the SQL query to match your specific Telegram group ID.

  3. Activate: Set the Webhook Telegram n8n trigger to active and ensure the webhook connection is established with Telegram. Activate the Schedule n8n trigger for automated posts. Your comprehensive n8n workflow is now ready.

Node Details

Webhook Telegram (n8n trigger): The main entry point. It receives all messages and commands sent to the bot in the Telegram chat.
Schedule (n8n trigger): A cron-based n8n trigger that executes hourly (0 ) to check for time-sensitive scheduled posts.
Postgres (Init Database): Executes complex SQL to create all required database tables for message logging, command tracking, user statistics, and scheduled posts. Essential for the function of this n8n workflow.
Postgres (Log message + statistics): Inserts every incoming user message and updates the messagescount in the userstats table using an ON CONFLICT clause for atomic updates.
Langchain Agent (AI response to command / mention / post generation): These are the core AI processing n8n node instances. They use the OpenRouter credential to access high-quality models (specified as openai/gpt-oss-120b in one instance) and adhere to strict system prompts for witty, concise output (1-2 sentences) tailored to specific commands (/joke, /roast, etc.).
Code (Mention Analysis): A custom n8n node that performs complex pre-processing, fetching chat history from Postgres, parsing commands, setting content type, and preparing the payload for the AI model.
Postgres (Chat history): Retrieves the last 15 user and bot messages from the database, aggregating them to provide conversational context for the AI agents.
Switch: Routes the incoming message to the correct processing path (AI response vs. Information response) based on the specific command found in the Telegram message. This efficient n8n node controls the flow.


  • Telegram (Send AI response / Reply to Mention / Send info reply): Final delivery n8n nodes that send the generated or retrieved text back to the relevant Telegram chat or channel.

Related n8n Workflows

Free

Nodes: 10 Nodes
Updated: December 26 2025
View all
Created by
Sergey Skorobogatov
Sergey Skorobogatov

Featured*