Telegram bot

sourav mandal
2 min readApr 21, 2022

--

https://www.section.io/engineering-education/telegram-bot-in-nodejs/

npm init

# install the telegraf library

npm install telegraf
const {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();

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

sourav mandal
sourav mandal

Written by sourav mandal

just a coder who forgets things so makes blogs so he can remember later

No responses yet

Write a response