Build a Telegram AI Chatbot with Node.js

by Fahim Mahmud Chisti

A developer workspace showing a laptop with code and a smartphone displaying a Telegram AI agent conversation.

This tutorial shows you how to build a Telegram AI chatbot with Node.js. You will create a bot in BotFather, connect it to a chat model through the OpenAI API, give it short-term memory, lock it to your own account and keep it online with PM2. If you would rather connect a local Ollama model to the Telegram bot, the same code works after a three-line change in .env.

Quick answer: Create a bot with @BotFather to get a token, then run a small Telegraf script that forwards each message to a chat model and sends the answer back. The OpenAI SDK calls OpenAI by default, or Ollama if you point it at http://localhost:11434/v1/.

  1. Send /newbot to @BotFather and copy the token.
  2. Run npm install telegraf openai dotenv and put the token and model settings in .env.
  3. Create index.js with the message handler and start it with node index.js.
  4. Add the allow-list so only your Telegram user ID can use the bot.
  5. Keep it running on a VPS with pm2 start index.js.
In this guide
  1. How the Bot Works
  2. Before You Start
  3. Step 1: Create the Bot and Get Its Token in BotFather
  4. Step 2: Set Up the Node.js Project
  5. Step 3: Write the Bot Script
  6. Step 4: Let Only Your Account Use the Bot
  7. Step 5: Give the Bot Memory of the Conversation
  8. Optional: Connect the Bot to a Local Ollama Model
  9. Step 6: Keep the Bot Running on a VPS with PM2
  10. Common Errors and Fixes
  11. Frequently Asked Questions
  12. Next Steps

How the Bot Works

Telegram already handles the chat window, user accounts and message delivery, so you only write the backend. The script does three things:

  1. It receives each new message. Telegraf uses long polling: the script keeps asking the Telegram Bot API for new updates, so you need no public URL or HTTPS certificate.
  2. It sends the text to a chat model and waits for the answer. This model call takes most of the response time, usually a few seconds.
  3. It replies in the same chat, split into parts when the answer is longer than Telegram allows.

Before You Start

  • Node.js 22 or newer on your computer and later on the server, because the current official openai package requires it. Check with node --version, and download it from the official Node.js website if needed.
  • A Telegram account to talk to BotFather and test the bot.
  • A model to call: an API key from the OpenAI Developer Platform with billing enabled, or Ollama running on the same machine as the bot.
  • A terminal for the commands, and SSH access to a VPS if you want the bot online around the clock.
  • Time: about 20 minutes for a working bot on your own computer.

Step 1: Create the Bot and Get Its Token in BotFather

BotFather is Telegram’s official account for creating bots. It gives you an HTTP API token, which works like a password that lets your code control the bot.

  1. In the Telegram app, search for @BotFather (it has a verified badge) and press Start.
  2. Send the command /newbot.
  3. Enter a display name, then a username that ends in “bot” (for example MyAIAgentBot).
  4. Copy the HTTP API token that BotFather sends back.

Keep this token private. Anyone who has it can control your bot and read the messages people send to it. If it leaks, send /token to BotFather to generate a new one.

Step 2: Set Up the Node.js Project

Run these commands in a terminal on your computer. They create the project folder and a default package.json file:

mkdir telegram-ai-agent
cd telegram-ai-agent
npm init -y

npm prints the new package.json. Next, install three packages: the Telegraf framework for the Telegram side, the official OpenAI SDK for the model call, and dotenv, which loads secrets from a file into environment variables:

npm install telegraf openai dotenv

Create a file named .env in the project folder and add your credentials, replacing the placeholder values:

TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_MODEL=gpt-6-luna

Add .env to .gitignore (for example with echo ".env" >> .gitignore) so the keys never reach a repository. OpenAI retires model IDs regularly (gpt-4o-mini, used in many older tutorials, is scheduled to shut down in January 2027), so check the current model list and keep the ID in this one variable.

Step 3: Write the Bot Script

Create a file named index.js in the same folder and paste the code below. It loads .env, starts Telegraf, sends every text message to the model with a short system prompt (the instruction that sets the bot’s behaviour), and posts the answer back to the chat.

require('dotenv').config();
const { Telegraf } = require('telegraf');
const { message } = require('telegraf/filters');
const { OpenAI } = require('openai');

const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const MODEL = process.env.OPENAI_MODEL || 'gpt-6-luna';

// Telegram rejects messages longer than 4096 characters, so send long replies in parts
async function replyInChunks(ctx, text) {
  for (let i = 0; i < text.length; i += 4096) {
    await ctx.reply(text.slice(i, i + 4096));
  }
}

bot.on(message('text'), async (ctx) => {
  const userMessage = ctx.message.text;
  try {
    const response = await openai.chat.completions.create({
      model: MODEL,
      messages: [
        { role: 'system', content: 'You are a helpful and concise AI assistant.' },
        { role: 'user', content: userMessage },
      ],
    });
    await replyInChunks(ctx, response.choices[0].message.content);
  } catch (error) {
    console.error('Error processing message:', error);
    await ctx.reply('Sorry, I encountered an error processing your request.');
  }
});

// With long polling, the promise returned by launch() only settles when the bot stops,
// so log from the onLaunch callback instead of .then()
bot.launch(() => console.log('AI Agent is running on Telegram...'));

process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));

Test it

  1. In the project folder, run node index.js. The terminal should print AI Agent is running on Telegram... and keep running.
  2. In Telegram, search for your bot’s username, open the chat and send a message such as “Hello”.
  3. The bot should answer within a few seconds. If it replies “Sorry, I encountered an error processing your request.”, the terminal shows the real error; see Common Errors and Fixes below.

Press Ctrl+C in the terminal to stop the bot.

Step 4: Let Only Your Account Use the Bot

Anyone who finds your bot’s username can message it and spend your OpenAI credits. Restrict it to a list of Telegram user IDs:

  1. Find your numeric user ID. Temporarily add console.log(ctx.from.id); as the first line inside the bot.on(...) handler, restart the bot, send it a message and copy the number from the terminal. Then remove the line.
  2. Add ALLOWED_USER_IDS= followed by your ID to .env. Separate several IDs with commas.
  3. In index.js, paste the block below after the const MODEL = ... line and before bot.on(...). Telegraf runs middleware in the order you register it, so the check has to come first.
const allowedUsers = (process.env.ALLOWED_USER_IDS || '').split(',').filter(Boolean);

bot.use((ctx, next) => {
  if (allowedUsers.includes(String(ctx.from?.id))) return next();
  // Everyone else is ignored
});

Restart the bot. It should still answer you and silently ignore every other account. If ALLOWED_USER_IDS is empty, the bot ignores everyone, including you.

Step 5: Give the Bot Memory of the Conversation

Chat model APIs are stateless: the model only sees what you send in each request. To make the bot remember earlier messages, you store each user’s recent messages and send them with every new one. This version keeps them in a JavaScript object in memory. That is fine for testing, but it is emptied every time the process restarts, so use a database or Redis in production.

Replace the contents of index.js with the version below. Then paste the allow-list block from Step 4 back in, after the const sessions = {}; line:

require('dotenv').config();
const { Telegraf } = require('telegraf');
const { message } = require('telegraf/filters');
const { OpenAI } = require('openai');

const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const MODEL = process.env.OPENAI_MODEL || 'gpt-6-luna';
const sessions = {};

async function replyInChunks(ctx, text) {
  for (let i = 0; i < text.length; i += 4096) {
    await ctx.reply(text.slice(i, i + 4096));
  }
}

bot.on(message('text'), async (ctx) => {
  const userId = ctx.from.id;
  const userMessage = ctx.message.text;

  if (!sessions[userId]) {
    sessions[userId] = [{ role: 'system', content: 'You are a helpful assistant.' }];
  }
  sessions[userId].push({ role: 'user', content: userMessage });

  // Keep the system prompt (index 0) and drop the oldest exchange
  if (sessions[userId].length > 15) {
    sessions[userId].splice(1, 2);
  }

  try {
    const response = await openai.chat.completions.create({
      model: MODEL,
      messages: sessions[userId],
    });
    const replyText = response.choices[0].message.content;
    sessions[userId].push({ role: 'assistant', content: replyText });
    await replyInChunks(ctx, replyText);
  } catch (error) {
    console.error(error);
    await ctx.reply('Error processing request.');
  }
});

bot.launch(() => console.log('AI Agent is running on Telegram...'));

process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));

The bot keeps the system prompt plus roughly the last 14 messages per user, so it remembers recent context without the request growing forever. To test it, restart the bot, tell it your name, then ask “What is my name?” in the next message. It should answer correctly.

Optional: Connect the Bot to a Local Ollama Model

Ollama runs open models on your own machine and offers an OpenAI-compatible API on port 11434. The OpenAI SDK reads the OPENAI_BASE_URL environment variable, so you can switch the bot to Ollama without editing index.js. With Ollama installed and a model pulled, change these three lines in .env and keep TELEGRAM_BOT_TOKEN and ALLOWED_USER_IDS as they are:

OPENAI_BASE_URL=http://localhost:11434/v1/
OPENAI_API_KEY=ollama
OPENAI_MODEL=llama3.2

Ollama ignores the API key, but the SDK needs a value. Set OPENAI_MODEL to the exact name that ollama list shows, for example a small instruction-tuned model such as llama3.2. Restart the bot and test it the same way; replies now come from your own hardware, so their speed depends on your CPU or GPU. New to Ollama? Start with how to install Ollama and run a model locally.

Step 6: Keep the Bot Running on a VPS with PM2

On your laptop, the bot stops when you close the terminal. To keep it online, run it on a virtual private server (VPS) under PM2, a process manager that restarts Node.js apps after a crash or a reboot.

  1. Copy the project folder to the server without node_modules (for example with git clone or scp), and create the .env file on the server by hand.
  2. Connect to the server over SSH, go to the project folder and run npm install.
  3. Stop the copy running on your laptop, then run these commands on the server:
npm install -g pm2
pm2 start index.js --name telegram-ai-agent
pm2 save
pm2 startup   # prints the command that makes PM2 start on boot

pm2 startup prints one more command; copy and run it so PM2 starts on boot. pm2 status should now list telegram-ai-agent as online, and pm2 logs telegram-ai-agent should show the startup line. For boot scripts and log rotation in more detail, see how to configure PM2 startup scripts and log rotation on a VPS.

Run a single instance only: two processes polling Telegram with the same bot token fail with a 409 Conflict error.

Common Errors and Fixes

  • 401: Unauthorized when the bot starts: the Telegram token in .env is wrong or was replaced. Copy it again from BotFather.
  • 409: Conflict: terminated by other getUpdates request: another copy of the bot is running with the same token. Stop it so only one process polls Telegram.
  • The bot replies “Sorry, I encountered an error…”: read the error in the terminal or in pm2 logs. A 401 from OpenAI means a bad API key, a 429 means you hit a rate limit or have no credit left, and a 404 means the model ID is not available to your account.
  • The bot never answers you: your ID is missing from ALLOWED_USER_IDS, or you edited .env without restarting. Restart with node index.js or pm2 restart telegram-ai-agent.
  • ECONNREFUSED with Ollama: Ollama is not running on the machine where the bot runs. Start the Ollama app or run ollama serve, then check that http://localhost:11434 answers “Ollama is running”.

Frequently Asked Questions

How much does it cost to run a Telegram AI chatbot?

The Telegram Bot API is free, so you pay only for the model and the hosting. OpenAI charges per token of input and output, and the history from Step 5 is sent with every message. A small VPS covers the always-on Node.js process. With Ollama there is no per-message fee, but you need hardware that can run the model.

Can I connect a local Ollama model to a Telegram bot?

Yes. Ollama offers an OpenAI-compatible API, so this bot works with it once you set OPENAI_BASE_URL, OPENAI_API_KEY and OPENAI_MODEL in .env, as shown in the optional section. Run the bot on the same machine as Ollama, or point the URL at the server where Ollama listens.

Can the bot call external APIs or tools?

Yes, through function calling (also called tool calling). You describe your functions in the request, the model answers with the function it wants and its arguments, and your code runs it and sends back the result. Keep each tool narrow, because anyone on the allow-list can trigger it from chat.

Does the bot work in Telegram group chats?

Yes, but bots run in privacy mode by default. In a group, the bot then only receives commands meant for it and replies to its own messages. You can turn privacy mode off with BotFather’s /setprivacy command and re-add the bot to the group. The allow-list still decides who gets answers.

How do I keep my bot token safe?

Keep it only in .env on your computer and server, never in code or a public repository. If it leaks, generate a new one with /token in BotFather and update .env. The allow-list from Step 4 also limits who can use the bot if someone finds its username.

Next Steps

Your bot now answers only you, remembers recent messages and keeps running under PM2. Good next moves:

all_in_one_marketing_tool