Код бота
Яconst TeleBot = require('telebot')
const bot = new TeleBot('тут ничего нет');
const chanellID = '-1001411019233';
const adminChatID = '-366998052';
// const chanellID = '-1001249115624';
// const adminChatID = '-398912261';
const API = 'https://thecatapi.com/api/images/get?format=src&type=';
let prevMessageGroup = 0;
let kittensArray = new Map();
let notes = [];
let quequeArray = [];
let fixState = false;
bot.on('*', function(msg){
console.log(`\n`);
console.log(msg);
console.log(`\n`);
if(msg.chat.id == adminChatID){
if(msg.reply_to_message){
if(msg.sticker){
bot.sendSticker(msg.reply_to_message.forward_from.id, msg.sticker.file_id);
}
bot.sendMessage(msg.reply_to_message.forward_from.id, msg.text);
}
if(msg.text.match( /\/list(@nepidooooorbot)?/ )){
let msgArray = [`Список котеков на очереди:\n`];
for(let i = 0; i < notes.length; i++){
msgArray.push(`\nНа ${notes[i]['time']}, /del_${i + 1}`)
}
if(notes.length == 0){
msgArray.push('\nНа данный момент на очереди нет ни одного котека:(');
} else{
msgArray.push(`\n\nВсего ${notes.length}; Если хотите удалить котека из списка жмякайте del рядом с ним`);
}
bot.sendMessage(adminChatID, msgArray.join(''), {replyToMessage: msg.message_id});
}
if(msg.text.match( /\/del_(\d+).+?/ )){
let del = msg.text.match( /\/del_(\d+).+?/ );
if(notes.length == 0 || notes[del[1] - 1] == undefined){
bot.sendMessage(adminChatID, `Ошибка, похоже этого котека и так не существует:(`, {replyToMessage: msg.message_id});
} else{
notes.splice(del[1] - 1, 1);
bot.sendMessage(adminChatID, `Удалён котек под номером ${del[1]}`, {replyToMessage: msg.message_id});
}
}
if(msg.text.match( /\/send/ )){
if(msg.reply_to_message.photo){
bot.sendMessage(adminChatID, 'Уже на канале;)', { replyToMessage: msg.message_id })
return bot.sendPhoto(chanellID, msg.reply_to_message.photo[msg.photo.length-1].file_id, {serverDownload: true}).catch(error => {
console.log('ERROR', error);
});
} else if(msg.replyToMessage.document){
bot.sendMessage(adminChatID, 'Уже на канале;)', { replyToMessage: msg.message_id });
return bot.sendDocument(chanellID, msg.reply_to_message.document.file_id, {serverDownload: true}).catch(error => {
console.log('ERROR', error);
});
} else if(msg.reply_to_message.video){
bot.sendMessage(adminChatID, 'Уже на канале;)', { replyToMessage: msg.message_id });
return bot.sendVideo(chanellID, msg.reply_to_message.video.file_id, {serverDownload: true}).catch(error => {
console.log('ERROR', error);
});
} else{
return bot.sendMessage(adminChatID, 'Произошла ошибка: не могу запостить(', { replyToMessage: msg.message_id });
}
}
if(msg.text == '/random'){
let randomNum = Math.floor(Math.random()*100);
if (randomNum % 2) {
bot.sendPhoto(msg.chat.id, API + 'jpg', {
fileName: 'kitty.jpg',
serverDownload: true,
replyToMessage: msg.message_id
}).catch(error => {
console.log('ERROR', error)
});;
} else {
bot.sendDocument(msg.chat.id, API + 'gif#', {
fileName: 'kitty.gif',
serverDownload: true,
replyToMessage: msg.message_id
}).catch(error => {
console.log('ERROR', error)
});;
}
}
if(msg.text == '/time' && msg.reply_to_message){
if(msg.reply_to_message.photo || msg.reply_to_message.document){
msg.reply_to_message.caption = msg.text;
setTime(msg.reply_to_message);
}
}
}
if(msg.text == '/start'){
return bot.sendMessage(msg.from.id, 'Приветствую тебя, любитель котиков\nХоть я и бездушная машина и не могу написать симфонию но зато с большой радостью могу переслать твоих котиков моим создателям)\nУже жду твоих пушистиков:3\nP.S. Всё что ты напишешь в этом чате сразу попадает к админам такшо смотри мне, никаких дикпиков', { replyToMessage: msg.message_id });
}
if (isGroup(msg)){return};
msgForward(msg);
});
bot.on('edit', function(msg){
if(msg.chat.id == adminChatID && msg.caption){
setTime(msg);
}
});
bot.on(['photo','video','document'], function(msg){
if(msg.chat.id == adminChatID && msg.caption){
setTime(msg);
}
if(msg.media_group_id){
quequeArray.push(msg);
}
if(msg.media_group_id == prevMessageGroup && prevMessageGroup != undefined){return}
prevMessageGroup = msg.media_group_id;
return bot.sendMessage(msg.from.id, 'Хороший котек, очень милый!(надеюсь это котек:D)', { replyToMessage: msg.message_id });
});
bot.sendMessage(adminChatID, 'Бот был перезапущен и не будет отвечать на кнопочки выше, список котеков был обнулён');
bot.start();
function isGroup(msg){
if(msg.chat.id < 0 && msg.chat.id != adminChatID) return true;
};
function msgForward(msg){
if(msg.chat.id == adminChatID){return}
if(msg.photo || msg.document || msg.video){
if(msg.media_group_id){
console.log('mediagroup');
} else{
var replyMarkup = bot.inlineKeyboard([
[
bot.inlineButton('Да', {callback: `/yes ${kittensArray.size + 1}`}),
bot.inlineButton('Нет', {callback: `/no ${kittensArray.size + 1}`})
],
[
bot.inlineButton('Опубликовать с таймером', {callback: `/timer ${kittensArray.size + 1}`})
]]);
bot.forwardMessage(adminChatID, msg.chat.id, msg.message_id).catch(error => {
console.log('ERROR', error);
}).then(re => {
kittensArray.set(kittensArray.size + 1, msg);
bot.sendMessage(adminChatID, `Новый котек(выше) \nОпубликовать?`, {replyMarkup});
});
}
} else{
bot.forwardMessage(adminChatID, msg.chat.id, msg.message_id).catch(error => {
console.log('ERROR', error)
});
}
bot.on('callbackQuery', query => {
if(/\/yes (.+)/.test(query.data)){
if(kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).photo){
bot.sendPhoto(chanellID, kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).photo[msg.photo.length-1].file_id,{
caption: `Прислал(а) ${kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).from.first_name} через @koteki_nya_nya_nya_bot`,
serverDownload: true
}).catch(error => {
console.log('ERROR', error);
});
} else if(kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).document){
bot.sendDocument(chanellID, kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).document.file_id,{
caption: `Прислал(а) ${kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).from.first_name} через @koteki_nya_nya_nya_bot`,
serverDownload: true
}).catch(error => {
console.log('ERROR', error);
});
} else{
bot.sendVideo(chanellID, kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).video.file_id,{
caption: `Прислал(а) ${kittensArray.get(parseInt(query.data.match(/\/yes (.+)/)[1])).from.first_name} через @koteki_nya_nya_nya_bot`,
serverDownload: true
}).catch(error => {
console.log('ERROR', error);
});
}
kittensArray.delete(parseInt(query.data.match(/\/yes (.+)/)[1]));
bot.editMessageText({chatId: query.message.chat.id , messageId: query.message.message_id}, `Уже опубликовано!`).catch(error => {
console.log('ERROR', error);
});
let see = bot.inlineKeyboard([[bot.inlineButton('Посмотреть', {url: 't.me/koteki_nya_nya_nya'})]]);
bot.editMessageReplyMarkup({chatId: query.message.chat.id , messageId: query.message.message_id}, {replyMarkup: see}).catch(error => {
console.log('ERROR', error);
});
}
if(/\/no (.+)/.test(query.data)){
kittensArray.delete(parseInt(query.data.match(/\/no (.+)/)[1]));
bot.editMessageText({chatId: query.message.chat.id , messageId: query.message.message_id}, `Ну нет так нет...`).catch(error => {
console.log('ERROR', error);
});
let noMarkup = bot.inlineKeyboard([[]]);
bot.editMessageReplyMarkup({chatId: query.message.chat.id , messageId: query.message.message_id}, {replyMarkup: noMarkup}).catch(error => {
console.log('ERROR', error);
});
}
if(/\/timer (.+)/.test(query.data)){
bot.editMessageText({chatId: query.message.chat.id , messageId: query.message.message_id}, `Ответь на это сообщение временем(начинать с /timе) когда нужно запостить котека`).catch(error => {
console.log('ERROR', error);
});
let noMarkup = bot.inlineKeyboard([[]]);
bot.editMessageReplyMarkup({chatId: query.message.chat.id , messageId: query.message.message_id}, {replyMarkup: noMarkup}).catch(error => {
console.log('ERROR', error);
});
bot.on(/time (.+)(\n(.+))?/, function(mesge){
if(mesge.reply_to_message.message_id == query.message.message_id){
kittensArray.get(parseInt(query.data.match(/\/timer (.+)/)[1])).caption = `Прислал(а) ${ kittensArray.get(parseInt(query.data.match(/\/timer (.+)/)[1])).from.first_name} через @koteki_nya_nya_nya_bot`;
let time = mesge.text.match( /time (.+)(\n(.+))?/ );
if( /^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$/.test(time[1]) == false ){
bot.sendMessage(adminChatID, `Неверный формат даты, попробуйте ещё разок или отредактируйте дату в уже отправленном сообщении`, {replyToMessage: mesge.message_id});
} else{
if(time[2]){
kittensArray.get(parseInt(query.data.match(/\/timer (.+)/)[1])).caption = time[2];
}
notes.push({'time': time[1], 'msg': kittensArray.get(parseInt(query.data.match(/\/timer (.+)/)[1]))});
bot.sendMessage(adminChatID, `Понял-принял, отправлю точно в ${time[1]} \nПосмотреть список котеков на очереди: /list`, {replyToMessage: mesge.message_id});
kittensArray.delete(parseInt(query.data.match(/\/timer (.+)/)[1]));
}
}
})
}
bot.answerCallbackQuery(query.id);
});
}
function setTime(msg){
let time = (msg.caption) ? msg.caption.match( /time (.+)(\n(.+))?/ ) : msg.text.match( /time (.+)(\n(.+))?/ );
if( /^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$/.test(time[1]) == false ){
bot.sendMessage(adminChatID, `Неверный формат даты, попробуйте ещё разок или отредактируйте дату в уже отправленном сообщении`, {replyToMessage: msg.message_id});
} else{
if(time[2]){
msg.caption = time[2];
}
notes.push({'time': time[1], 'msg': msg});
bot.sendMessage(adminChatID, `Понял-принял, отправлю точно в ${time[1]} \nПосмотреть список котеков на очереди: /list`, {replyToMessage: msg.message_id});
}
}
setInterval(function(){
if(!fixState && quequeArray.length > 0){
fixState = true;
setTimeout(mediaGroupFix, 1000);
}
for (let i = 0; i < notes.length; i++){
let hours = new Date().getHours();
let minutes = new Date().getMinutes();
if(hours < 10){hours = `0${hours}`};
if(minutes < 10){minutes = `0${minutes}`}
let curDate = `${hours}:${minutes}`;
if ( notes[i]['time'] == curDate ) {
if(notes[i]['msg'].photo){
bot.sendPhoto(chanellID, notes[i]['msg'].photo[notes[i]['msg'].photo.length-1].file_id, {caption: notes[i]['msg'].caption, serverDownload: true});
} else if(notes[i]['msg'].document){
bot.sendDocument(chanellID, notes[i]['msg'].document.file_id, {caption: notes[i]['msg'].caption, serverDownload: true});
} else{
bot.sendVideo(chanellID, notes[i]['msg'].video.file_id, {caption: notes[i]['msg'].caption, serverDownload: true});
}
bot.sendMessage(adminChatID, 'Отправлено!', {replyToMessage: notes[i]['msg'].message_id});
notes.splice(i,1);
}
}
},1000);
function mediaGroupFix(){
if(quequeArray.length == 0){return};
let msg = quequeArray[quequeArray.length - 1];
var replyMarkup = bot.inlineKeyboard([
[
bot.inlineButton('Да', {callback: `/yes ${kittensArray.size + 1}`}),
bot.inlineButton('Нет', {callback: `/no ${kittensArray.size + 1}`})
],
[
bot.inlineButton('Опубликовать с таймером', {callback: `/timer ${kittensArray.size + 1}`})
]]);
bot.forwardMessage(adminChatID, msg.chat.id, msg.message_id).catch(error => {
console.log('ERROR', error);
}).then(re => {
quequeArray.splice(quequeArray.length - 1, 1);
bot.sendMessage(adminChatID, 'Новый котек(выше) \nОпубликовать?', {replyMarkup}).then(re => {
kittensArray.set(kittensArray.size + 1, msg);
if(quequeArray.length == 0){
fixState = false;
return;
}
mediaGroupFix();
});
});
}