Back to Catalog

Create a Telegram bot with Mistral Nemotron AI and conversation memory

Ajith joseph Ajith joseph
818 views
2/3/2026
Official Page

πŸ€– Create a Telegram Bot with Mistral AI and Conversation Memory

A sophisticated Telegram bot that provides AI-powered responses with conversation memory. This template demonstrates how to integrate any AI API service with Telegram, making it easy to swap between different AI providers like OpenAI, Anthropic, Google AI, or any other API-based AI model.

πŸ”§ How it works

The workflow creates an intelligent Telegram bot that:

  • πŸ’¬ Maintains conversation history for each user
  • 🧠 Provides contextual AI responses using any AI API service
  • πŸ“± Handles different message types and commands
  • πŸ”„ Manages chat sessions with clear functionality
  • πŸ”Œ Easily adaptable to any AI provider (OpenAI, Anthropic, Google AI, etc.)

βš™οΈ Set up steps

πŸ“‹ Prerequisites

  • πŸ€– Telegram Bot Token (from @BotFather)
  • πŸ”‘ AI API Key (from any AI service provider)
  • πŸš€ n8n instance with webhook capability

πŸ› οΈ Configuration Steps

  1. πŸ€– Create Telegram Bot

    • Message @BotFather on Telegram
    • Create new bot with /newbot command
    • Save the bot token for credentials setup
  2. 🧠 Choose Your AI Provider

    • OpenAI: Get API key from OpenAI platform
    • Anthropic: Sign up for Claude API access
    • Google AI: Get Gemini API key
    • NVIDIA: Access LLaMA models
    • Hugging Face: Use inference API
    • Any other AI API service
  3. πŸ” Set up Credentials in n8n

    • Add Telegram API credentials with your bot token
    • Add Bearer Auth/API Key credentials for your chosen AI service
    • Test both connections
  4. πŸš€ Deploy Workflow

    • Import the workflow JSON
    • Customize the AI API call (see customization section)
    • Activate the workflow
    • Set webhook URL in Telegram bot settings

✨ Features

πŸš€ Core Functionality

  • πŸ“¨ Smart Message Routing: Automatically categorizes incoming messages (commands, text, non-text)
  • 🧠 Conversation Memory: Maintains chat history for each user (last 10 messages)
  • πŸ€– AI-Powered Responses: Integrates with any AI API service for intelligent replies
  • ⚑ Command Support: Built-in /start and /clear commands

πŸ“± Message Types Handled

  • πŸ’¬ Text Messages: Processed through AI model with context
  • πŸ”§ Commands: Special handling for bot commands
  • ❌ Non-text Messages: Polite error message for unsupported content

πŸ’Ύ Memory Management

  • πŸ‘€ User-specific chat history storage
  • πŸ”„ Automatic history trimming (keeps last 10 messages)
  • 🌐 Global state management across workflow executions

πŸ€– Bot Commands

  • /start 🎯 - Welcome message with bot introduction
  • /clear πŸ—‘οΈ - Clears conversation history for fresh start
  • Regular text πŸ’¬ - Processed by AI with conversation context

πŸ”§ Technical Details

πŸ—οΈ Workflow Structure

  1. πŸ“‘ Telegram Trigger - Receives all incoming messages
  2. πŸ”€ Message Filtering - Routes messages based on type/content
  3. πŸ’Ύ History Management - Maintains conversation context
  4. 🧠 AI Processing - Generates intelligent responses
  5. πŸ“€ Response Delivery - Sends formatted replies back to user

πŸ€– AI API Integration (Customizable)

Current Example (NVIDIA):

  • Model: mistralai/mistral-nemotron
  • Temperature: 0.6 (balanced creativity)
  • Max tokens: 4096
  • Response limit: Under 200 words

πŸ”„ Easy to Replace with Any AI Service:

OpenAI Example:

{
  "model": "gpt-4",
  "messages": [...],
  "temperature": 0.7,
  "max_tokens": 1000
}

Anthropic Claude Example:

{
  "model": "claude-3-sonnet-20240229",
  "messages": [...],
  "max_tokens": 1000
}

Google Gemini Example:

{
  "contents": [...],
  "generationConfig": {
    "temperature": 0.7,
    "maxOutputTokens": 1000
  }
}

πŸ›‘οΈ Error Handling

  • ❌ Non-text message detection and appropriate responses
  • πŸ”§ API failure handling
  • ⚠️ Invalid command processing

🎨 Customization Options

πŸ€– AI Provider Switching

To use a different AI service, modify the "NVIDIA LLaMA Chat Model" node:

  1. πŸ“ Change the URL in HTTP Request node
  2. πŸ”§ Update the request body format in "Prepare API Request" node
  3. πŸ” Update authentication method if needed
  4. πŸ“Š Adjust response parsing in "Save AI Response to History" node

🧠 AI Behavior

  • πŸ“ Modify system prompt in "Prepare API Request" node
  • 🌑️ Adjust temperature and response parameters
  • πŸ“ Change response length limits
  • 🎯 Customize model-specific parameters

πŸ’Ύ Memory Settings

  • πŸ“Š Adjust history length (currently 10 messages)
  • πŸ‘€ Modify user identification logic
  • πŸ—„οΈ Customize data persistence approach

🎭 Bot Personality

  • πŸŽ‰ Update welcome message content
  • ⚠️ Customize error messages and responses
  • βž• Add new command handlers

πŸ’‘ Use Cases

  • 🎧 Customer Support: Automated first-line support with context awareness
  • πŸ“š Educational Assistant: Homework help and learning support
  • πŸ‘₯ Personal AI Companion: General conversation and assistance
  • πŸ’Ό Business Assistant: FAQ handling and information retrieval
  • πŸ”¬ AI API Testing: Perfect template for testing different AI services
  • πŸš€ Prototype Development: Quick AI chatbot prototyping

πŸ“ Notes

  • 🌐 Requires active n8n instance for webhook handling
  • πŸ’° AI API usage may have rate limits and costs (varies by provider)
  • πŸ’Ύ Bot memory persists across workflow restarts
  • πŸ‘₯ Supports multiple concurrent users with separate histories
  • πŸ”„ Template is provider-agnostic - easily switch between AI services
  • πŸ› οΈ Perfect starting point for any AI-powered Telegram bot project

πŸ”§ Popular AI Services You Can Use

| Provider | Model Examples | API Endpoint Style | |----------|---------------|-------------------| | 🟒 OpenAI | GPT-4, GPT-3.5 | https://api.openai.com/v1/chat/completions | | πŸ”΅ Anthropic | Claude 3 Opus, Sonnet | https://api.anthropic.com/v1/messages | | πŸ”΄ Google | Gemini Pro, Gemini Flash | https://generativelanguage.googleapis.com/v1beta/models/ | | 🟑 NVIDIA | LLaMA, Mistral | https://integrate.api.nvidia.com/v1/chat/completions | | 🟠 Hugging Face | Various OSS models | https://api-inference.huggingface.co/models/ | | 🟣 Cohere | Command, Generate | https://api.cohere.ai/v1/generate |

Simply replace the HTTP Request node configuration to switch providers!

Telegram Bot with AI Conversation Memory

This n8n workflow creates an interactive Telegram bot that leverages AI models (Mistral, Nemotron) for generating responses and maintains conversation memory for more coherent interactions.

What it does

This workflow automates the following steps:

  1. Listens for Telegram Messages: It acts as a Telegram bot, waiting for any incoming messages from users.
  2. Initial Message Check: It checks if the incoming message is a new conversation starter or a continuation of an existing one.
  3. Manages Conversation History (Code Node):
    • If it's a new conversation, it initializes a new chat history.
    • If it's an ongoing conversation, it retrieves the previous messages to provide context to the AI.
    • It appends the new user message to the conversation history.
  4. Generates AI Response (HTTP Request): It sends the conversation history to an AI model (Mistral or Nemotron, based on the HTTP Request node configuration) via an API call to generate a relevant response.
  5. Updates Conversation History (Code Node): It appends the AI's generated response to the conversation history.
  6. Sends Response to Telegram: It sends the AI's response back to the user in Telegram.

Prerequisites/Requirements

  • n8n Instance: A running n8n instance.
  • Telegram Bot Token: A Telegram Bot Token from BotFather.
  • AI API Endpoint: An API endpoint for an AI model (e.g., Mistral, Nemotron) that accepts a conversation history and returns a generated response. This will likely require an API key or other authentication.
  • AI API Key/Credentials: Necessary authentication details for your chosen AI API.

Setup/Usage

  1. Import the Workflow:
    • Copy the provided JSON code.
    • In your n8n instance, click "New" to create a new workflow.
    • Go to the "Import" menu (usually a clipboard icon or "File" > "Import from JSON") and paste the JSON.
  2. Configure Telegram Trigger:
    • Click on the "Telegram Trigger" node.
    • Select or create a new Telegram API credential using your Telegram Bot Token.
    • Save the workflow.
  3. Configure HTTP Request Node:
    • Click on the "HTTP Request" node.
    • Update the "URL" field to point to your AI model's API endpoint.
    • Configure the "Authentication" section with your AI API Key or other required credentials.
    • Adjust the "Body Parameters" to match the expected input format of your AI model, ensuring it sends the conversation history correctly (e.g., {{ JSON.stringify($json.messages) }}).
  4. Configure Telegram Node:
    • Click on the "Telegram" node.
    • Select the same Telegram API credential used in the "Telegram Trigger" node.
    • Ensure the "Chat ID" is correctly mapped to the incoming chat ID from the trigger (e.g., {{ $json.chat.id }}).
    • Ensure the "Text" field is mapped to the AI's response from the "HTTP Request" node (e.g., {{ $json.response }}).
  5. Activate the Workflow:
    • Save the workflow.
    • Toggle the workflow to "Active" in the top right corner.

Your Telegram bot is now ready to interact! Send a message to your bot on Telegram to start a conversation.

Related Templates

Track competitor SEO keywords with Decodo + GPT-4.1-mini + Google Sheets

This workflow automates competitor keyword research using OpenAI LLM and Decodo for intelligent web scraping. Who this is for SEO specialists, content strategists, and growth marketers who want to automate keyword research and competitive intelligence. Marketing analysts managing multiple clients or websites who need consistent SEO tracking without manual data pulls. Agencies or automation engineers using Google Sheets as an SEO data dashboard for keyword monitoring and reporting. What problem this workflow solves Tracking competitor keywords manually is slow and inconsistent. Most SEO tools provide limited API access or lack contextual keyword analysis. This workflow solves that by: Automatically scraping any competitor’s webpage with Decodo. Using OpenAI GPT-4.1-mini to interpret keyword intent, density, and semantic focus. Storing structured keyword insights directly in Google Sheets for ongoing tracking and trend analysis. What this workflow does Trigger β€” Manually start the workflow or schedule it to run periodically. Input Setup β€” Define the website URL and target country (e.g., https://dev.to, france). Data Scraping (Decodo) β€” Fetch competitor web content and metadata. Keyword Analysis (OpenAI GPT-4.1-mini) Extract primary and secondary keywords. Identify focus topics and semantic entities. Generate a keyword density summary and SEO strength score. Recommend optimization and internal linking opportunities. Data Structuring β€” Clean and convert GPT output into JSON format. Data Storage (Google Sheets) β€” Append structured keyword data to a Google Sheet for long-term tracking. Setup Prerequisites If you are new to Decode, please signup on this link visit.decodo.com n8n account with workflow editor access Decodo API credentials OpenAI API key Google Sheets account connected via OAuth2 Make sure to install the Decodo Community node. Create a Google Sheet Add columns for: primarykeywords, seostrengthscore, keyworddensity_summary, etc. Share with your n8n Google account. Connect Credentials Add credentials for: Decodo API credentials - You need to register, login and obtain the Basic Authentication Token via Decodo Dashboard OpenAI API (for GPT-4o-mini) Google Sheets OAuth2 Configure Input Fields Edit the β€œSet Input Fields” node to set your target site and region. Run the Workflow Click Execute Workflow in n8n. View structured results in your connected Google Sheet. How to customize this workflow Track Multiple Competitors β†’ Use a Google Sheet or CSV list of URLs; loop through them using the Split In Batches node. Add Language Detection β†’ Add a Gemini or GPT node before keyword analysis to detect content language and adjust prompts. Enhance the SEO Report β†’ Expand the GPT prompt to include backlink insights, metadata optimization, or readability checks. Integrate Visualization β†’ Connect your Google Sheet to Looker Studio for SEO performance dashboards. Schedule Auto-Runs β†’ Use the Cron Node to run weekly or monthly for competitor keyword refreshes. Summary This workflow automates competitor keyword research using: Decodo for intelligent web scraping OpenAI GPT-4.1-mini for keyword and SEO analysis Google Sheets for live tracking and reporting It’s a complete AI-powered SEO intelligence pipeline ideal for teams that want actionable insights on keyword gaps, optimization opportunities, and content focus trends, without relying on expensive SEO SaaS tools.

Ranjan DailataBy Ranjan Dailata
161

Generate song lyrics and music from text prompts using OpenAI and Fal.ai Minimax

Spark your creativity instantly in any chatβ€”turn a simple prompt like "heartbreak ballad" into original, full-length lyrics and a professional AI-generated music track, all without leaving your conversation. πŸ“‹ What This Template Does This chat-triggered workflow harnesses AI to generate detailed, genre-matched song lyrics (at least 600 characters) from user messages, then queues them for music synthesis via Fal.ai's minimax-music model. It polls asynchronously until the track is ready, delivering lyrics and audio URL back in chat. Crafts original, structured lyrics with verses, choruses, and bridges using OpenAI Submits to Fal.ai for melody, instrumentation, and vocals aligned to the style Handles long-running generations with smart looping and status checks Returns complete song package (lyrics + audio link) for seamless sharing πŸ”§ Prerequisites n8n account (self-hosted or cloud with chat integration enabled) OpenAI account with API access for GPT models Fal.ai account for AI music generation πŸ”‘ Required Credentials OpenAI API Setup Go to platform.openai.com β†’ API keys (sidebar) Click "Create new secret key" β†’ Name it (e.g., "n8n Songwriter") Copy the key and add to n8n as "OpenAI API" credential type Test by sending a simple chat completion request Fal.ai HTTP Header Auth Setup Sign up at fal.ai β†’ Dashboard β†’ API Keys Generate a new API key β†’ Copy it In n8n, create "HTTP Header Auth" credential: Name="Fal.ai", Header Name="Authorization", Header Value="Key [Your API Key]" Test with a simple GET to their queue endpoint (e.g., /status) βš™οΈ Configuration Steps Import the workflow JSON into your n8n instance Assign OpenAI API credentials to the "OpenAI Chat Model" node Assign Fal.ai HTTP Header Auth to the "Generate Music Track", "Check Generation Status", and "Fetch Final Result" nodes Activate the workflowβ€”chat trigger will appear in your n8n chat interface Test by messaging: "Create an upbeat pop song about road trips" 🎯 Use Cases Content Creators: YouTubers generating custom jingles for videos on the fly, streamlining production from idea to audio export Educators: Music teachers using chat prompts to create era-specific folk tunes for classroom discussions, fostering interactive learning Gift Personalization: Friends crafting anniversary R&B tracks from shared memories via quick chats, delivering emotional audio surprises Artist Brainstorming: Songwriters prototyping hip-hop beats in real-time during sessions, accelerating collaboration and iteration ⚠️ Troubleshooting Invalid JSON from AI Agent: Ensure the system prompt stresses valid JSON; test the agent standalone with a sample query Music Generation Fails (401/403): Verify Fal.ai API key has minimax-music access; check usage quotas in dashboard Status Polling Loops Indefinitely: Bump wait time to 45-60s for complex tracks; inspect fal.ai queue logs for bottlenecks Lyrics Under 600 Characters: Tweak agent prompt to enforce fuller structures like [V1][C][V2][B][C]; verify output length in executions

Daniel NkenchoBy Daniel Nkencho
601

Automate Dutch Public Procurement Data Collection with TenderNed

TenderNed Public Procurement What This Workflow Does This workflow automates the collection of public procurement data from TenderNed (the official Dutch tender platform). It: Fetches the latest tender publications from the TenderNed API Retrieves detailed information in both XML and JSON formats for each tender Parses and extracts key information like organization names, titles, descriptions, and reference numbers Filters results based on your custom criteria Stores the data in a database for easy querying and analysis Setup Instructions This template comes with sticky notes providing step-by-step instructions in Dutch and various query options you can customize. Prerequisites TenderNed API Access - Register at TenderNed for API credentials Configuration Steps Set up TenderNed credentials: Add HTTP Basic Auth credentials with your TenderNed API username and password Apply these credentials to the three HTTP Request nodes: "Tenderned Publicaties" "Haal XML Details" "Haal JSON Details" Customize filters: Modify the "Filter op ..." node to match your specific requirements Examples: specific organizations, contract values, regions, etc. How It Works Step 1: Trigger The workflow can be triggered either manually for testing or automatically on a daily schedule. Step 2: Fetch Publications Makes an API call to TenderNed to retrieve a list of recent publications (up to 100 per request). Step 3: Process & Split Extracts the tender array from the response and splits it into individual items for processing. Step 4: Fetch Details For each tender, the workflow makes two parallel API calls: XML endpoint - Retrieves the complete tender documentation in XML format JSON endpoint - Fetches metadata including reference numbers and keywords Step 5: Parse & Merge Parses the XML data and merges it with the JSON metadata and batch information into a single data structure. Step 6: Extract Fields Maps the raw API data to clean, structured fields including: Publication ID and date Organization name Tender title and description Reference numbers (kenmerk, TED number) Step 7: Filter Applies your custom filter criteria to focus on relevant tenders only. Step 8: Store Inserts the processed data into your database for storage and future analysis. Customization Tips Modify API Parameters In the "Tenderned Publicaties" node, you can adjust: offset: Starting position for pagination size: Number of results per request (max 100) Add query parameters for date ranges, status filters, etc. Add More Fields Extend the "Splits Alle Velden" node to extract additional fields from the XML/JSON data, such as: Contract value estimates Deadline dates CPV codes (procurement classification) Contact information Integrate Notifications Add a Slack, Email, or Discord node after the filter to get notified about new matching tenders. Incremental Updates Modify the workflow to only fetch new tenders by: Storing the last execution timestamp Adding date filters to the API query Only processing publications newer than the last run Troubleshooting No data returned? Verify your TenderNed API credentials are correct Check that you have setup youre filter proper Need help setting this up or interested in a complete tender analysis solution? Get in touch πŸ”— LinkedIn – Wessel Bulte

Wessel BulteBy Wessel Bulte
247