UNPKG

message-buttons-pagination

Version:

A simple but useful module to add paginator buttons to your embeds

74 lines (64 loc) 2.56 kB
const { ActionRowBuilder, Message, EmbedBuilder, ButtonBuilder } = require('discord.js') const Discord = require('discord.js') /** * Creates a messageCreate Pagination Embed * @param { Message } msg * @param { EmbedBuilder[] } pages * @param { ButtonBuilder[] } buttons * @param { number } timeout * @returns */ const msgEmbed = async (msg, pages, buttons, timeout = 120000) => { if(!msg && !msg.channel) throw new Error("Unsupported Channel!") if(!pages) throw new Error("Pages are not Given!") if(!buttons) throw new Error("Buttons are not given!") if(buttons[0].style === Discord.ButtonStyle.Link || buttons[1].style === Discord.ButtonStyle.Link) { throw new Error( "Links Buttons are not allowed with the message-buttons-pagination!" ) } if(buttons.length !== 2) throw new Error ("You need three buttons: (`previous` `delete` `next`)"); let page = 0 const row = new ActionRowBuilder().addComponents(buttons); const curPage = await msg.channel.send({ embeds: [pages[page].setFooter({ text: `Pagina ${page + 1} de ${pages.length}` })], components: [row], }); const filter = (i) => i.customId === buttons[0].customId || i.customId === buttons[1].customId; const collector = await curPage.createMessageComponentCollector({ filter, time: timeout, }); collector.on("collect", async (i) => { switch (i.customId) { case buttons[0].customId: page = page > 0 ? --page : pages.length - 1; break; case buttons[1].customId: page = page + 1 < pages.length ? ++page : 0; break; default: break; } await i.deferUpdate() await i.editReply({ embeds: [pages[page].setFooter({ text: `Pagina ${page + 1} de ${pages.length}` })], components: [row], }); collector.resetTimer(); }); collector.on("end", () => { if(!curPage.delete) { const disRow = new ActionRowBuilder().addComponents( buttons[0].setDisabled(true), buttons[1].setDisabled(true) ); curPage.edit({ embeds: [pages[page].setFooter({ text: `Pagina ${page + 1} de ${pages.length}` })], components: [disRow], }); } }); return curPage; }; module.exports = msgEmbed;