To create a Telegram bot using the Telegraf library, you'll need to follow these steps:
Prerequisites
1. Node.js: Make sure you have Node.js installed. If you don't have it, download and install it from here.
2. Telegram Bot Token: You'll need a bot token from Telegram. You can create one by messaging BotFather on Telegram, following its instructions, and getting your token.
Steps to Create a Telegraf Bot
1. Initialize a Node.js Project
Create a new folder for your bot, open it in your terminal, and run:
mkdir my-telegraf-bot
cd my-telegraf-bot
npm init -y
2. Install Dependencies
You need to install the Telegraf library:
npm install telegraf
3. Create the Bot Script
Create a file called bot.js in your project folder:
touch bot.js
Now, open this file and paste the following code to set up your basic bot:
const { Telegraf } = require('telegraf');
// Replace 'YOUR_BOT_TOKEN' with your bot token from BotFather
const bot = new Telegraf('YOUR_BOT_TOKEN');
// Responds to the /start command
bot.start((ctx) => {
ctx.reply('Welcome! I am your bot. How can I assist you today?');
});
// Responds to the /help command
bot.help((ctx) => {
ctx.reply('Send me a message, and I will repeat it!');
});
// Echoes whatever the user sends
bot.on('text', (ctx) => {
ctx.reply(`You said: ${ctx.message.text}`);
});
// Start the bot
bot.launch().then(() => {
console.log('Bot is running...');
});
4. Run Your Bot
Once your bot script is ready, run it using the following command:
node bot.js
You should see the message Bot is running... in your terminal, meaning your bot is now live.
5. Interact with Your Bot
Go to Telegram, search for your bot by its username, and start chatting! Your bot will reply based on the commands you defined (/start, /help, and echoing text messages).
#js #Javascript
@officalZenith