Telegraf JS: Library for creating telegram bot using Javascript
Humehr Sanatkar
Posted on January 14, 2024
We can use any programming languages for develop a telegram bot like PHP, C#, Python...
in this article we used JavaScript for develop telegram bot.
1- In first we need to install Nodejs and NPM (Link).
2- Next step, create an directory so open Terminal or CMD on your project directory, so run this command:
npm init --y
3- For develop, we need TelegrafJS library. So run this command:
npm i --save telegraf
4- create index.js file
5- open project on your code editor like VSCode, Notepad++, ...
6- open index.js and write the following code:
const {Telegraf} = requrie("telegraf")
const bot = new Telegraf("YOUR_BOT_TOKEN")
// When user send /start command
bot.start((ctx) => ctx.reply('Welcome'))
bot.launch();
7- For run bot, write and run this command on terminal:
node .
Extra information about TelegrafJS and documentation: TelegrafJS Doc
Example
I create a simple bot for check user join to telegram channel or no
const { Telegraf } = require('telegraf');
// Replace 'YOUR_BOT_TOKEN' with your Telegram Bot API token
const bot = new Telegraf('YOUR_BOT_TOKEN');
// Middleware function to check if a user has joined a channel
function checkChannelJoin(ctx, next) {
const channelId = '@YourChannelUsername'; // Replace with your channel's username or ID
const userId = ctx.from.id;
// Check if the user is a member of the channel
bot.telegram.getChatMember(channelId, userId)
.then((chatMember) => {
if (chatMember.status === 'member' || chatMember.status === 'creator' || chatMember.status === 'administrator') {
// User is a member of the channel
console.log(`User is a member of the channel.`);
next();
} else {
// User is not a member of the channel
console.log(`User ${userId} is not a member of the channel.`);
ctx.reply(`
Please join our channel to access the bot functionality.
${channelId}
`);
}
})
.catch((error) => {
console.log('Error:', error);
ctx.reply('Oops! Something went wrong. Please try again later.');
});
}
// Command handler for '/start' command
bot.command('start', checkChannelJoin, (ctx) => {
ctx.reply('Welcome to the bot!');
});
// Start the bot
bot.launch();
Note: This script, when the user send /start command in your bot, checks whether the user has subscribed to your Telegram channel (using the middleware), if yes, it executes the next step and Otherwise, it requires the user to join.
Posted on January 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.