Chatbots in TypeScript: A Complete Guide to Building from Scratch

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why TypeScript is the Best Choice for Chatbots?

\n\n

When it comes to creating chatbots, many developers immediately think of Python or JavaScript. But there is one language that combines the flexibility of dynamic typing with the safety of static checking — that is TypeScript. In this practical guide, we will break down how to create chatbots in TypeScript that will not only work stably but also be easy to maintain.

\n\n

TypeScript is not just a "superset" of JavaScript. It is a full-fledged tool that allows you to write code that is harder to break. Imagine: you are writing a bot for Telegram, and suddenly your colleague passes a number instead of a string to a function. In JavaScript, you would find out about this at runtime when the bot crashes. In TypeScript, the compiler will tell you about the error even before launch. Isn't that magic?

\n\n

Where to Start: Environment Setup

\n\n

Before we dive into the code, let's set up the workspace. We will need Node.js (version 16 or higher) and a package manager npm or yarn.

\n\n

Step 1: Project Initialization

\n\n
mkdir my-chat-bot\ncd my-chat-bot\nnpm init -y\n
\n\n

Step 2: Installing Dependencies

\n\n

To work with chatbots, we will use the popular library telegraf (for Telegram) and discord.js (for Discord). But in this guide, we will focus on a universal approach.

\n\n
npm install typescript @types/node telegraf dotenv\nnpx tsc --init\n
\n\n

The tsconfig.json file needs a slight adjustment: enable strict: true and specify outDir: "./dist". This will make the code safer.

\n\n

Project Structure for Chatbots in TypeScript

\n\n

Good architecture is the key to success. Here is how I recommend organizing the files:

\n\n
src/\n├── bot/\n│   ├── index.ts          # Entry point\n│   ├── handlers/         # Command handlers\n│   ├── middleware/        # Middleware handlers\n│   └── types/            # Types and interfaces\n├── config/\n│   └── index.ts          # Configuration\n└── utils/\n    └── logger.ts         # Logging\n
\n\n

Writing Your First Chatbot in TypeScript

\n\n

Let's create a simple Telegram bot that responds to the /start command and echo messages.

\n\n

File: src/config/index.ts

\n\n
import dotenv from 'dotenv';\ndotenv.config();\n\nexport const config = {\n  BOT_TOKEN: process.env.BOT_TOKEN || '',\n  PORT: parseInt(process.env.PORT || '3000')\n};\n
\n\n

File: src/bot/index.ts

\n\n
import { Telegraf } from 'telegraf';\nimport { config } from '../config';\nimport { startHandler } from './handlers/start';\nimport { echoHandler } from './handlers/echo';\n\nconst bot = new Telegraf(config.BOT_TOKEN);\n\n// Register handlers\nbot.start(startHandler);\nbot.on('text', echoHandler);\n\n// Launch the bot\nbot.launch()\n  .then(() => console.log('Bot launched!'))\n  .catch((err) => console.error('Launch error:', err));\n\n// Graceful shutdown\nprocess.once('SIGINT', () => bot.stop('SIGINT'));\nprocess.once('SIGTERM', () => bot.stop('SIGTERM'));\n
\n\n

File: src/bot/handlers/start.ts

\n\n
import { Context } from 'telegraf';\n\nexport const startHandler = async (ctx: Context) => {\n  const userName = ctx.from?.first_name || 'friend';\n  await ctx.reply(`Hello, ${userName}! I am a bot in TypeScript. Write me something.`);\n};\n
\n\n

File: src/bot/handlers/echo.ts

\n\n
import { Context } from 'telegraf';\n\nexport const echoHandler = async (ctx: Context) => {\n  const message = ctx.message?.text || '';\n  await ctx.reply(`You wrote: "${message}". Cool!`);\n};\n
\n\n

Notice the typing: Context from the telegraf library is fully typed. This means the IDE will suggest all available methods and properties to you. Chatbots in Ty

Blogs

Book Recommendations