-
Notifications
You must be signed in to change notification settings - Fork 13
/
board.js
246 lines (219 loc) · 7.74 KB
/
board.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import {
ButtonBuilder,
ButtonStyle,
ChannelType,
ComponentType,
EmbedBuilder,
Message,
} from "discord.js";
import { guild } from "../client.js";
import { extractMessageExtremities, getBaseChannel, messageToText } from "../util/discord.js";
import { MessageActionRowBuilder } from "./types/ActionRowBuilder.js";
import CONSTANTS from "./CONSTANTS.js";
import Database from "./database.js";
import { censor } from "./moderation/automod.js";
import { userSettingsDatabase } from "../commands/settings.js";
import giveXp from "./xp.js";
export const BOARD_EMOJI = "🥔";
/** @param {import("discord.js").TextBasedChannel} [channel] */
export function boardReactionCount(channel) {
const COUNTS = { scradd: 2, devs: 6, modsPlus: 5, mods: 4, admins: 3, default: 8 };
if (process.env.NODE_ENV !== "production") return COUNTS.scradd;
const baseChannel = getBaseChannel(channel);
if (!baseChannel) return COUNTS.default;
if (baseChannel.isDMBased()) return COUNTS.mods;
if (baseChannel.parent?.id === "866028754962612294") return COUNTS.modsPlus; // The Cache!
return (
{
[CONSTANTS.channels.mod?.id || ""]: COUNTS.mods,
[CONSTANTS.channels.admin?.id || ""]: COUNTS.admins,
[CONSTANTS.channels.modmail?.id || ""]: COUNTS.mods,
[CONSTANTS.channels.devs?.id || ""]: COUNTS.devs,
[CONSTANTS.channels.boosters?.id || ""]: COUNTS.modsPlus,
[CONSTANTS.channels.youTube?.id || ""]: COUNTS.modsPlus,
}[baseChannel.id] || 8
);
}
if (!CONSTANTS.channels.board) throw new ReferenceError("Could not find board channel");
export const boardDatabase = new Database("board");
await boardDatabase.init();
/**
* @param {import("./database").Databases["board"] | import("discord.js").Message} info
* @param {{ pre?: ButtonBuilder[]; post?: ButtonBuilder[] }} [extraButtons]
*
* @returns {Promise<import("discord.js").BaseMessageOptions | undefined>}
*/
export async function generateBoardMessage(info, extraButtons = {}) {
const count =
info instanceof Message ? info.reactions.resolve(BOARD_EMOJI)?.count || 0 : info.reactions;
/** @param {import("discord.js").Message} message */
async function messageToBoardData(message) {
const { files, embeds } = await extractMessageExtremities(message, false);
const description = await messageToText(message);
const censored = censor(description);
const censoredName = censor(message.author.username);
const boardEmbed = new EmbedBuilder()
.setColor(message.member?.displayColor ?? 0)
.setDescription(censored ? censored.censored : description || null)
.setAuthor({
iconURL: (message.member ?? message.author).displayAvatarURL(),
name:
message.member?.displayName ??
(censoredName ? censoredName.censored : message.author.username),
})
.setTimestamp(message.createdAt);
const button = new ButtonBuilder()
.setLabel("View Context")
.setStyle(ButtonStyle.Link)
.setURL(message.url);
while (embeds.length > 9) embeds.pop(); // 9 and not 10 because we still need to add ours
return {
allowedMentions: { users: [] },
components: [
new MessageActionRowBuilder().addComponents(
...(extraButtons.pre || []),
button,
...(extraButtons.post || []),
),
],
content: `**${BOARD_EMOJI} ${count}** | ${
message.channel.isThread() && message.channel.parent
? `${
[CONSTANTS.channels.modmail?.id, CONSTANTS.channels.admin?.id].includes(
message.channel.parent.id,
)
? "#deleted-channel"
: message.channel.toString()
} (${message.channel.parent.toString()})`
: message.channel.toString()
} | ${message.author.toString()}`,
embeds: [boardEmbed, ...embeds],
files,
};
}
if (info instanceof Message) return messageToBoardData(info);
if (!CONSTANTS.channels.board) throw new ReferenceError("Could not find board channel");
const onBoard =
info.onBoard &&
(await CONSTANTS.channels.board.messages.fetch(info.onBoard).catch(() => {}));
if (onBoard) {
const linkButton = onBoard.components?.[0]?.components?.[0];
const buttons =
linkButton?.type === ComponentType.Button
? [
...(extraButtons.pre || []),
ButtonBuilder.from(linkButton),
...(extraButtons.post || []),
]
: [...(extraButtons.pre || []), ...(extraButtons.post || [])];
return {
allowedMentions: { users: [] },
components: buttons.length
? [new MessageActionRowBuilder().setComponents(buttons)]
: [],
content: onBoard.content,
embeds: onBoard.embeds.map((oldEmbed) => EmbedBuilder.from(oldEmbed)),
files: onBoard.attachments.map((attachment) => attachment),
};
}
const channel = await guild.channels.fetch(info.channel).catch(() => {});
if (!channel?.isTextBased()) return;
const message = await channel.messages.fetch(info.source).catch(() => {});
if (!message) return;
return messageToBoardData(message);
}
/**
* Update the count on a message on #potatoboard.
*
* @param {import("discord.js").Message} message
*/
export async function updateBoard(message) {
/** @type {Promise<any>[]} */
const promises = [];
const count = message.reactions.resolve(BOARD_EMOJI)?.count || 0;
const minReactions = boardReactionCount(message.channel);
const info = boardDatabase.data.find(({ source }) => source === message.id);
if (!CONSTANTS.channels.board) throw new ReferenceError("Could not find board channel");
const boardMessage =
info?.onBoard &&
(await CONSTANTS.channels.board?.messages.fetch(info.onBoard).catch(() => {}));
const pings =
userSettingsDatabase.data.find(({ user }) => user === message.author.id)?.boardPings ??
process.env.NODE_ENV === "production";
if (boardMessage) {
if (count < Math.max(Math.floor(minReactions - minReactions / 6), 0)) {
await boardMessage.delete();
} else {
await boardMessage.edit({
allowedMentions: pings ? undefined : { users: [] },
content: boardMessage.content.replace(/\d+/, `${count}`),
});
}
} else if (count >= minReactions) {
if (!CONSTANTS.channels.board) throw new ReferenceError("Could not find board channel");
promises.push(giveXp(message.member ?? message.author));
const boardMessage = await CONSTANTS.channels.board.send({
...(await generateBoardMessage(message)),
allowedMentions: pings ? undefined : { users: [] },
});
if (CONSTANTS.channels.board.type === ChannelType.GuildAnnouncement)
promises.push(boardMessage.crosspost());
boardDatabase.data = info
? boardDatabase.data.map((item) =>
item.source === message.id
? { ...item, onBoard: boardMessage.id, reactions: count }
: item,
)
: [
...boardDatabase.data,
{
reactions: count,
user: message.author.id,
channel: message.channel.id,
source: message.id,
onBoard: boardMessage.id,
},
];
}
if (boardMessage || count < minReactions) {
boardDatabase.data = count
? boardMessage
? boardDatabase.data.map((item) =>
item.source === message.id ? { ...item, reactions: count } : item,
)
: [
...boardDatabase.data,
{
channel: message.channel.id,
onBoard: 0,
reactions: count,
source: message.id,
user: message.author.id,
},
]
: boardDatabase.data.filter((item) => item.source !== message.id);
}
const top = [...boardDatabase.data.sort((a, b) => b.reactions - a.reactions)];
top.splice(5);
promises.push(
Promise.all(
top.map(async ({ onBoard }) => {
const toPin =
onBoard &&
(await CONSTANTS.channels.board?.messages.fetch(onBoard)?.catch(() => {}));
toPin && (await toPin.pin());
return onBoard;
}),
).then((top) => {
CONSTANTS.channels.board?.messages.fetchPinned().then(async (pins) => {
return (
pins.size > 5 &&
(await Promise.all(
pins.map(async (pin) => !top.includes(pin.id) && (await pin.unpin())),
))
);
});
}),
);
await Promise.all(promises);
}