-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot-utils.ts
More file actions
342 lines (296 loc) · 8.56 KB
/
bot-utils.ts
File metadata and controls
342 lines (296 loc) · 8.56 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import * as cheerio from 'cheerio';
import Discord, {
AttachmentBuilder,
Client,
Message,
TextChannel,
WebhookClient,
} from 'discord.js';
import dayjs from 'dayjs';
import CONSTANTS from './constants';
import Blog from './templates/Announcement_Blog';
import C3Update from './templates/Announcement_C3';
import { database } from './firebase';
import { ref, get, set, child } from 'firebase/database';
const WEBHOOK_NAME = 'Message duplication';
const isDev = process.env.NODE_ENV === 'development';
export const duplicateMessage = async (
toChannel: TextChannel,
content: string,
user: {
username: string;
avatarURL: () => string | null;
},
attachments: { url: string; name?: string }[] = []
) => {
try {
// Fetch existing webhooks
const webhooks = await toChannel.fetchWebhooks();
// Find our webhook
let webhook = webhooks.find((w) => w.name === WEBHOOK_NAME);
// Create if missing
if (!webhook) {
if (webhooks.size >= 10) {
throw new Error('Webhook limit reached in channel');
}
webhook = await toChannel.createWebhook({
name: WEBHOOK_NAME,
});
}
// Build files
const files =
attachments.length > 0
? attachments.map(
(a) =>
new AttachmentBuilder(a.url, {
name: a.name ?? 'attachment',
})
)
: undefined;
// Send duplicated message
const message = await webhook.send({
content: content || undefined,
username: user.username,
avatarURL: user.avatarURL() ?? undefined,
files,
});
return message;
} catch (error) {
console.error('[duplicateMessage]', error);
return null;
}
};
/**
* @param client
* @param permissions
* @param msg
* @return {string|boolean}
*/
export const hasPermissions = (client, permissions, msg) => {
const hasRole = msg.member.roles.cache.some((role) =>
permissions.roles.map((r) => r.id).includes(role.id)
); // stop and return true if predicate match
const isInChannel =
permissions.channels.includes(CONSTANTS.CHANNELS.ANY) ||
permissions.channels.includes(msg.channel.id) ||
msg.channel.id === CONSTANTS.CHANNELS.PRIVATE_TESTS ||
msg.channel.id === CONSTANTS.CHANNELS.TEST;
console.log('isInChannel', isInChannel);
if (hasRole && isInChannel) return true;
if (!hasRole) return 'You are not permitted to use this command!';
if (!isInChannel)
return `Wrong channel! This command is available only in ${permissions.channels.map((chan) => `<#${chan}>`)}`;
console.log('Another error happened');
return false;
};
/**
*
* @param {Discord.Message} sent
* @param type
* @return {Promise<void>}
*/
export const addReactions = async (sent, type = 'dismiss') => {
try {
const voteUp = sent.guild.emojis.resolve('276908986744438794');
const alfred = sent.guild.emojis.resolve('626417707373428750');
const princess = sent.guild.emojis.resolve('626417707373428750');
await sent.react(voteUp);
if (type === 'c3') {
await sent.react(alfred);
} else if (type === 'promo') {
//
} else if (type === 'server_news') {
//
} else {
await sent.react(princess);
}
} catch (e) {
console.error('Cannot add reactions', e);
}
};
export const checkBlogPosts = async (client) => {
const scirraStaff = ['Laura_D', 'Ashley', 'Tom'];
try {
const headers = new Headers();
headers.append('User-Agent', process.env.USER_AGENT);
const resp = await fetch('https://www.construct.net/en/blogs/posts', {
headers,
});
const body = await resp.text();
const $ = cheerio.load(body);
const common = $(
'form#form1 div:nth-child(3) > div:nth-child(1) > div > div'
);
const newTitle = common
.find('.titleOuterWrap > div > div.right > a')
.text()
.trim();
const author = common
.find('.statWrap .detailCol .usernameTextWrap a > span:nth-child(1)')
.text();
// .text().trim();
const timeToRead = common
.find('.statWrap > div:nth-child(1) > div > ul > li:nth-child(2)')
.text()
.replace(/<img(.*)>/, '')
.replace('read time', '')
.trim();
const link = common
.find('.titleOuterWrap > div > div.right > a')
.attr('href')
.trim()
.replace(/^(.*?)\/blogs/, 'https://www.construct.net/blogs');
const image = common.find('.statWrap .avatarWrap > img').attr('src');
const newPostId = link.split('?')[0].split('/').pop().split('-').pop();
console.log('new blog Post Id', newPostId);
const dbRef = ref(database);
get(child(dbRef, 'blog')).then(async (snapshot) => {
const postId = snapshot.val();
const isScirra = scirraStaff.includes(author);
// prevent posts that are not from scirra to prevent spam
if (postId !== newPostId && newTitle !== '' && isScirra) {
const sent = (
(await client.channels.cache.get(
isScirra
? CONSTANTS.CHANNELS.SCIRRA_ANNOUNCEMENTS
: CONSTANTS.CHANNELS.PROMO
)) as TextChannel
).send({
content: isScirra ? '@here' : '',
embeds: [
new Blog({
title: newTitle,
author,
timeToRead,
link,
image,
}).embed(),
],
});
await addReactions(sent, 'blog');
set(ref(database, 'blog'), newPostId);
}
});
} catch (e) {
console.error(e);
}
};
type Release = {
releaseName: string;
shortDescription: string;
viewDetailsURL: string;
branchName: 'Beta' | 'Stable' | 'LTS';
publishDate: string;
};
export const checkC3Updates = async (client: Client) => {
try {
console.log('Checking C3 updates');
const resp = await fetch('https://editor.construct.net/versions.json');
const data = (await resp.json()) as Release[];
const branches = ['Beta', 'Stable', 'LTS'];
let latestRelease: Release;
// Iterate through all releases and identify the latest release based on publishDate
for (const release of data) {
const branch = release.branchName;
if (branches.includes(branch)) {
if (
!latestRelease ||
new Date(release.publishDate) > new Date(latestRelease.publishDate)
) {
latestRelease = release;
}
}
}
if (!latestRelease) {
console.log('No releases found');
return;
}
const snapshot = await get(child(ref(database), 'c3release'));
const lastRelease = snapshot.val();
const snap = await get(child(ref(database), 'releases'));
const listReleases = snap.val();
const newVersion = latestRelease.releaseName;
const description = latestRelease.shortDescription;
const url = latestRelease.viewDetailsURL;
const branch = latestRelease.branchName;
console.log('last release:', lastRelease, ', new version', newVersion);
if (isDev) {
console.log('New C3 release available');
console.log({
description,
version: newVersion,
link: url,
icon: branch === 'Stable' ? 'C3Stableicon' : 'C3Betaicon',
});
}
// release different from latest, not empty, not already posted
if (
lastRelease !== newVersion &&
newVersion !== '' &&
!listReleases[newVersion]
) {
console.log('New C3 release available');
const sent = (
(await client.channels.cache.get(
CONSTANTS.CHANNELS.SCIRRA_ANNOUNCEMENTS
)) as TextChannel
).send({
content: '@here',
embeds: [
new C3Update({
description,
version: newVersion,
link: url,
icon: branch === 'Stable' ? 'C3Stableicon' : 'C3Betaicon',
}).embed(),
],
});
await addReactions(sent, 'c3');
await set(ref(database, 'c3release'), newVersion);
listReleases[newVersion] = branch;
await set(ref(database, 'releases'), listReleases);
}
} catch (error) {
console.log(error);
//= > 'Internal server error ...'
}
};
export const checkForNotificationBot = async (message: Message) => {
if (message.channel.id === CONSTANTS.CHANNELS.SCIRRA_ANNOUNCEMENTS) {
// sent from the "notification" bot
await addReactions(message, 'notification');
}
};
export const crossPost = async (message: Message) => {
if (message.channel.id === CONSTANTS.CHANNELS.SCIRRA_ANNOUNCEMENTS) {
// sent from the news channel
await message.crosspost();
}
};
/**
*
* @param {Message} message
*/
export const checkForNewUsers = async (message: Message) => {
if (message.channel.id === CONSTANTS.CHANNELS.INTRODUCE_YOURSELF) {
await message.react('👋');
}
};
export const checkToolsHasLink = async (message: Message) => {
const toolsChan = CONSTANTS.CHANNELS.TOOLS;
if (message.channel.id === toolsChan) {
if (
message.content.search(
/[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_+.~#?&//=]*)?/gi
) === -1
) {
await message.delete();
await message.author.send(
'**Your content does not meet one or more requirements!**\n\n__List of requirements:__\n► **1** Link/embed or attachment'
);
}
}
};
export const checkJobOffers = async (message: Message) => {
return true;
};