Build an AI Telegram Bot with OpenAI & Supabase Memory

Automate Telegram conversations with this workflow using OpenAI for responses and Supabase for user memory, solving the problem of chatbots lacking context. Maintain continuity across chats and deliver more natural, engaging interactions.
telegramTrigger
httpRequest
supabase
+4
Workflow Identifier: 1921
NODES in Use: Telegram Trigger, HTTP Request, Supabase, Merge, If, Telegram, Sticky Note

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

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

1. Opening Problem Statement

Meet Mark, a busy community manager running multiple Telegram groups where users frequently ask complex, varied questions. Mark wastes hours daily answering repetitive queries and struggles to maintain context over multiple chats. His current chatbot solutions often fail to remember previous conversations, leading to frustrating user experiences and lost engagement.

Without memory, the chatbot treats each message statelessly, causing users to repeat themselves or receive generic answers. This not only wastes Mark’s time but also impacts the community’s satisfaction and retention.

This workflow solves Mark’s specific challenge: creating a Telegram AI chatbot that remembers past conversations, maintaining context over time by saving user sessions and chat threads in a Supabase database.

2. What This Automation Does

This automated Telegram AI bot workflow using n8n connects Telegram, OpenAI, and Supabase to achieve a smarter, context-aware chatbot. Here’s what happens when the workflow runs:

  • Detects incoming Telegram messages from users via the Telegram Trigger node.
  • Looks up user session data in Supabase to check if the user has an existing OpenAI chat thread.
  • Creates a new OpenAI thread if the user is new, storing the thread ID in Supabase for persistent memory.
  • Sends user messages to the correct OpenAI thread for contextually relevant AI responses.
  • Executes the OpenAI assistant to generate an answer based on the conversation history.
  • Retrieves the AI’s reply and sends it back as a Telegram message, seamlessly continuing the conversation.

With this, Mark saves hours every day, improves user satisfaction, and turns simple Telegram chats into engaging AI-powered conversations retaining context over time.

3. Prerequisites ⚙️

  • n8n account (cloud or self-hosted) 🔌
  • Telegram Bot (created via Botfather) 📱
  • OpenAI API key with Assistant access 🔑
  • Supabase project with a database table to store user sessions 📊
  • Configured credentials in n8n for Telegram, OpenAI, and Supabase 🔐

4. Step-by-Step Guide

Step 1: Create Your Telegram Bot

Open Telegram and start a chat with Botfather. Use the /newbot command to make your bot and get its API token. Copy this token; you will need it to connect n8n to Telegram.

You should see a message confirming bot creation with your bot’s username.

Common mistake: Not copying the token fully or pasting incorrectly in n8n credentials.

Step 2: Set Up Supabase Database

Sign up at Supabase and create a new project.

Access the SQL editor and run this SQL to create the telegram_users table:

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)
 ) tablespace pg_default;

After running, note your SUPABASE_URL and SUPABASE_KEY to configure n8n credentials.

Common mistake: Forgetting to grant read/write permissions to this table for your API key.

Step 3: Create OpenAI Assistant

Go to OpenAI Assistants and create a new assistant.

Customize the assistant personality as needed. Copy its assistant ID; you’ll use this in the “OPENAI – Run assistant” node.

Common mistake: Not specifying the assistant ID in n8n or using a wrong assistant type.

Step 4: Configure Credentials in n8n

Go to Credentials in n8n. Add:

  • Telegram API credentials with your bot token 📱
  • Supabase credentials with your project URL and API key 📊
  • OpenAI API key with necessary permission for assistant access 🔑

Common mistake: Mismatched API keys or expired credentials causing authentication failures.

Step 5: Set Up Telegram Trigger Node

Drag in the Telegram Trigger node titled “Get New Message.”

Configure it to listen to “message” updates.

Link it to your Telegram API credentials.

You should see the webhook URL generated and active after activation.

Step 6: Find User in Supabase

Add the Supabase node named “Find User.”

Configure it to query the “telegram_users” table filtering where telegram_id equals the incoming message chat id:

{
  "filters": {
    "conditions": [{
      "keyName": "telegram_id",
      "keyValue": "={{ $json.message.chat.id }}",
      "condition": "eq"
    }]
  },
  "tableId": "telegram_users",
  "operation": "getAll"
}

Ensure it uses your Supabase credentials.

Common mistake: Wrong filter setup causing empty or incorrect results.

Step 7: Condition Check If User Exists

Drag the If node called “If User exists” connected to the Find User node.

Set the condition to check if $json.id exists. This tells if the database returned any user matching the telegram_id.

If true (user exists), proceed to merge and continue conversation. If false, create a new OpenAI thread.

Common mistake: Using incorrect json path in condition, causing wrong branching.

Step 8: Create OpenAI Chat Thread for New Users

Add the HTTP Request node “OPENAI – Create thread.”

Configure it as a POST request to https://api.openai.com/v1/threads, with header OpenAI-Beta: assistants=v2 and your OpenAI credentials.

This sets up a new conversation thread to maintain context.

Common mistake: Forgetting to send proper headers or payload format.

Step 9: Store New User with Thread ID in Supabase

Use the Supabase node named “Create User.”

Map telegram_id to the incoming message chat id and openai_thread_id to the newly created thread’s ID.

This saves the relationship for future conversations.

Step 10: Merge User Data

Add the Merge node.

Combine outputs from the “If User exists” node (true) and “Create User” node (false) so the conversation continues regardless.

This node ensures unified data for the next steps.

Step 11: Send User Message to the Right OpenAI Thread

Add an HTTP Request node “OPENAI – Send message.”

Configure it as POST to https://api.openai.com/v1/threads/{{thread_id}}/messages, sending JSON body with role: user and content as the incoming Telegram message text.

Use dynamic expressions to replace {{thread_id}} with the correct thread from merged data.

Step 12: Run OpenAI Assistant

Add another HTTP Request node “OPENAI – Run assistant.”

Make a POST call to https://api.openai.com/v1/threads/{{thread_id}}/runs with assistant_id parameter referencing your OpenAI assistant ID.

This runs the AI to generate a response based on all chat history.

Step 13: Fetch Assistant Messages

Add a final HTTP Request node “OPENAI – Get messages.”

GET from https://api.openai.com/v1/threads/{{thread_id}}/messages to pull the assistant’s latest reply.

Step 14: Send Response Back via Telegram

Add the Telegram node “Send Message to User.”

Send a message using the first content text from the assistant’s response JSON, targeting the original user’s chat ID.

Success! Your Telegram AI bot now listens, remembers, and replies with human-like context.

5. Customizations ✏️

  • Change Assistant Personality: In the “OPENAI – Run assistant” node, change the assistant_id to use a different OpenAI assistant tailored for your use case.
  • Add User Name in Replies: Modify the “Send Message to User” node’s message text to include the Telegram user’s first name using {{$json.message.chat.first_name}}.
  • Store Additional User Data: Extend the “Create User” Supabase node fields to save user info like username or language for personalized interactions.
  • Support Group Chats: Adjust the Telegram Trigger to handle messages from group chats by changing the update types and filtering chat types.

6. Troubleshooting 🔧

Problem: Telegram messages not triggering workflow

Cause: Webhook URL not activated or not correctly set in Telegram Bot settings.

Solution: Go to Telegram Trigger node, copy the webhook URL, and set it as your bot’s webhook via Botfather or Telegram API. Ensure webhook is reachable.

Problem: OpenAI API returns unauthorized or errors

Cause: Incorrect API key or missing required headers.

Solution: Verify your OpenAI credentials in n8n. Confirm header OpenAI-Beta: assistants=v2 is present. Regenerate API keys if needed.

Problem: Supabase queries return empty or no data

Cause: Filters misconfigured or Supabase table permissions are restrictive.

Solution: Check the filter condition in the “Find User” Supabase node matches the incoming telegram_id. Confirm the API key has correct read/write permissions.

7. Pre-Production Checklist ✅

  • Verify Telegram Bot webhook is active and reachable.
  • Ensure Supabase table telegram_users is created with correct schema.
  • Test OpenAI API calls with your assistant ID separately in Postman or n8n.
  • Run sample Telegram messages and verify user creation/lookup in Supabase.
  • Inspect n8n execution logs for errors or unexpected behaviors during runs.

8. Deployment Guide

Activate your workflow in n8n by toggling it ON.

Keep monitoring executions initially to ensure messages trigger the flow correctly.

Use n8n’s built-in logging and execution history to troubleshoot issues.

9. FAQs

Can I use another database instead of Supabase?

Yes, but you’ll need to replace the Supabase nodes with appropriate database nodes and update queries accordingly.

Does this consume many OpenAI API credits?

Each conversation thread run and message consumes tokens. Keeping threads context-aware may increase the token use per conversation.

Is the user data safe in this setup?

Supabase stores the user IDs and thread IDs securely, but you should ensure API keys and database credentials are kept private and secure.

10. Conclusion

Congratulations! You’ve built a Telegram AI chatbot that remembers your users and keeps engaging conversations using OpenAI and Supabase in n8n.

This workflow saves you hours on customer interactions, improves experience, and delivers personalized, context-rich answers without manual intervention.

Next steps: add more advanced assistant personalities, integrate other messaging platforms, or expand user data stored for richer personalization.

Keep experimenting and enjoy your smart Telegram AI bot!

Promoted by BULDRR AI

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

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