In this case we are using javascript and Nodejs for develop the bot. Telegraf.js is a library that will helps to make it easy. First of all we need our api token of Telegram bot.
- Go to telegram and search BotFather (You have to choose the verified bot).
- Enter on the chat and send /start.
- We will recieve an info message and we have to answer /newbot.
- He will ask for a name and a username of the bot.
- Then you will have a congrats message with the token api. Should be something like 123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ.
- Be sure that have node.js installed.
npm install -g npm
Install Telegraf.js
$ npm install telegraf
In your directory create a main.js file and import telegraf.
const { Telegraf } = require('telegraf');Set the bot constant with your token directly (not recommended)1.
const bot = new Telegraf("TOKEN_API");or with environment variables.
const bot = new Telegraf(process.env.BOT_TOKEN);- You can use environment variables creating a .env file and inside write
BOT_TOKEN:"YOUR_TOKEN". - After install dotenv
npm install dotenv --save - Import dotenv to your main.js
require('dotenv').config();const { Telegraf } = require('telegraf');
const bot = new Telegraf(process.env.BOT_TOKEN);
bot.start((ctx) => ctx.reply('Welcome'));
bot.help((ctx) => ctx.reply('Send me a sticker'));
bot.on('sticker', (ctx) => ctx.reply('👍'));
bot.hears('hi', (ctx) => ctx.reply('Hey there'));
bot.launch();- For the first test. Run in your terminal
node main.js - Go to your Telegram app, search your bot chat and write
/start - After a change remember kill your process and run
node main.jsagain.
If you want use your bot on a group:
- Invite the bot to the group
- Give admin permissions to him
Footnotes
-
Is important dont share or upload your tokens or keys. Using .env is a easy method to put them safe. ↩