Below is the code. When my code runs for the first time it works like a charm, but when I again input the URL and click on any of the buttons it shows me 2 pics (1 pic is from the previous result), and for 3rd time it shows 3 pics (2 pics are from the previous result) and so on. So, when I again input the URL, it should only work once. With the below screenshots, you can understand my problem better.
When codes run for the first time
When it runs again with the same URL
When it runs for 3rd time with different URL
So, to solve the issue what is the best possible option
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
const fetch = require("node-fetch");
const token = process.env.TOKEN;
const bot = new TelegramBot(token, {
polling: true
})
bot.onText(/\/yt/, async (message, match) => { //ontext takes regex
if (match.input === "/yt") {
await bot.sendMessage(message.chat.id, "No input")
} else {
const url = match.input.split(' ')[1];
if (url.match(/v=(\w|-|_)+/g)) {
var idOfVid = url.match(/v=(\w|-|_)+/g);
idOfVid = idOfVid[0].slice(2);
fetch(`${accessYoutubeApi}${idOfVid}`)
.then(res => res.json())
.then(async (data) => {
titleOfVideo = data.items[0].snippet.title;
channelOfVideo = data.items[0].snippet.channelTitle;
if (url != undefined) {
if (/(www.youtube.com)/gm.test(url)) {
await bot.sendMessage(message.chat.id, `${titleOfVideo}
${channelOfVideo}
Select the photo size :`, {
reply_markup: {
inline_keyboard: [
[{
text: "120x90",
callback_data: "default"
},
{
text: "320x180",
callback_data: 'medium'
},
{
text: "480x360",
callback_data: 'high'
},
{
text: "640x480",
callback_data: 'standard'
},
{
text: "1280x720",
callback_data: 'maxres'
}
]
]
}
})
bot.on("callback_query", function callback(callBackQuery) {
callBackData = callBackQuery.data;
thumbnails = data.items[0].snippet.thumbnails;
if (callBackData == "default") {
bot.sendPhoto(message.chat.id, thumbnails.default.url, {
caption: "120x90"
});
} else if (callBackData == "medium") {
bot.sendPhoto(message.chat.id, thumbnails.medium.url, {
caption: "320x180"
})
} else if (callBackData == "high") {
bot.sendPhoto(message.chat.id, thumbnails.high.url, {
caption: "480x360"
})
} else if (callBackData == 'standard') {
bot.sendPhoto(message.chat.id, thumbnails.standard.url, {
caption: "640x480"
})
} else if (callBackData == 'maxres') {
bot.sendPhoto(message.chat.id, thumbnails.maxres.url, {
caption: "1280x720"
})
}
/*bot.answerCallbackQuery(callBackQuery.id)
.then((e) => {
if (callBackData.command == idOfVid) {
bot.sendMessage(message.chat.id, "Wait for few seconds, may take some time");
bot.sendPhoto(message.chat.id, thumbnails[callBackData].url)
}
})*/
})
} else {
bot.sendMessage(message.chat.id, `Invalid URL
If you are providing the URL of youtube video make sure while pasting the URL before /yt don't write any character.
If you have provided the perfect URL, please try again.`)
}
}
})
} else {
bot.sendMessage(message.chat.id, 'Invalid URL')
}
}
})