Telegram bot
2 min readApr 21, 2022
https://www.section.io/engineering-education/telegram-bot-in-nodejs/
npm init
# install the telegraf library
npm install telegrafconst {Telegraf} = require('telegraf');const bot = new Telegraf('<token>');//method for invoking start command
bot.command('talk', ctx => {
console.log(ctx.from)
bot.telegram.sendMessage(ctx.chat.id, 'hello there! Welcome to my new telegram bot.', {
})
})bot.command('status', ctx => {
console.log(ctx.from)
bot.telegram.sendMessage(ctx.chat.id, 'Active.', {
})
})bot.launch();
souravmandalm@gmail.com
Session #2
sending images
const bot = new Telegraf('<token>');//method for invoking start command
bot.command('talk', ctx => {
console.log(ctx.from)
bot.telegram.sendMessage(ctx.chat.id, 'hello there! Welcome to my new telegram bot.', {
})
})bot.command('status', ctx => {
console.log(ctx.from)
bot.telegram.sendMessage(ctx.chat.id, 'Active.', {
})
})bot.hears('dog', ctx => {
bot.telegram.sendPhoto(ctx.chat.id, {
source: "res/dog.jpeg"
})
})bot.launch();
Session #3
bot.hears('options', ctx => {
bot.telegram.sendMessage(ctx.chat.id, `Morning or Evening`, {
reply_markup: {
inline_keyboard: [
[{
text: "Morning",
callback_data: 'morning'
},
{
text: "Evening",
callback_data: 'evening'
}
],]
}
})
})bot.action('morning', ctx => {
bot.telegram.sendMessage(ctx.chat.id, "Good Morning!")
})
bot.action('evening', ctx => {
bot.telegram.sendMessage(ctx.chat.id, "Good Evening!")
})
next session
//method that displays the inline keyboard buttons
bot.hears('animals', ctx => {
console.log(ctx.from)
let animalMessage = `great, here are pictures of animals you would love`;
ctx.deleteMessage();
bot.telegram.sendMessage(ctx.chat.id, animalMessage, {
reply_markup: {
inline_keyboard: [
[{
text: "dog",
callback_data: 'dog'
},
{
text: "cat",
callback_data: 'cat'
}
],
]
}
})
})
//method that returns image of a dog
bot.action('dog', ctx => {
bot.telegram.sendPhoto(ctx.chat.id, {
source: "res/dog.jpeg"
})
})
//method that returns image of a cat
bot.action('cat', ctx => {
bot.telegram.sendPhoto(ctx.chat.id, {
source: "res/cat.jpeg"
})
})
How to send to all users
I guess looping through all ids is the only option.
//method to start get the script to pulling updates for telegram
bot.launch();