Create a Telegram Bot in Seconds: The Ultimate Step-by-Step Guide
--
Hello, My name is Armin and I am thrilled that you are reading my first programming tutorial on Medium! In this tutorial, I’ll be using a CLI tool I developed to create a Telegram bot with a range of capabilities. This tool makes a well-structured template with boilerplate code and all you need to do is to add you commands or functionality you have in mind into the bot, no further headache of setting up everything yourself! So, let’s dive into it.
• Workplace Set up:
To start a project create a new directory and give it a name, then open up a terminal and run the following command:
npm i -g create-telebot-app
This will install the CLI app, which will make it easy to generate a boilerplate project, Don’t miss the -g
flag as it is a CLI app that has to be accessible globally in the command line. I made this myself by the way!🍑
Once it’s installed run the following:
npx create-telebot-app
Now you’ll be prompted to choose between a full or basic template. for now, we’ll go with the full template which comes with a database and built-in commands. So Choose “Full-Template (Including Database and pre-made Control commands)” using the arrow keys.
After selecting a template, choose a name for your project. you can either:
- type a name, then a folder will be created and the project set up inside it.
- just type a single dot to create inside the current directory
Now give it a few seconds to set up and install the dependencies.
After the workplace has been set up, create a new bot and paste the API TOKEN inside of .env
.
NOTE: The full template includes a built-in database, administration system, and commands. The admin system enables you to add admins who can control important commands like adding or removing bot users to the blacklist. When you run the bot using npm start
for the first time, the database will be automatically created.
All database jobs are handled inside /modifiers/text.js
so be careful while editing it.
• Bot configuration
.env
file is the heart of your bot, here’s what you should know about its content:
- API_KEY: the API token of your bot.
- SKIP_COMMANDS_ON_TEXT: In Telebot, all defined commands will be treated as text events which means that both the text event function and the function of the defined command will be triggered when a user sends the message, to avoid text event triggering the bot commands set ‘SKIP_COMMANDS_ON_TEXT’ to ‘true’.
- ADMINS: This is used to specify who can access the admin commands of the bot, and to specify an admin, write their numeric user IDs separated by commas.
- LOG_CHANNEL_ID: the numeric channel ID where the bot will send its error logs, starts with a minus sign (e.g., ‘-10012112121212’).
- DATABASE_FILENAME: Name of the database file which will be created and used for the bot. The bot will check for the provided name, if a database file already exists it will be used otherwise a new file will be created.
• Usage
- Set the API_KEY in
.env.
- Find your numeric user id and set it as admin in
.env
. - Make sure DATABASE_FILENAME has a name and
.sqlite3
extension. - run
npm start
.
After everything has been loaded you should see [bot.info] bot started
in the console which means the bot is ready to use.
• Adding commands:
to add a command create a file inside /commands
directory and give it a name.
All commands must be exported as below:
module.exports = {
name: 'command_name', // or ['command1', 'command2']
async execute(bot, msg, args) {
// command code
}
}
• Adding events:
to add an event create a file inside /events
directory and give it a name.
All events must be exported as below:
module.exports = {
name: 'text', // or events -> ['text', 'video']
execute(bot, msg) {
// event code
}
}
The bot will only trigger events defined in the Telebot documentation. Any unsupported events will not be triggered by the bot.
• Adding modifiers
to add a modifier create a file inside /modifiers
directory and give it a name.
All modifiers must be exported as below:
module.exports = {
name: 'text', // which defined event you'd like to manipulate its data before passing it to its event.
execute(bot, data) {
return data; // Must be returned
}
}
What are modifiers? In Telebot modifiers let you manipulate the data of any event before it is passed into it. for instance let’s say a user sends the text message “Hello” to your bot, and inside your text event file events/text.js
you have logged the message to the console. you can access the data before it is accessed by the text event function.
// modifiers/text.js
module.exports = {
name: 'text', // which defined event you'd like to manipulate its data before passing it to its event.
execute(bot, data) {
const msg = data.message
msg.text = `🍑 ${msg.text}`
return data; // Must be returned
}
}
Now “🍑 Hello” will be passed to the text event and gets printed into the console, as simple as that.
• Practice
Now that you learned how to set up and configure a project, It’s time to put your knowledge to test with create-telebot-app.
After creating a project and configuring the .env
, create a command file: /commands/define.js
and copy and paste the code below into it.
const axios = require('axios');
module.exports = {
name: 'define',
async execute(bot, msg, args) {
const query = args[0];
const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${query}`;
try {
const res = await axios.get(url);
const data = res.data[0];
const word = data.word;
const allTypes = data.meanings.flatMap(meaning => meaning.partOfSpeech);
const antonyms = data.meanings.flatMap(meaning => meaning.antonyms);
const allDefinitions = data.meanings.flatMap(meaning => meaning.definitions.map(obj => `→*${obj.definition}*\n \t\t${obj.example ? `example: ${obj.example}` : ""}\n\n`));
const synonyms = data.meanings.flatMap(meaning => meaning.synonyms);
const userResponse = `
*word*: ${word}
*all types*: ${allTypes.join(", ")}
*all definitions*: \n${allDefinitions.join("")}
*synonyms*: ${synonyms}
*antonyms*: ${antonyms}
`;
await msg.reply.text(userResponse, {
asReply: true,
parseMode: "markdown"
});
} catch (error) {
console.log(error);
}
}
};
The Dictionary API is used to retrieve data about a particular word such as its meaning, synonyms, antonyms, etc. For instance, after implementing the above command in your bot and sending /define hello
to it, It will send a get request to the API and fetch the information about the word “hello”, the sample output should be as below:
word: hello
all types: noun, verb, interjection
all definitions:
→"Hello!" or an equivalent greeting.
→To greet with "hello".
→A greeting (salutation) said when meeting someone or acknowledging someone’s arrival or presence.
example: Hello, everyone.
→A greeting used when answering the telephone.
example: Hello? How may I help you?
→A call for response if it is not clear if anyone is present or listening, or if a telephone conversation may have been disconnected.
example: Hello? Is anyone there?
→Used sarcastically to imply that the person addressed or referred to has done something the speaker or writer considers to be foolish.
example: You just tried to start your car with your cell phone. Hello?
→An expression of puzzlement or discovery.
example: Hello! What’s going on here?
synonyms: greeting
antonyms: bye,goodbye
As simple as that! you just made a dictionary bot using create-telebot-app! This shows the power of this tool and how it can simplify the process of building a bot. Just imagine having to handle all the commands, events, modifiers, database selection, and integration, user data management, blacklisting, database coding, admin systems, error handling, folder structure, and many other challenges that come with building a bot from scratch all by yourself! With create-telebot-app, you can avoid these headaches and focus on just implementing the main functionality.
• Conclusion
CTA(create-telebot-app) is a great tool for creating simple to complex Telegram bots which comes with a built-in administration system and database. It saves you time by creating a template project for you in which all the hard parts are already done. the practice was just to show you a sample use of commands. By now you should have learned how to set up and configure a project with CTA and you should be able to add commands, events, and modifiers easily.
Thanks for reading this tutorial! Hope this tool prevents the headaches you might have if you had decided to make a bot without ever reading this article😎.
If you found this tutorial beneficial, please leave a clap to support me in creating more content.