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.
Top comments (6)
First time i know that we can develop a telegram bot using Js, thanks For This interesting article.
Glad you liked the article
Navigate to dev.to/settings/organization
Paste the secret code below and click Join Organization
Your secret code is:
ad0b7578f22434ee2fa3d40d3c9ef791056276a707b0af00f6f4894ccba4df047e1cb20d255e318c274356c780818de117fb
How to package it to run in Telegram? APK file?
No.
You can deploy on your server or,
Run it on localhost using this command:
Note: This command run server on localhost for handle user's requests on server-side
I hope answered you
I got it