Opening Problem Statement
Meet Ana, a digital content creator who often struggles to keep up with her audience’s growing demand for fast, creative AI-generated content. She spends countless hours manually inputting prompts into different AI services, waiting for responses, and then sharing those results in her Telegram community. This process is not only time-consuming but prone to delays and errors, costing her valuable engagement opportunities and her sanity.
Ana’s challenge is very specific: she wants a Telegram bot that can understand user commands, send those commands to an advanced AI model for either text or image generation, and return the results directly in the chat — all automatically and reliably. She wishes to cut down hours of back-and-forth and streamline the whole interaction without writing complicated code or managing multiple separate platforms.
What This Automation Does
This n8n workflow provides a comprehensive solution for Ana’s problem by integrating Telegram with NeurochainAI’s advanced models. Here is what happens automatically when a user interacts with the Telegram bot:
- 1. Detect Commands and Message Types: The bot listens for messages starting with the
/fluxprefix for image requests or messages directed at the bot for text generation. - 2. Clean User Prompts: Commands are parsed and cleaned to extract the user’s intent without extra prefixes.
- 3. Show Real-Time Status: The bot sends a typing or processing emoji to inform users their prompt is being handled.
- 4. Call NeurochainAI API: Depending on the request type, text prompts are sent to a language model API, while image prompts trigger AI image generation endpoints.
- 5. Return AI Responses: For text, the generated AI response is sent directly as a Telegram message. For images, the AI-generated image URL is retrieved and shared as a photo in chat with captioning.
- 6. Handle Errors Gracefully: If the prompt is too short, the API response is invalid, or a failure occurs, the bot replies with appropriate error messages and options to retry.
This workflow saves Ana and her users several hours weekly by automating prompt handling, AI requests, and Telegram replies with no manual intervention needed.
Prerequisites ⚙️
- Telegram Bot API: A Telegram Bot credentials setup is required, generated via Telegram’s BotFather.
- NeurochainAI API Key: Valid API access to NeurochainAI for calling their AI models for text and image generation.
- n8n Account: An n8n automation platform set up to design and run the workflow.
Optional:
- Self-hosting your n8n instance is possible for advanced users who want full control. Hostinger offers reliable solutions to get started easily (https://buldrr.com/hostinger).
Step-by-Step Guide
1. Create and Configure Your Telegram Bot
Start by opening Telegram and searching for BotFather. Issue the /newbot command, follow the prompts, choose a bot username, and copy the Token provided. In n8n, add this token to all Telegram nodes under credentials.
Visual: You should see the bot token field in each Telegram node’s credentials tab.
Tip: Ensure tokens are correct in all Telegram nodes to avoid connection errors.
2. Register with NeurochainAI and Retrieve API Key
Sign in to the NeurochainAI Dashboard and generate an API key under the Inference As Service section. Keep this key handy for configuring HTTP Request nodes.
3. Identify Workflow Nodes and Purpose
- Telegram Trigger Node: Listens for any messages sent to your Telegram bot.
- Switch Node: Routes messages based on content, e.g., starts with
/flux, mentions bot, or is a private message. - Code Node (Clean Prompt): Removes the
/fluxprefix to prepare a clean prompt for AI processing. - Telegram Nodes: Several Telegram action nodes send messages, typing indicators, or delete messages based on workflow stage.
- HTTP Request to NeurochainAI – REST API: Sends text prompts to the language model with specific parameters.
- HTTP Request to NeurochainAI – Flux API: Sends prompts for AI image generation.
- Code Node (Parse Image URL): Extracts image URL from the AI response for Telegram photo sending.
4. Configure the Telegram Trigger Node
Set it to listen for all message updates using *. Confirm your Telegram API credentials are entered correctly. This node starts the workflow on any user message.
5. Configure the Switch Node for Message Routing
Set conditions to detect messages starting with /flux and those containing your bot’s username. This routes the flow either to image generation path or text AI response path.
6. Prepare the User Prompt in Code Node
In the Code node, paste the following JavaScript code that removes the /flux prefix and trims whitespace:
// Acessa a mensagem original que está em $json.message.text
const userMessage = $json.message.text;
// Remover o prefixo '/flux' e qualquer espaço extra após o comando
const cleanMessage = userMessage.replace(/^/fluxs*/, '');
// Retornar a mensagem limpa
return {
json: {
cleanMessage: cleanMessage
}
};This prepares the prompt for the AI model.
7. Send Typing Chat Action for User Feedback
Use the Telegram node with the sendChatAction operation to show the typing status in the chat. Configure the chat ID dynamically from the trigger.
8. Configure HTTP Request Nodes
- In the NeurochainAI – REST API node, set the URL to
https://ncmb.neurochain.io/tasks/messageand methodPOST. Paste the JSON body template with the model name and prompt binding. - Configure headers including
Authorization: Bearer YOUR-API-KEY-HEREandContent-Type: application/json. - Similarly, for the NeurochainAI – Flux node, set the image generation endpoint and provide JSON with image prompt and parameters like size and quality.
9. Process AI Responses and Handle Errors
Use Switch nodes to detect errors such as invalid prompts or no response from workers. For text responses, send the AI’s message using Telegram nodes. For images, extract the image URL using the Code node shown below:
// O valor vem como um array com uma string, então precisamos pegar o primeiro item do array
const rawUrl = $json.choices[0].text;
// Remover colchetes e aspas (se existirem) e pegar o primeiro elemento do array
const imageUrl = JSON.parse(rawUrl)[0];
return {
json: {
imageUrl: imageUrl
}
};After parsing, send the image as a photo message with caption referencing the prompt.
10. Fine-tune Result Messaging
Delete processing emojis or old messages using Telegram delete message operations to keep the chat clean and user-friendly.
Customizations ✏️
- Change AI Models: In the HTTP Request nodes to NeurochainAI, swap out the model parameter with any model supported in NeurochainAI dashboard to try different AI behaviors.
- Adjust Image Size and Quality: In the NeurochainAI – Flux node, modify the
sizeandqualityJSON fields for higher resolution or faster generation. - Add More Commands: Extend the Switch node logic to handle new prefixes or commands for other functionalities.
- Customize Bot Responses: Modify Telegram nodes’ text fields to personalize replies, add markdown, emojis, or buttons for richer interaction.
Troubleshooting 🔧
- Problem: “Prompt too short” error message always appears.
Cause: The user message is empty or too short after removing the prefix.
Solution: Add checks in the Code node to ensure minimal length before sending to API or improve the user prompt instructions. - Problem: AI does not respond and “No response from worker” error.
Cause: API key may be invalid or account credits exhausted.
Solution: Verify API key in HTTP Request nodes and ensure balance on NeurochainAI dashboard. - Problem: Telegram messages not sent after AI response.
Cause: Telegram API credentials missing or incorrect.
Solution: Double-check tokens in every Telegram node’s credentials.
Pre-Production Checklist ✅
- Ensure Telegram Bot tokens are correctly added to all Telegram nodes’ credentials.
- Verify NeurochainAI API keys and replace placeholders in HTTP Request nodes.
- Test sending /flux commands and bot mentions in private and group chats.
- Check error handling paths by sending invalid or empty prompts.
- Make sure to save the workflow and activate it before testing.
Deployment Guide
Activate the workflow by toggling it live within n8n. Monitor incoming Telegram updates and logs from n8n’s execution panel for any failures. Adjust API keys or bot token permissions as needed. The workflow’s modular design makes it easy to expand for other AI tasks or message types in the future.
FAQs
- Can I use another AI service instead of NeurochainAI?
Yes, but you’ll need to adjust the HTTP Request nodes and API parameters accordingly. - Do API calls consume usage credits?
Yes, based on NeurochainAI’s pricing and your plan. - Is my Telegram chat data safe?
Data flows through n8n and Telegram servers. Ensure your API keys and tokens are kept private for security. - Can this bot handle large volumes of requests?
The workflow is built for typical usage; consider scaling and rate-limiting if demand grows.
Conclusion
By following this guide, Ana has automated her Telegram community’s AI requests end-to-end using n8n and NeurochainAI. She saves hours weekly by automatically processing text and image prompts, receiving immediate answers and media in chat without manual effort.
This integration proves invaluable for content creators and bot developers wanting to add intelligent AI capabilities within Telegram easily. Next, consider extending this workflow to include multi-language support, richer interactive commands, or integration with other AI models to enhance user experience further.
Happy automating!