Build an AI Telegram Bot with n8n, Supabase & OpenAI

This workflow automates Telegram bot conversations using OpenAI and Supabase to remember user sessions, enabling context-aware interactions. It solves the common problem of chatbots lacking memory for seamless user experience.
telegramTrigger
supabase
httpRequest
+3
Learn how to Build this Workflow with AI:
Workflow Identifier: 1211
NODES in Use: Telegram Trigger, Supabase, If, Merge, HTTP Request, Telegram

Press CTRL+F5 if the workflow didn't load.

Visit through Desktop for Best experience

Opening Problem Statement

Meet Mark, a solo entrepreneur managing a customer support Telegram channel for his growing online community. Every day, Mark receives dozens of user messages, but switching between conversations means losing context quickly. Without a memory system, Mark’s bot repeatedly asks users to re-explain issues, wasting time and frustrating users. Mark estimates at least 2 hours lost daily resolving repeated questions, delaying help and lowering user satisfaction.

Mark wants a smarter Telegram bot that remembers previous conversations so users feel heard and supported. He needs a solution that handles multiple user chats asynchronously without losing track of each session’s history. Moreover, Mark wants the bot to use advanced AI assistant capabilities to answer queries intelligently.

What This Automation Does

This custom-built n8n workflow integrates Telegram, OpenAI’s assistant API, and Supabase to create a context-aware AI Telegram bot that remembers users across sessions. Here’s what happens end-to-end when it runs:

  • Captures new Telegram messages from any user via the Telegram Trigger node.
  • Checks Supabase database to see if the user already has an assigned OpenAI conversation thread.
  • If no thread exists, creates a new OpenAI thread for that user and stores the mapping in Supabase.
  • Sends the user’s message as input to the OpenAI assistant in the correct conversation thread.
  • Runs the OpenAI assistant to generate a response based on the entire conversation context.
  • Fetches the assistant’s reply from OpenAI and sends it back to the user on Telegram.

Benefits include maintaining conversation memory across sessions, enabling personalized, coherent conversations. This can save hours daily for customer support teams, improve user engagement, and elevate the chatbot’s usefulness beyond simple scripted answers.

Prerequisites ⚙️

  • n8n account configured with access to Telegram Trigger and Telegram nodes.
  • Telegram bot token created via Botfather 📱
  • Supabase project with a table named telegram_users set up using provided SQL. 📊
  • OpenAI account with API key and an assistant created in the OpenAI platform. 🔐
  • Credentials configured inside n8n for Telegram, Supabase, and OpenAI nodes. 🔑

Step-by-Step Guide

Step 1: Create Your Telegram Bot

Open Telegram and chat with @BotFather. Use the command /newbot to create a new bot. Follow instructions to name it and get a bot token.

Keep your bot token safe; you’ll need it to configure the Telegram nodes in n8n.

Common mistake: Using a bot token from a different or inactive bot.

Step 2: Set Up Supabase and Create User Table

Go to Supabase and start a new project. In the SQL editor, run:

create table
  public.telegram_users (
    id uuid not null default gen_random_uuid (),
    date_created timestamp with time zone not null default (now() at time zone 'utc'::text),
    telegram_id bigint null,
    openai_thread_id text null,
    constraint telegram_users_pkey primary key (id)
  );

This table stores your Telegram users with corresponding OpenAI thread IDs.

Common mistake: Forgetting to set the primary key or default UUID can cause errors.

Step 3: Create an OpenAI Assistant

In the OpenAI platform, create a new assistant (https://platform.openai.com/assistants). Customize its behavior or personality as needed.

Note the assistant ID for use in the workflow.

Common mistake: Not specifying your custom assistant ID in the workflow nodes.

Step 4: Configure n8n Credentials

In n8n, go to Credentials and set up your Telegram API credentials using your bot token.

Set up your Supabase credentials with the URL and anon key from your project settings.

Set up OpenAI credentials with your API key.

Step 5: Set Up the Telegram Trigger Node

Add a Telegram Trigger node named “Get New Message”.

Set it to listen for message updates only, connected to your Telegram bot credentials.

This node acts as the workflow entry point, triggering whenever a user sends a message to your bot.

Step 6: Find or Create User Record in Supabase

Add a Supabase node named “Find User” after the trigger.

Configure it to query the telegram_users table where telegram_id equals {{ $json.message.chat.id }}.

Add an If node named “If User exists” to check if the query returned a record.

If the user doesn’t exist, an HTTP Request node creates a new OpenAI thread, and another Supabase node “Create User” inserts a new record with telegram_id and openai_thread_id.

Step 7: Merge User Data

A Merge node combines the newly created or found user data for further processing.

Step 8: Send Message to OpenAI Assistant

An HTTP Request node “OPENAI – Send message” posts the user’s Telegram message text as the content to the user’s OpenAI thread.

Use the OpenAI API endpoint https://api.openai.com/v1/threads/{{ thread_id }}/messages with headers including OpenAI-Beta: assistants=v2.

Step 9: Run the OpenAI Assistant

A following HTTP Request node “OPENAI – Run assistant” posts to https://api.openai.com/v1/threads/{{ thread_id }}/runs to start processing the message.

Include body parameters like assistant_id and stream: true.

Step 10: Retrieve Assistant Response

Next, “OPENAI – Get messages” HTTP node fetches the latest messages from the thread.

Step 11: Send Response Back to Telegram User

Finally, a Telegram node “Send Message to User” sends the assistant’s reply text back to the user’s chat on Telegram.

Customizations ✏️

  • Change Assistant Personality: Update the assistant profile on OpenAI’s assistant platform and update the assistant_id in the “OPENAI – Run assistant” HTTP Request node.
  • Add Message Filtering: Add conditions in the Telegram Trigger node or in n8n to filter only specific commands or keywords before forwarding to OpenAI.
  • Store Additional User Data: Extend the Supabase user table schema to include usernames or preferences, then update the “Create User” node to store these fields.
  • Add Logging: Insert Slack or email notification nodes to get alerts for failed API requests or other workflow errors.

Troubleshooting 🔧

Problem: “No user found or multiple users returned” from Supabase query

Cause: Incorrect query key or multiple records for one Telegram ID.

Solution: Ensure the telegram_id is unique in Supabase and the query condition eq filter matches exactly {{ $json.message.chat.id }}.

Problem: “OpenAI API authentication failed”

Cause: Wrong or expired API key.

Solution: Verify your API keys in n8n credentials and update them if necessary.

Problem: “Telegram message not sent”

Cause: Incorrect chat ID or Telegram bot not authorized.

Solution: Confirm the chat ID passed to the Telegram node matches the message’s sender ID and your bot is active.

Pre-Production Checklist ✅

  • Verify Telegram bot token works by testing with direct messages.
  • Confirm Supabase table schema matches the expected fields: telegram_id, openai_thread_id.
  • Test OpenAI assistant ID and API key are valid and responding to test queries.
  • Run the workflow manually with test Telegram messages and check logs for errors.

Deployment Guide

Activate your workflow in n8n by switching it from inactive to active.

Monitor the execution logs for errors especially when forwarding messages or when new threads are created.

Consider setting an alert node (e.g., email or Slack integration) for failures if scaling to many users.

FAQs

Can I use other databases instead of Supabase?

Yes, but this workflow specifically integrates Supabase for easy real-time data handling and API support. Using a different database requires node and query adjustments.

Does this consume OpenAI API credits?

Yes, every message sent and assistant run consumes OpenAI tokens billed according to your subscription.

Is the Telegram chat data secure?

Data is stored only in your Supabase project and processed by OpenAI under your API keys. Ensure you protect your keys and project access.

What if multiple users message simultaneously?

This workflow handles each Telegram message independently, creating or fetching user threads from Supabase to keep sessions isolated and context-aware.

Conclusion

By following this tutorial, you’ve built a powerful AI-powered Telegram bot using n8n, Supabase, and OpenAI. Your bot now maintains conversation history for each user, delivering rich, relevant responses that adapt over time.

This saves Mark and others countless hours managing ongoing chats and greatly improves user experience by providing continuity and context.

Next, consider adding features like multi-language support, voice message processing, or integrating this bot with other messaging platforms.

With this solid foundation, you’re ready to build more advanced, personalized automation workflows for your community or business needs.

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation in n8n (Beginner Guide)

A complete beginner guide to building an AI-powered SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free