Chatbot Mastery: Coding Telegram Bots with GPT-4 Made Easy

Chapter 1: Laying the Foundation — Creating the Ultimate Telegram Bot Boilerplate with GPT-4 (part 1/2)

Carlos De La Lama-Noriega
10 min readMar 17, 2023

--

Hey folks! If you’ve ever wondered whether it’s possible to tap into the mind-blowing potential of GPT-4 to code a fully functional Telegram bot, I’ve got some exciting news for you — it totally is! And let me tell you, it works like an absolute charm. 🤯

Jumping into coding with GPT-4 feels like diving headfirst into a groundbreaking new world, where AI swoops in and helps create spectacular things with barely any effort. In this series, I’ll guide you every step of the way as we build an insanely awesome Telegram bot from the ground up, with some major (and I mean, A LOT of) assistance from our AI buddy, GPT-4.

And, get this: even this very text you’re reading right now has been whipped up by GPT-4 itself! Mind-blowing, right?!

I’ve designed this as a “shower series” 🚿, where I’ll be guiding you step-by-step, starting from absolute scratch. In this first part, we’ll have GPT-4 help us generate a Telegram bot boilerplate, which you can use every time you want to start a new bot project. So, buckle up and get ready for an incredible journey! 🚀

The Naming Game — GPT-4 Cooks Up ‘Telegram-BoilerBotBazaar’

Before we dive into the actual coding, we need a catchy name for our GitHub repository! So, I turned to GPT-4 for some suggestions. My initial question was, “how would you call a GitHub repository that has a project to start a TypeScript Telegram bot? It’s a skeleton to get started. Give me 10 names.” The names GPT-4 provided were decent, but they didn’t quite pack the creative punch I was looking for.

So, I nudged GPT-4 a bit further, saying “ok, be more creative. Even make it fun.” After another 10 ideas, I still wanted something that truly stood out. I decided to ask GPT-4 to “Use the word boilerplate, or something similar that sounds funny.”

GPT-4 took up the challenge, and after a few more tries, it hit the jackpot. I finally chose the perfect name for our repository: “Telegram-BoilerBotBazaar.” 🎉

Not only did GPT-4 come up with the brilliant name “Telegram-BoilerBotBazaar,” but it even crafted a description for the GitHub repository. I did make a few tweaks, though, as it was a tad overenthusiastic with adjectives like “robust” and “versatile.” After my edits, the final description reads: “Telegram-BoilerBotBazaar provides a starting point for building your own custom Telegram bots using TypeScript.”

Oops, Almost Forgot! — Essential Tools to Have Installed Before We Begin

There are a few prerequisites you’ll need to have installed on your system:

  1. Node.js: To run the bot, you’ll need to have Node.js installed. It’s the JavaScript runtime that executes the TypeScript code after it’s been transpiled. You can download it from the official website: https://nodejs.org/
  2. npm (Node Package Manager): npm comes bundled with Node.js and is used for managing dependencies and running scripts. Make sure you have the latest version installed. You can check your installed version by running npm -v in your terminal or command prompt.
  3. TypeScript: Since we’re using TypeScript for this project, you’ll need to have it installed globally. We’ll install it when we initialize the project.
  4. Visual Studio Code (VSCode): Although not strictly required, using a code editor like VSCode is highly recommended for a smooth development experience. VSCode has excellent support for TypeScript and a vast array of extensions for additional functionality. You can download it from the official website: https://code.visualstudio.com/
  5. GrammY: As the Telegram bot framework we’ll be using in this project, you’ll need to install GrammY. To install the GrammY library, run the following command in your terminal:
npm install grammy

This command adds GrammY to your project’s dependencies, allowing you to utilize its features to build your bot.

With these tools installed, you’ll be well-prepared to start building your Telegram bot using the GrammY framework and TypeScript.

Ready, Set, Code! — Kicking Off the Telegram Bot Development

For my first query to GPT-4, I asked: “Write a basic Telegram bot that uses GrammY and TypeScript.” To my delight, GPT-4 provided me with the instructions needed to generate a fundamental Telegram bot. Let’s dive into those steps and kick off our bot development journey!

It’s worth noting that I chose the GrammY framework based on GPT-4’s recommendation. I asked GPT-4 which framework to use, and it suggested GrammY. This was actually my first time using GrammY, so it was a fantastic learning experience for both of us!

Following GPT-4’s guidance, I created a folder called “Telegram-BoilerBotBazaar” and opened it in Visual Studio Code (VSCode). Inside VSCode, I opened a terminal and typed the command npm init -y. This command initializes a new Node.js project by generating a package.json file, which serves as the project's manifest. The -y flag automatically accepts the default values for the various configuration options, speeding up the process and allowing us to get started on our bot development even quicker.

To install TypeScript, I used the command npm install -g typescript ts-node. This command not only installs TypeScript but also installs ts-node, a handy tool that allows you to execute TypeScript code directly, without the need for transpiling it to JavaScript first.

Next up, I ran tsc --init in the terminal. This command initializes a TypeScript project by creating a tsconfig.json file, which contains the configuration settings for the TypeScript compiler. By customizing the settings in this file, you can control various aspects of the TypeScript compilation process to best suit your project's needs.

Following that, I installed nodemon by running the command npm i nodemon. Nodemon is a fantastic utility that automatically restarts your Node.js application whenever any file changes in the project directory. This feature is particularly useful during development, as it saves you from having to manually restart the application every time you make changes to the code.

To streamline the development process and make running our bot more efficient, I added the following scripts to the package.json file:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc -w --skipLibCheck",
"dev": "nodemon --exec ts-node -- bot.ts"
}

Here’s a quick breakdown of each script:

  1. "test": This is the default test script that gets generated when you run npm init. It doesn't perform any actual testing but serves as a placeholder for when you want to add your own test script.
  2. "tsc": This script runs the TypeScript compiler (tsc) in watch mode (-w) while skipping library type checking (--skipLibCheck). With watch mode enabled, the compiler will automatically recompile your TypeScript code whenever you save a file, making development faster and more efficient.
  3. "dev": This script uses nodemon to run the ts-node command, which in turn executes our main bot file bot.ts. The --exec flag tells nodemon to use ts-node to run the TypeScript code directly. With this script in place, you can simply run npm run dev in your terminal to start your bot, and it will automatically restart whenever you make changes to your code.

Basic Setup Complete — Time to Craft Our Telegram Bot!

With the fundamental configuration and tooling in place, we’re all set to start writing the actual code for our Telegram bot! In the following steps, we’ll dive into the GrammY framework, explore its features, and start crafting our very own TypeScript-powered Telegram bot. It’s an exciting journey ahead, so let’s get those creative juices flowing and bring our bot to life! 🤖🚀

As per GPT-4’s guidance, our first step in building the Telegram bot is to create a bot.ts file. This file will serve as the main entry point for our bot's code, and it's where we'll write all the logic needed to interact with Telegram's API using the GrammY framework and TypeScript. So go ahead and create the bot.ts file in your project's src directory!

This is how bot.ts should look like:

import { Bot } from "grammy";

// Replace YOUR_BOT_TOKEN with your actual bot token
const bot = new Bot("YOUR_BOT_TOKEN");

bot.command("start", (ctx) => ctx.reply("Welcome to my basic GrammY bot!"));

bot.on("message", (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});

bot.start();

Leveling Up Security — Safely Storing the Bot Token in an .env File

GPT-4 initially suggested placing the bot token directly in the main bot.ts file. However, for security reasons, it's much safer to store sensitive information like the bot token in a separate .env file. So, I asked GPT-4 for a better approach, and it provided me with the right answer!

So to install the dotenv package, which will help us securely access the bot token stored in our .env file, simply run the following command:

npm install dotenv

This command installs the dotenv package as a dependency in your project, making it available for you to import and use in your code. Once installed, you can use dotenv to load the contents of your .env file into your application's environment variables.

And our bot.ts now should look like this:

import { Bot } from "grammy";
import * as dotenv from "dotenv";

// Load environment variables from .env file
dotenv.config();

// Use the bot token from the .env file
const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN!);

bot.command("start", (ctx) => ctx.reply("Welcome to my basic GrammY bot!"));

bot.on("message", (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});

bot.start();

Awesome.

Generating Your Telegram Bot and Token — A Chat with the BotFather

Before we proceed with storing the bot token in the .env file, let's take a step back and make sure we have our bot token ready. If you haven't done so already, you'll need to create a new Telegram bot and obtain its unique bot token. To do this, follow these steps:

  1. Open the Telegram app and search for the “BotFather” bot.
  2. Start a chat with the BotFather and send the command /newbot to create a new bot.
  3. Follow BotFather’s instructions to choose a name and username for your bot.
  4. Once your bot is created, the BotFather will provide you with a bot token. Make sure to save this token securely, as you’ll need it to interact with the Telegram API.

Now that you have your bot token, create a .env file in the root folder of your project. Inside the .env file, add the following line to store your bot token:

TELEGRAM_BOT_TOKEN=your_bot_token_here

Replace your_bot_token_here with the actual bot token you received from the BotFather. With the token safely stored in the .env file, we can now proceed with configuring our project to access it securely.

Taking Our Telegram Bot for Its First Test Run — Two Commands Away!

Now that we’ve set up our Telegram bot project, it’s time to give it a test run for the very first time! To do this, you’ll need to follow these two steps:

  1. In a terminal window, run the command npm run tsc. This command starts the TypeScript compiler, which will compile your TypeScript code into JavaScript, based on the configuration specified in the tsconfig.json file. By running this command, you ensure that your latest TypeScript code is properly transpiled into JavaScript, making it executable by Node.js.
  2. In a second terminal window, execute the command npm run dev. This command will start your bot using nodemon and ts-node, as defined in the dev script in your package.json. With this setup, your bot will automatically restart whenever you make changes to the code, providing you with a seamless development experience.

By executing these two commands, you’ll have your bot up and running, ready to respond to your commands and messages on Telegram.

NOTE: You might encounter an error message like “Cannot find name ‘process’. Do you need to install type definitions for node? Try npm i --save-dev @types/node" while working with TypeScript and Node.js. This error occurs because TypeScript, by default, doesn't include the type definitions for Node.js global objects such as process. As a result, TypeScript is unable to recognize these objects, leading to the error. To fix this issue, you'll need to install the Node.js type definitions using the command npm i --save-dev @types/node. This command adds the type definitions for Node.js as a development dependency, ensuring that TypeScript can properly recognize and work with the process object and other Node.js global objects. Once you've installed @types/node, the error should be resolved, and your project should run smoothly:

The moment has finally arrived! After all the setup, configuration, and coding with GPT-4, GrammY, and TypeScript, you’ve successfully executed your Telegram bot for the first time. Seeing your bot come to life and work as intended is a genuinely exciting and rewarding experience. It’s a testament to the power of AI, modern frameworks, and your dedication to learning and building something new. As you continue to enhance your bot, remember to celebrate these small victories along the way — they’re the building blocks of innovation and growth.

It seems like this post is getting quite lengthy, and there’s still a lot more to cover! In the interest of keeping things digestible and easy to follow, I’ve decided to wrap up this post here and continue our journey in a second part. Stay tuned for the next installment of our series, where we’ll dive deeper into building our Telegram bot using GPT-4, GrammY, and TypeScript. See you there!

--

--

Carlos De La Lama-Noriega

Carlos is the CEO and founder of Startup Embassy, a coliving space in Silicon Valley with a global community of more than 2000 entrepreneurs in 90 countries