-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.js
88 lines (78 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const {
MessageActionRow,
Message,
MessageEmbed,
MessageButton,
} = require("discord.js");
/**
* Creates a pagination embed
* @param {Interaction} interaction
* @param {MessageEmbed[]} pages
* @param {MessageButton[]} buttonList
* @param {number} timeout
* @returns
*/
const paginationEmbed = async (
interaction,
pages,
buttonList,
timeout = 120000
) => {
if (!pages) throw new Error("Pages are not given.");
if (!buttonList) throw new Error("Buttons are not given.");
if (buttonList[0].style === "LINK" || buttonList[1].style === "LINK")
throw new Error(
"Link buttons are not supported with discordjs-button-pagination"
);
if (buttonList.length !== 2) throw new Error("Need two buttons.");
let page = 0;
const row = new MessageActionRow().addComponents(buttonList);
//has the interaction already been deferred? If not, defer the reply.
if (interaction.deferred == false) {
await interaction.deferReply();
}
const curPage = await interaction.editReply({
embeds: [pages[page].setFooter({ text: `Page ${page + 1} / ${pages.length}` })],
components: [row],
fetchReply: true,
});
const filter = (i) =>
i.customId === buttonList[0].customId ||
i.customId === buttonList[1].customId;
const collector = await curPage.createMessageComponentCollector({
filter,
time: timeout,
});
collector.on("collect", async (i) => {
switch (i.customId) {
case buttonList[0].customId:
page = page > 0 ? --page : pages.length - 1;
break;
case buttonList[1].customId:
page = page + 1 < pages.length ? ++page : 0;
break;
default:
break;
}
await i.deferUpdate();
await i.editReply({
embeds: [pages[page].setFooter({ text: `Page ${page + 1} / ${pages.length}` })],
components: [row],
});
collector.resetTimer();
});
collector.on("end", (_, reason) => {
if (reason !== "messageDelete") {
const disabledRow = new MessageActionRow().addComponents(
buttonList[0].setDisabled(true),
buttonList[1].setDisabled(true)
);
curPage.edit({
embeds: [pages[page].setFooter({ text: `Page ${page + 1} / ${pages.length}` })],
components: [disabledRow],
});
}
});
return curPage;
};
module.exports = paginationEmbed;