How to create a Telegram bot with ChatGPT: no-code and with code
We will build a Ukrainian AI bot that a user writes to in Telegram, and an OpenAI model generates the response. A beginner can do this in n8n without programming, while an experienced reader can launch a minimal version in JavaScript and develop it further.

What we are creating and who needs it
A Telegram bot is a separate account managed by a program. A person sends a message, Telegram passes it to our script, the script calls the OpenAI model and returns the response back to the chat. This can be used to create a customer support assistant, an internal knowledge base, a trainer, a translator, an idea generator, or an interface for your own service.
In everyday life, such a project is often called a "ChatGPT bot." Technically, the bot does not manage the ChatGPT website: it uses OpenAI API. This is an important distinction. A ChatGPT subscription and API usage are separate products; a bot requires an API key and configured API usage billing.
No-code route
Telegram Trigger → OpenAI → Telegram in n8n. Suitable for a first working prototype, automations, and people who prefer building logic with blocks.
Code route
A small JavaScript server-side script. Suitable if you need custom logic, a database, precise error control, or scaling.
What you need before starting
- a Telegram account;
- access to an official @BotFather;
- OpenAI Platform account, an API key, and a set spending limit;
- for the no-code route — n8n Cloud or your own n8n with a public HTTPS address;
- for the code route — Node.js 20 or newer and a server for continuous operation.
Step 1. Create a bot via BotFather
- Check the address. Open specifically
@BotFatherthe one with the blue Telegram checkmark, not a similar third-party account. - Send
/newbot. Specify a visible name, e.g., "My AI Assistant". - Create a username. It must be unique and end with
bot, for examplemy_ua_helper_bot. - Save the token. BotFather will send a string for Bot API access. Do not forward it in a chat or publish it on GitHub.
- Add a description and commands. Through
/mybotsset up/start,/helpand briefly explain what the bot can do and how it uses messages.
Telegram allows you to revoke a token via BotFather. If a secret ends up in a screenshot, repository, or someone else's hands, don't just delete it from the file — immediately create a new token and replace it in your settings.
Option 1. No-code Telegram bot via n8n
In n8n, a workflow consists of nodes. For a minimal bot, you need three parts: receive a message from Telegram, pass the text to the model, and send the response. Individual operation names may change slightly with the n8n interface, but the scheme remains the same.
- Create a Telegram credential. In n8n, add Telegram credentials and paste the BotFather token into the secure credentials field.
- Add a Telegram Trigger. Select the new message event. Start a test listen and message the bot in a private chat.
- Discard unnecessary events. Verify that the update contains text. Photos, stickers, or button presses have a different structure and should not break the scenario.
- Connect OpenAI. Create an OpenAI credential, without pasting the key into a regular text field of the node. Select a text generation operation and an affordable, current text model.
- Pass the instruction. Set the bot's role separately, and insert the user's message from the Telegram Trigger.
- Add Telegram Send Message. In the Chat ID field, pass the incoming chat ID, and in Text — the OpenAI result.
- Activate the workflow. Test run only works during verification. For a permanent response, the scenario must be saved and active.
For the first version, do not add conversation memory, documents, search, and ten integrations all at once. First, test a simple chain with twenty different messages. Then, separately add dialogue history, user restrictions, a knowledge base, or commands.
Common problems in n8n
- The Trigger is silent. One Telegram bot can have only one active webhook. Check if the same token is being used in another workflow or service.
- It works in the test, but not after closing. The workflow is not activated or n8n is not accessible from the internet via HTTPS.
- The bot responds in the wrong chat. The Chat ID is set manually instead of using the value from the current incoming message.
- The OpenAI node returns a payment error. API billing is not configured, the limit is exhausted, or a model unavailable for the project is selected.
Option 2. Minimal bot in JavaScript
This example uses the official OpenAI package and receives Telegram messages via long polling. For learning, this is easier than a webhook: the process constantly requests new updates. For high loads and serverless hosting, it is better to switch to a webhook later.
Create an empty folder and run:
npm init -y
npm install openai
npm pkg set type=module
Save the code in a file bot.mjs:
import OpenAI from "openai";
const telegramToken = process.env.TELEGRAM_BOT_TOKEN;
const openaiKey = process.env.OPENAI_API_KEY;
const model = process.env.OPENAI_MODEL || "gpt-5.6-luna";
if (!telegramToken || !openaiKey) {
throw new Error("Додайте TELEGRAM_BOT_TOKEN і OPENAI_API_KEY");
}
const openai = new OpenAI({ apiKey: openaiKey });
const telegramApi = `https://api.telegram.org/bot${telegramToken}`;
let offset = 0;
async function telegram(method, body = {}) {
const response = await fetch(`${telegramApi}/${method}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
const data = await response.json();
if (!data.ok) throw new Error(`Telegram: ${data.description}`);
return data.result;
}
async function answer(chatId, text) {
const response = await openai.responses.create({
model,
instructions:
"Відповідай українською, коротко і точно. Не проси секрети.",
input: text,
});
const reply = response.output_text || "Не вдалося сформувати відповідь.";
await telegram("sendMessage", { chat_id: chatId, text: reply.slice(0, 4096) });
}
while (true) {
try {
const updates = await telegram("getUpdates", {
offset,
timeout: 30,
allowed_updates: ["message"],
});
for (const update of updates) {
offset = update.update_id + 1;
const message = update.message;
if (!message?.text) continue;
if (message.text === "/start") {
await telegram("sendMessage", {
chat_id: message.chat.id,
text: "Привіт! Напишіть запитання — я відповім українською.",
});
continue;
}
await answer(message.chat.id, message.text);
}
} catch (error) {
console.error(error.message);
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
Before running, set secrets as environment variables. Do not write them into the file itself. On Linux or macOS for local testing:
export TELEGRAM_BOT_TOKEN="ваш_токен"
export OPENAI_API_KEY="ваш_ключ"
node bot.mjs
In PowerShell, use $env:TELEGRAM_BOT_TOKEN="..." and a $env:OPENAI_API_KEY="...". For hosting, add the same names via the platform's secrets panel.
If the bot needs to not just write text, but return stable fields for a CRM, a table, or other automation, use Structured Outputs and JSON Schema instead of a fragile prompt like "return only JSON".
Security, privacy, and real cost
| Part | Free | Possible costs |
|---|---|---|
| Telegram Bot API | Creating a bot and basic messages | Your server, database, or third-party services |
| n8n | Self-hosting Community Edition | n8n Cloud or a server for self-hosting |
| OpenAI API | Do not rely on a permanent free quota | Payment for actual usage of the selected model |
| JavaScript bot | Development and local testing | 24/7 hosting, domain not required |
For a text bot with a large flow of short messages, it is logical to start with a cost-optimized model and set a small monthly limit. Do not copy old prices from the article: models and tariffs change, so check the current OpenAI catalog before launching.
- keep keys only in credentials or environment variables;
- limit the length of the incoming message and the number of requests from a single user;
- do not send medical, financial, children's, or other sensitive data to the model without a clear need and proper rules;
- explain to the user that responses are AI-generated and may be incorrect;
- do not allow user text to change system rules, run arbitrary code, or read secrets;
- disable or minimize message logging; define a data retention period;
- set a spending limit and alerts, and immediately revoke both keys in case of a leak.
A more detailed action plan is in our material on API key security in Vibe Coding.
How to test a bot before public launch
- Start with a private test. Do not add the bot to groups until the core logic is stable.
- Check the commands.
/start, plain text, empty message, very long text, Ukrainian and English languages. - Send non-text content. Photos, voice messages, files, and stickers should not break the scenario. The bot can politely inform that it currently only works with text.
- Check parallel users. One user's response and memory should not leak to another.
- Simulate an API error. The user should receive a short message, not a technical stack or a secret.
- Restart the server. Ensure the bot recovers automatically and does not respond twice to old messages.
- Review costs. After a series of tests, check usage in the OpenAI Platform and set an acceptable budget.
What the minimal code already does and what needs to be finished
The checklist above describes the requirements for launch. The tutorial script from this guide covers only part of them. Below is the result of code reading, not a report of a test conducted with real users.
| Scenario | Current code behavior | Next steps for improvement |
|---|---|---|
Command /start | Sends a greeting without calling the model. | Verify that the response arrives in the correct private chat. |
| Sticker or photo | Ignores messages without text. | If necessary, add a short explanation of the supported format without calling the AI. |
| Model request error | The external handler logs the error to the console; the user may not receive a response. | Handle failure for an individual message and show neutral text without technical details. |
| Two people writing simultaneously | Messages are processed sequentially; a slow response delays the next ones. | Think through a queue, a limited number of concurrent tasks, and the order of responses in each chat. |
| Restarting the process | offset is only kept in memory and resets upon startup. | Store the processing state reliably and verify update redelivery. This example itself does not guarantee the absence of duplicates. |
| Many requests from a single account | There is no built-in rate limiting or budget in the code. | Add server-side usage tracking to the open access. |
How to record a failure: record the time, message type, expected and actual behavior. In the technical log, leave only the necessary error code and test request ID; do not copy tokens or private conversations. After the fix, repeat the exact failed scenario and one normal request.
For an advanced check of changes, use the AI code verification guide. A public bot requires separate checks for access, costs, and recovery after failures, even if the first response already works.
FAQ
Can you make a bot without programming?
Yes. n8n allows you to build a first version using ready-made nodes. But "no-code" does not mean "no logic": you still need to correctly pass the Chat ID, text, credentials, and anticipate errors.
Will the bot work when the computer is turned off?
Only if n8n or the code is running on an external server. A local process on a laptop will stop responding after being turned off, entering sleep mode, or losing internet.
Do you need your own domain?
For long polling — no. For a webhook, a reachable Telegram HTTPS address is required; n8n Cloud provides one, while a self-hosted n8n will need a correctly configured public address.
How to create conversation memory?
Store history separately for each chat_id in a database or a specialized memory store. Do not use one shared history for everyone and do not pass an endless message log to the model.
Official primary sources
Telegram bot as a service for a client
Include deployment, API costs, error handling, and maintenance in your estimate. Do not promise work without limitations for a fixed price. More details: how to sell automations and calculate the scope of work.
Stuck with a bot or want to show your results?
Bring your scheme or code to "Vibe Coding". We will help formulate the problem and analyze the project without publishing secrets.
Join the Telegram chat ↗
Discussion
Share your opinion or ask about the material. Your nickname and comment text will be visible to everyone.
Log in via email
Get a one-time code. No password required.
The code is valid for 10 minutes. Logging in does not subscribe you to the newsletter. Data usage.
Or log in via ChatGPT ↗Loading comments...