-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
476 lines (441 loc) · 16.4 KB
/
Copy pathindex.js
File metadata and controls
476 lines (441 loc) · 16.4 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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
const DTF = require("@eartharoid/dtf");
const dtf = new DTF();
const { MessageAttachment, MessageEmbed } = require("discord.js");
const axios = require("axios");
const url = require("url");
const moment = require("moment");
module.exports = (Plugin) =>
class DemoPlugin extends Plugin {
constructor(client, id) {
super(client, id, {
commands: [],
name: "Ticket Transcripts",
});
}
preload() {
this.config = this.client.config[this.id];
checkUpdates(this.client);
this.client.tickets.on("close", async (id) => {
const ticket = await this.client.db.models.Ticket.findOne({
where: { id },
});
if (!ticket) return;
const category = await this.client.db.models.Category.findOne({
where: { id: ticket.category },
});
if (!category) return;
const guild = await this.client.db.models.Guild.findOne({
where: { id: category.guild },
});
if (!guild) return;
if (this.config.disabled_servers || [].contains(String(guild.id)))
return this.client.log.warn(
`Ignoring ticket #${ticket.number} close because transcripts are disabled for guild with ID ${guild.id}`
);
const creator = await this.client.db.models.UserEntity.findOne({
where: {
ticket: id,
user: ticket.creator,
},
});
if (!creator)
return this.client.log.warn(
`Can't create text transcript for ticket #${ticket.number} due to missing creator`
);
const lines = [];
let closer;
let tempMap = new Map();
let ticketCreatedAt = dtf.fill(
"DD.MM.YYYY HH:mm:ss",
new Date(ticket.createdAt),
true
);
const channel_name = category.name_format
.replace(
/{+\s?(user)?name\s?}+/gi,
this.client.cryptr.decrypt(creator.display_name)
)
.replace(/{+\s?num(ber)?\s?}+/gi, ticket.number);
if (!this.config.disable_ascii) {
lines.push(
" _____ _ _ _ _____ _ _ \n |_ _(_) ___| | _____| |_ |_ _| __ __ _ _ __ ___ ___ _ __(_)_ __ | |_ ___ \n | | | |/ __| |/ / _ \\ __| | || '__/ _` | '_ \\/ __|/ __| '__| | '_ \\| __/ __|\n | | | | (__| < __/ |_ | || | | (_| | | | \\__ \\ (__| | | | |_) | |_\\__ \\\n |_| |_|\\___|_|\\_\\___|\\__| |_||_| \\__,_|_| |_|___/\\___|_| |_| .__/ \\__|___/\n |_| "
);
}
lines.push(
`Ticket Transcripts plugin v${
require("./package.json").version
} by AnonDev (https://anon.is-a.dev)\n-----------------------------------------------------------------------------------\nID: ${
ticket.number
} (#${channel_name})\nCategory: ${
category.name || "?"
}\nCreated (opened) by: ${this.client.cryptr.decrypt(
creator.username
)}#${creator.discriminator} (${
ticket.creator || "?"
})\nCreated (opened) at: ${ticketCreatedAt}`
);
if (ticket.closed_by) {
closer = await this.client.db.models.UserEntity.findOne({
where: {
ticket: id,
user: ticket.closed_by,
},
});
}
let ticketClosedAt = dtf.fill(
"DD.MM.YYYY HH:mm:ss",
new Date(ticket.updatedAt),
true
);
if (ticket.topic) {
lines.push(`Topic: ${this.client.cryptr.decrypt(ticket.topic)}`);
}
lines.push(`Closed at: ${ticketClosedAt}`);
if (closer) {
lines.push(
`Closed by: ${this.client.cryptr.decrypt(closer.username)}#${
closer.discriminator
} (${ticket.closed_by || "?"})`
);
}
if (ticket.closed_reason) {
lines.push(
`Close reason: ${this.client.cryptr.decrypt(ticket.closed_reason)}`
);
}
lines.push(
`-----------------------------------------------------------------------------------`
);
const messages = await this.client.db.models.Message.findAll({
where: { ticket: id },
});
for (const message of messages) {
const user = await this.client.db.models.UserEntity.findOne({
where: {
ticket: id,
user: message.author,
},
});
if (!user) continue;
const timestamp = dtf.fill(
"DD.MM.YYYY HH:mm:ss",
new Date(ticket.createdAt),
true
);
const username = this.client.cryptr.decrypt(user.username);
const display_name = this.client.cryptr.decrypt(user.display_name);
const data = JSON.parse(this.client.cryptr.decrypt(message.data));
let content = data.content ? data.content.replace(/\n/g, "\n\t") : "";
data.attachments?.forEach((a) => {
content += "\n\t[attachment] " + a.url;
});
data.embeds?.forEach(() => {
content += "\n\t[embedded content]";
});
lines.push(
`${
data.pinned ? "📌 " : ""
}[${timestamp}] ${display_name} (${username}#${
user.discriminator
}): ${content} ${message.deleted ? "(deleted) " : ""}${
message.edited ? "(edited) " : ""
}`
);
}
if (this.config.channels[guild.id]) {
try {
const g = await this.client.guilds.fetch(guild.id);
const embed = new MessageEmbed()
.setColor(guild.colour)
.setTitle(`Ticket Closed`)
.addField("ID", `\`${ticket.number}\` (#${channel_name})`, true)
.addField("Category", `${category.name || "?"}`, true)
.addField("Creator", `<@${ticket.creator}>`, true)
.addField(
"Created (opened) at",
`<t:${moment(new Date(ticket.createdAt)).format("X")}:f>`,
true
)
.setTimestamp()
.setFooter(guild.footer, g.iconURL());
if (ticket.topic) {
embed.addField(
"Topic",
`\`${this.client.cryptr.decrypt(ticket.topic)}\``,
true
);
}
embed.addField(
"Closed at",
`<t:${moment(new Date(ticket.updatedAt)).format("X")}:f>`,
true
);
if (closer) {
embed.addField("Closed by", `<@${ticket.closed_by}>`, true);
}
if (ticket.closed_reason) {
embed.addField(
"Close reason",
`\`${this.client.cryptr.decrypt(ticket.closed_reason)}\``,
true
);
}
const log_channel = await this.client.channels.fetch(
this.config.channels[guild.id]
);
if (!log_channel) return;
if (this.config.type && this.config.type == "attachment") {
const attachment = new MessageAttachment(
Buffer.from(lines.join("\n")),
channel_name + ".txt"
);
embed.addField(
"Transcript",
"*Uploaded as attachment below*",
true
);
tempMap.set("transcript", {
embeds: [embed],
files: [attachment],
});
}
if (this.config.type && this.config.type == "hastebin") {
const haste = await uploadToHastebin(
lines.join("\n"),
this.config.hastebin_url
? this.config.hastebin_url
: "https://hastebin.com",
"txt",
this.config.transcript_raw_url || false
).catch((err) => {
this.client.log.warn(
"Failed to upload ticket transcript to Hastebin"
);
this.client.log.error(err);
embed.addField(
":x: Error",
`Error while uploading transcript to Hastebin: \`${err.message}\`\nUploaded transcript as attachment below.`
);
tempMap.set("hastebin_error", true);
});
let hastebinerror = tempMap.get("hastebin_error") || null;
if (hastebinerror) {
const attachment = new MessageAttachment(
Buffer.from(lines.join("\n")),
channel_name + ".txt"
);
tempMap.set("transcript", {
embeds: [embed],
files: [attachment],
});
tempMap.delete("hastebin_error");
} else {
embed.addField(
"Transcript",
`*Uploaded to Hastebin* - [here](${haste})`,
true
);
tempMap.set("transcript", { embeds: [embed] });
}
}
if (this.config.type && this.config.type == "pastebin") {
if (!this.config.pastebin_api_key)
return this.client.log.warn(
"You have not provided Pastebin API key so I can't upload ticket transcript to Pastebin"
);
const paste = await uploadToPastebin(
lines.join("\n"),
this.config.pastebin_api_key,
"text",
`Ticket Transcript #${ticket.number}`,
this.config.transcript_raw_url || false
).catch((err) => {
this.client.log.warn(
"Failed to upload ticket transcript to Pastebin"
);
this.client.log.error(err);
embed.addField(
":x: Error",
`Error while uploading transcript to Pastebin: \`${err.message}\`\nUploaded transcript as attachment below.`
);
tempMap.set("pastebin_error", true);
});
let pastebinerror = tempMap.get("pastebin_error") || null;
if (pastebinerror) {
const attachment = new MessageAttachment(
Buffer.from(lines.join("\n")),
channel_name + ".txt"
);
tempMap.set("transcript", {
embeds: [embed],
files: [attachment],
});
tempMap.delete("pastebin_error");
} else {
embed.addField(
"Transcript",
`*Uploaded to Pastebin* [here](${paste})`,
true
);
tempMap.set("transcript", { embeds: [embed] });
}
}
let transcript = tempMap.get("transcript") || null;
if (!transcript)
return this.client.log.warn("Transcript object is missing");
log_channel.send(transcript);
} catch (error) {
this.client.log.warn(
"Failed to send ticket transcript to the guild's log channel"
);
this.client.log.error(error);
}
if (this.config.send_to_user && this.config.send_to_user == true) {
try {
const user = await this.client.users.fetch(ticket.creator);
let transcript = tempMap.get("transcript") || null;
if (!transcript)
return this.client.log.warn(
"Transcript object is missing in tempMap"
);
if (this.config.send_transcript_to_user == false) {
let transcriptembed = transcript.embeds[0];
transcriptembed.fields.pop();
let transcript2 = transcriptembed;
if (!transcript2)
return this.client.log.warn(
"Transcript2 (log embed without transcript) object is missing"
);
user.send({ embeds: [transcriptembed] });
} else {
console.log("send transcript to user is enabled");
user.send(transcript);
}
} catch (error) {
this.client.log.warn(
"Failed to send ticket transcript to the ticket creator"
);
this.client.log.error(error);
}
}
}
});
}
load() {}
};
const uploadToHastebin = async (text, domain, format, raw_url) => {
let response = await axios
.post(`${domain}/documents`, text, {
headers: { "Content-Type": "text/plain" },
})
.catch(function (error) {
if (error.response)
throw new Error(
`Could not POST to ${domain}/documents (status: ${error.response.status}) - ${error.response.data}`
);
throw new Error(
`Could not POST to ${domain}/documents - ${error.message}`
);
});
const { key } = await response.data;
if (!key)
throw new Error(
`Key is missing in response object (status ${response.status})`
);
const parsedURL = `${domain}/${key}.${format ? format : "txt"}`;
if (raw_url ? raw_url : null == true)
return `${domain}/raw/${key}.${format ? format : "txt"}`;
// this.client.log.info(`Uploaded transcript to hastebin server`, parsedURL)
return parsedURL;
};
const uploadToPastebin = async (text, apikey, format, title, raw_url) => {
const params = new URLSearchParams();
params.append("api_option", "paste");
params.append("api_dev_key", apikey);
params.append("api_paste_code", text);
params.append("api_paste_private", 1);
params.append("api_paste_name", title ? title : "Untitled Paste");
params.append("api_paste_format", format);
let response = await axios
.post(`https://pastebin.com/api/api_post.php`, params, {})
.catch(function (error) {
if (error.response)
throw new Error(
`Could not POST to Pastebin (status: ${error.response.status}) - ${error.response.data}`
);
throw new Error(`Could not POST to Pastebin - ${error.message}`);
});
const key = await response.data;
if (!key)
throw new Error(`Response data is missing (status ${response.status})`);
if (!key.includes("https://pastebin.com/"))
throw new Error(
`Response data is not valid Pastebin URL (${response.data})`
);
const parsedURL = key;
// this.client.log.info(`Uploaded transcript to Pastebin`, parsedURL)
if (raw_url ? raw_url : null == true)
return `https://pastebin.com/raw/${parsedURL.split("/")[3]}`;
return parsedURL;
};
const isValidUrl = (s, protocols) => {
const { URL } = require("url");
try {
url = new URL(s);
return protocols
? url.protocol
? protocols.map((x) => `${x.toLowerCase()}:`).includes(url.protocol)
: false
: true;
} catch (err) {
return false;
}
};
const checkUpdates = async (client) => {
const boxen = require("boxen");
const link = require("terminal-link");
const semver = require("semver");
const { format } = require("leekslazylogger");
const json = (
await axios({
method: "GET",
url: "https://api.github.com/repos/AnonDev-org/discord-tickets_transcripts/releases",
responseType: "json",
})
).data;
const { version: current } = require("./package.json");
const update = json[0];
const latest = semver.coerce(update.tag_name);
if (!semver.valid(latest)) return;
if (semver.lt(current, latest)) {
client.log.notice(
`There is an update available for Ticket Transcripts plugin by AnonDev (${current} -> ${update.tag_name})`
);
const lines = [
`&k&6You are currently using &c${current}&6, the latest is &a${update.tag_name}&6.&r`,
`&k&6Download "&f${update.name}&6" from&r`,
link(
"&k&6the GitHub releases page.&r&6",
"https://github.com/AnonDev-org/discord-tickets_transcripts/releases/"
),
];
console.log(
boxen(format(lines.join("\n")), {
align: "center",
borderColor: "yellow",
borderStyle: "round",
margin: 1,
padding: 1,
})
);
}
};
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
};