-
Notifications
You must be signed in to change notification settings - Fork 12
/
app.js
212 lines (173 loc) · 6.04 KB
/
app.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
const Discord = require("discord.js");
const puppeteer = require('puppeteer');
const SimpleNodeLogger = require('simple-node-logger')
const config = require("./config.json");
const wikiRegex = /\[\[([^\[\]]*)\]\]|\[([^\[\]]*)\]/gu;
let log = SimpleNodeLogger.createSimpleLogger({
logFilePath: './logs/requests.log',
timestampFormat: 'YYYY-MM-DD HH:mm:ss'
});
let errorLog = SimpleNodeLogger.createSimpleLogger({
logFilePath: './logs/error.log',
timestampFormat: 'YYYY-MM-DD HH:mm:ss'
});
errorLog.setLevel('error');
var client;
function setup() {
client = new Discord.Client({
disableEveryone: true,
disabledEvents: ["TYPING_START"],
autoReconnect: true
});
client.login(config.token).then(() => {
console.log("Logged in");
}).catch(reason => errorLog.error(reason));
client.on("ready", () => {
console.log(`Ready as ${client.user.username}`);
});
client.on("message", (message) => {
if (message.author.bot) return;
let matches = wikiRegex.exec(message.cleanContent);
while (matches) {
match = matches[1];
if (match == undefined)
match = matches[2];
let target
if (match.startsWith("!"))
target = match.substr(1);
else
target = titleCase(match);
handleItem(target, message);
matches = wikiRegex.exec(message.cleanContent);
}
});
client.on("error", (error) => {
errorLog.log(error);
});
};
setup();
async function handleItem(itemName, message) {
var channel = message.channel;
var guildName = message.guild.name;
let itemUrlPart = convertToUrlString(itemName);
let url = config.wikiURL + itemUrlPart;
let initialMessage = "Retrieving details from the Wiki for **" + itemName + "**";
let messageId;
await channel.send(initialMessage)
.then(message => messageId = message.id)
.catch(error => {
errorLog.error(`"${error.message}" "${guildName}" "${itemName}"`);
});
if (messageId == null) return;
getImage(url, guildName).then(result => {
let outputString = '<' + url + '>';
if (!result.success) {
editMessage(channel, messageId, `Could not get details from the Wiki for **${itemName}**`);
setTimeout(function () {
channel.fetchMessage(messageId).then(message => {
message.delete();
}).catch(() => {
errorLog.error(`"Could not delete message ${messageId}" "${guildName}" "${outputString}"`);
});
}, 2000)
log.error(`"${guildName}" "${itemName}" "${url}" "INVALID PAGE"`);
return;
}
//log success
log.info(`"${guildName}" "${itemName}" "${url}"`);
if (result.textblock) {
outputString += `\n${result.textblock}`;
}
//if no screenshot, just edit the original message
if (!result.screenshot) {
editMessage(channel, messageId, outputString);
return;
}
//otherwise delete the message and create a new one with the screenshot
channel.fetchMessage(messageId).then(message => {
message.delete();
}).catch(() => {
errorLog.error(`"Could not delete message ${messageId}" "${guildName}" "${outputString}"`);
});
channel.send(outputString, { file: result.screenshot });
}).catch((reason) => {
errorLog.error(`"GetImage Failed" "${guildName}" "${reason}"`);
channel.fetchMessage(messageId).then(message => {
message.delete();
}).catch(() => {
errorLog.error(`"Could not delete message ${messageId}" "${guildName}" "${outputString}"`);
});
});
}
function editMessage(channel, messageId, content) {
channel.fetchMessage(messageId).then(message => {
message.edit(content);
}).catch(() => {
errorLog.error(`"Could not edit message ${messageId}" "${channel.guild.name}" "${content}"`);
});
}
async function getImage(url, guildName) {
let output = {
screenshot: false,
success: false
};
const browser = await puppeteer.launch({
ignoreHTTPSError: true,
headless: true,
handleSIGHUP: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
});
const page = await browser.newPage();
await page.setJavaScriptEnabled(config.enableJavascript); //Disabling Javascript adds 100% increased performance
await page.setViewport({ 'width': config.width, 'height': config.height }); //Set a tall page so the image isn't covered by popups
//played around with a few different waitUntils. This one seemed the quickest.
//If you don't disable Javascript on the PoE Wiki site, removing this parameter makes it hang
try {
await page.goto(url, { waitUntil: 'load' });
} catch (error) {
errorLog.error(`"${error.message}" "${guildName}" "${url}"`);
return output;
}
const invalidPage = await page.$(config.wikiInvalidPageSelector);
if (invalidPage && invalidPage !== null) return output;
output.success = true;
var paragraphs = await page.$(config.wikiParagraphsSelector);
if (await paragraphs.$(config.wikiInfoboxPageContainerSelector))
output.textblock = await page.evaluate(() => document.querySelector('#mw-content-text > .mw-parser-output > p:nth-of-type(2)').innerText);
else
output.textblock = await page.evaluate(() => document.querySelector('#mw-content-text > .mw-parser-output > p:nth-of-type(1)').innerText);
//remove newlines
output.textblock = output.textblock.replace(/[\n\r]/g, '');
async function getScreenshot(selector) {
const element = await page.$(selector);
if (!element)
return;
let screenshot = await element.screenshot();
await page.close();
await browser.close();
return screenshot;
}
output.screenshot = await getScreenshot(config.wikiInfoCardSelector);
if (output.screenshot) return output;
output.screenshot = await getScreenshot(config.wikiItemBoxSelector);
if (output.screenshot) return output;
output.screenshot = await getScreenshot(config.wikiTableSelector);
if (output.screenshot) return output;
await page.close();
await browser.close();
return output;
}
function convertToUrlString(name) {
return name.replace(/ /g, "_");
}
function titleCase(str) {
let excludedWords = ["of", "and", "the", "to", "at", "for", "league"];
str = str.toLowerCase();
let words = str.split(" ");
words.forEach((word, index) => {
if (index > 0 && excludedWords.includes(word))
return;
words[index] = word.charAt(0).toUpperCase() + word.substr(1);
})
return words.join(" ");
};