Как сделать вывод случайных картинок без повторений в Telegram бота на JavaScript?
Вот код который выводит случайные картинки, но они повторяются. Что нужно исправить?
bot.on('message', (msg) => {
const chatId = msg.chat.id;
if (msg.text === 'Закрыть') {
bot.sendMessage(chatId, 'Закрываю клавиатуру', {
reply_markup: {
remove_keyboard: true,
},
});
} else if (msg.text === 'cccc') {
var random_img = ['c1.jpg', 'c2.jpg', 'c3.jpg'];
var foto = random_img[Math.floor(Math.random() * random_img.length)];
bot.sendPhoto(msg.from.id, foto);
} else if (msg.text === 'dddd') {
var random_img = ['d1.jpg', 'd2.jpg', 'd3.jpg'];
var foto = random_img[Math.floor(Math.random() * random_img.length)];
bot.sendPhoto(msg.from.id, foto);
} else {
bot.sendMessage(chatId, 'Клавиатура', {
reply_markup: {
keyboard: [
['Закрыть'],
['cccc', 'dddd']
],
},
});
}
});
Ответы (1 шт):
Автор решения: Aziz Umarov
→ Ссылка
Идея простая удаляйте уже отправленные картинки из массива. Только вот есть небольшие ньюансы, этот метод для единичного случая. Вам нужно будет хранить массивы отправленных фото в разрезе чатов если хотите чтобы фото повторялись по чатам но в одном чате нет
const img_c = ['c1.jpg','c2.jpg','c3.jpg'];
const img_d = ['d1.jpg','d2.jpg','d3.jpg'];
bot.on('message', msg => {
const chatId = msg.chat.id
if (msg.text === 'Закрыть') {
bot.sendMessage(chatId, 'Закрываю клавиатуру', {
reply_markup:{
remove_keyboard: true
}
})
} else if (msg.text === 'cccc') {
let foto = img_c[(Math.floor(Math.random() * img_c.length))];
let index = img_c.indexOf(foto);
if (index > -1) {
img_c.splice(index, 1);
bot.sendPhoto(msg.from.id, foto);
}
} else if (msg.text === 'dddd') {
let foto = img_d[(Math.floor(Math.random() * img_d.length))];
let index = img_d.indexOf(foto);
if (index > -1) {
img_d.splice(index, 1);
bot.sendPhoto(msg.from.id, foto);
}
} else {
bot.sendMessage(chatId, 'Клавиатура', {
reply_markup: {
keyboard:
[
['Закрыть'],
['cccc','dddd']
]
}
})
}
})