This repository has been archived by the owner on Jan 17, 2023. It is now read-only.
generated from stacks-network/.github
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
388 lines (368 loc) · 16.5 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
const Discord = require('discord.js');
const client = new Discord.Client({ partials: Object.values(Discord.Constants.PartialTypes) });
const { mod_message_init, mod_queue, send_guidelines, log, send_roaster } = require('./constants/messages/message_mod/index'),
{ createPendingItem } = require('./app/controllers/PendingItems'),
{ Status, PendingItem, Vote, VoteRequirement, Guideline, RoleRule } = require('./app/models'),
{ formatGuidelineMessages } = require('./app/lib/util'),
moment = require('moment')
module.exports = client
client.on('ready', async (msg) => {
// delete community guideline messages
await client.channels.cache.get(process.env.COMMUNITY_GUIDELINE_CHANNEL_ID).messages.fetch() // Fetch last 100 messages
.then(messages => {
messages.forEach((message) => {
message.delete()
})
})
// delete roaster messages
await client.channels.cache.get(process.env.ROASTER_CHANNEL_ID).messages.fetch() // Fetch last 100 messages
.then(messages => {
messages.forEach((message) => {
message.delete()
})
})
let role = client.guilds.cache.get(process.env.MOD_CHANNEL_ID).roles.cache.find(role => role.name === "CM1");
let text = `React to enroll as a community manager.\n Current Role :\n`;
role.members.forEach(user => {
text += `${user}\n`
});
Promise.all([client.channels.cache.get(process.env.ROASTER_CHANNEL_ID).send(send_roaster(client, text)).then(sentEmbed => {
sentEmbed.react("📝")
})])
// Send the quidelines
const guidelines = await Guideline.query().eager('action.voteRequirement')
Promise.all(guidelines.map(g => client.channels.cache.get(process.env.COMMUNITY_GUIDELINE_CHANNEL_ID).send(send_guidelines(client, formatGuidelineMessages(g))).then(sentEmbed => {
sentEmbed.react("📝")
})))
});
const events = {
MESSAGE_REACTION_ADD: 'messageReactionAdd',
MESSAGE_REACTION_REMOVE: 'messageReactionRemove',
};
client.on('message', async (message, user) => {
// consider only DMs to bot
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
let regex = new RegExp(expression);
if (message.content.match(regex)) {
const messageIDs = message.content.split('/')
const messgaeId = messageIDs[messageIDs.length - 1]
const channelId = messageIDs[messageIDs.length - 2]
const guildId = messageIDs[messageIDs.length - 3]
if (messgaeId.length === 18 && channelId.length === 18 && guildId.length === 18) {
client.channels.cache.get(channelId).messages.fetch(messgaeId).then(async msg => {
return await createPendingItemAction(messgaeId, message.author.id, msg.author.id, guildId, channelId, msg.content, message.author)
})
}
}
})
client.on('messageReactionRemove', async (reaction, user) => {
// removing myself from role
if (reaction.message.channel.id === process.env.ROASTER_CHANNEL_ID && reaction._emoji.name === '📝') {
let role = reaction.message.guild.roles.cache.find(role => role.name === "CM1");
reaction.message.guild.members.fetch(user.id).then(async (member) => {
if (member.roles.cache.find(r => r.name === "CM1")) {
await member.roles.remove(role);
updateRoasterRoles(reaction, user);
}
})
return
}
})
client.on('messageReactionAdd', async (reaction, user) => {
// updating roles here
if (reaction.message.channel.id === process.env.ROASTER_CHANNEL_ID && reaction._emoji.name === '📝') {
let role = reaction.message.guild.roles.cache.find(role => role.name === "CM1");
const roleRule = await RoleRule.query().findOne({ role_id: role.id })
if (!user.bot) {
let now = moment()
let joined = moment(reaction.message.channel.guild.members.cache.get(user.id).joinedTimestamp)
// check for no of days in sever
if ((now.diff(joined, 'days') > roleRule.days_in_server)) {
user.send({
embed: {
color: 3447003,
author: {
name: 'Blockstack',
icon_url: client.user.avatarURL
},
description: `Sorry, you have not been part of the server long enough. This role requires you to be part of this server for ${roleRule.days_in_server} days.`,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "© Blockstack"
}
}
})
return
}
}
// check for maximum roles in server
if (role.members.size >= roleRule.max_allowed) {
user.send({
embed: {
color: 3447003,
author: {
name: 'Blockstack',
icon_url: client.user.avatarURL
},
description: `Sorry, we currently do not have any open ${role.name} positions. Please check back at a later time.`,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "© Blockstack"
}
}
})
return
}
reaction.message.guild.members.fetch(user.id).then(async (member) => {
await member.roles.add(role);
updateRoasterRoles(reaction, user);
})
return
}
// if 📝 was reacted in Community channel
if (reaction.message.channel.id === process.env.COMMUNITY_GUIDELINE_CHANNEL_ID) {
checkEmojiActions(reaction, user)
return
}
if (reaction._emoji.name === '🚩') {
let author_id = reaction.message.author && reaction.message.author.id
if (reaction.message.partial) {
let message = await reaction.message.fetch()
author_id = message.author.id
}
return await createPendingItemAction(reaction._emoji.reaction.message.id, user.id, author_id, reaction.message.guild.id, reaction.message.channel.id, reaction.message.content, user)
} else if (reaction.emoji.name === '👍') {
let message = await reaction.message.fetch()
if (user.bot) {
return
}
if (reaction.message.channel.id === process.env.MOD_QUEUE_CHANNEL_ID) {
return await onApproveMessage(message.id, reaction, user)
}
return await sendToMOdQueue(message.id, reaction, user)
// Take message ID that it was reacted too... and compare with DB `pending items`. If we have item that
// matches and status === 'setup', then.. change status to 'pending'. Send another message to use
// stating: "Thank you for confirming, we have put your message in the mod queue".
//
// Actions To Take:
// - Send message to user
// - Send message to #mod-queue
// -- "{user_id} has flagged message {message_id}. The message was: {message_body}. 👍 to confirm, 👎 to decline"
} else if (reaction.emoji.name === '👎') {
// Take message ID that it was reacted too... and compare with DB `pending items`. If we have item that
// matches and status === 'setup', then.. change status to 'canceled'. Send another message to use
// stating: "Your request has been canceled".
let message = await reaction.message.fetch()
if (user.bot) {
return
}
if (reaction.message.channel.id === process.env.MOD_QUEUE_CHANNEL_ID) {
return await rejectAction(message.id, reaction, user)
}
const setup = await Status.query().findOne({ title: 'setup' })
const wasItemFound = await PendingItem.query().findOne({ status_id: setup.id, reference_message_id: message.id })
if (wasItemFound) {
return await cancelAction(wasItemFound, reaction, user)
}
} else {
// Nothing yet
}
});
// Log our bot in using the token from https://discord.com/developers/applications/me
client.login(process.env.SERVER_ID);
function checkEmojiActions(reaction, user) {
let emoji = reaction._emoji
if (!user.bot && emoji.name == '📝') {
// send instructions to the user how to copy the message id
user.send({
embed: {
color: 3447003,
author: {
name: 'Blockstack',
icon_url: client.user.avatarURL
},
description: `I see you are looking to remove a message. Please reply with the message link. Here are instructions on how to do that:`,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "© Blockstack"
}
}
})
}
}
async function createPendingItemAction(reference_message_id, action_taker_user_id, message_sender_id, message_guild_id, channel_id, message, user) {
const status = await Status.query().findOne({ title: 'setup' })
await createPendingItem({
status_id: status.id,
reference_message_id,
action_taker_user_id,
message_sender_id,
message_guild_id,
channel_id,
})
user.send({
embed: {
color: 3447003,
author: {
name: 'Blockstack',
icon_url: client.user.avatarURL
},
description: `I see that you want to report the following message: ${message}.Message ID: #${reference_message_id}`,
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "© Blockstack"
}
}
}).then(sentEmbed => {
sentEmbed.react("👍");
sentEmbed.react("👎");
}).catch((e) => {
console.log(e)
console.log('something went wrong');
});
}
async function onApproveMessage(message_id, reaction, user) {
let m_id = message_id.split('.')[0]
const statuses = await Status.query()
const pending = statuses.find(f => f.title === 'pending')
const approved = statuses.find(f => f.title === 'approved')
const pendingItem = await PendingItem.query().findOne({ reference_message_id: m_id, status_id: pending.id })
let vote_count = pendingItem.vote_count
if (!vote_count) {
vote_count = 1
} else {
vote_count += 1
}
const vouteRequirement = await VoteRequirement.query().findOne({}, qb => {
qb.joinRelation('action').where(qb1 => {
qb1.where(`action.title`, '=', 'Flag') // Change the action type if Required
})
})
if (vote_count === vouteRequirement.number_of_votes) {
// if the count is 2, delete the reported message.
client.channels.cache.get(pendingItem.channel_id).messages.fetch(pendingItem.reference_message_id).then(message => message.delete())
// delete the mod queue message as well
reaction.message.delete()
// log mod queue message into activity log
await PendingItem.query().patchAndFetchById(pendingItem.id, { status_id: approved.id })
client.users.cache.get(pendingItem.message_sender_id).send({
embed: {
color: 3447003,
author: {
name: 'Blockstack',
icon_url: client.user.avatarURL
},
description: 'Your message has been deleted.',
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "© Blockstack"
}
}
})
client.channels.cache.get(process.env.ACTIVITY_LOG_CHANNEL_ID).send(log(client, `message #${pendingItem.reference_message_id} was deleted from #${pendingItem.channel_id}.`))
}
const updateVoteCount = await PendingItem.query().patchAndFetchById(pendingItem.id, { vote_count })
return await Vote.query().insert({ user_id: user.id, approved: true, pending_item_id: pendingItem.id })
}
async function sendToMOdQueue(message_id, reaction, user) {
const setup = await Status.query().findOne({ title: 'setup' })
const wasItemFound = await PendingItem.query().findOne({ status_id: setup.id, reference_message_id: message_id })
if (wasItemFound) {
const pending = await Status.query().findOne({ title: 'pending' })
user.send({
embed: {
color: 3447003,
author: {
name: 'Blockstack',
icon_url: client.user.avatarURL
},
description: 'Thank you for confirming, we have put your message in the mod queue',
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "© Blockstack"
}
}
})
client.channels.cache.get(wasItemFound.channel_id).messages.fetch(wasItemFound.reference_message_id).then(message => {
client.channels.cache.get(process.env.MOD_QUEUE_CHANNEL_ID).send(mod_queue(client, user, message_id, message)).then(sentEmbed => {
sentEmbed.react("👍");
sentEmbed.react("👎");
}).catch((e) => {
console.log(e)
console.log('something went wrong 1');
});
})
return await PendingItem.query().patchAndFetchById(wasItemFound.id, { status_id: pending.id })
}
}
async function rejectAction(message_id, reaction, user) {
let m_id = message_id.split('.')[0]
const statuses = await Status.query()
const pending = statuses.find(f => f.title === 'pending')
const rejected = statuses.find(f => f.title === 'rejected')
const pendingItem = await PendingItem.query().findOne({ reference_message_id: m_id, status_id: pending.id })
let vote_count = pendingItem.vote_count
const vouteRequirement = await VoteRequirement.query().findOne({}, qb => {
qb.joinRelation('action').where(qb1 => {
qb1.where(`action.title`, '=', 'Flag') // Change the action type if Required
})
})
if (!vote_count) {
vote_count = -1
} else {
vote_count -= 1
}
if (vote_count === -(vouteRequirement.number_of_votes)) {
await PendingItem.query().patchAndFetchById(pendingItem.id, { status_id: rejected.id })
}
// delete the mod queue message as well
reaction.message.delete()
// log mod queue message into activity log
client.channels.cache.get(process.env.ACTIVITY_LOG_CHANNEL_ID).send(log(client, `message #${m_id} was not deleted because it was voted down.`))
const updateVoteCount = await PendingItem.query().patchAndFetchById(pendingItem.id, { vote_count })
return await Vote.query().insert({ user_id: user.id, approved: false, pending_item_id: pendingItem.id })
}
async function cancelAction(wasItemFound, reaction, user) {
const canceled = await Status.query().findOne({ title: 'canceled' })
user.send({
embed: {
color: 3447003,
author: {
name: 'Blockstack',
icon_url: client.user.avatarURL
},
description: 'Your request has been canceled',
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: "© Blockstack"
}
}
})
return await PendingItem.query().patchAndFetchById(wasItemFound.id, { status_id: canceled.id })
}
const updateRoasterRoles = async (reaction, user) => {
if (!user.bot) {
// delete roaster messages
await client.channels.cache.get(process.env.ROASTER_CHANNEL_ID).messages.fetch() // Fetch last 100 messages
.then(messages => {
messages.forEach((message) => {
message.delete()
})
})
let role = reaction.message.guild.roles.cache.find(role => role.name === "CM1");
let text = `React to enroll as a community manager.\n Current Role :\n`;
role.members.forEach(user => {
text += `${user}\n`
});
Promise.all([client.channels.cache.get(process.env.ROASTER_CHANNEL_ID).send(send_roaster(client, text)).then(sentEmbed => {
sentEmbed.react("📝")
})])
}
}