This repository was archived by the owner on Jun 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathask.js
More file actions
60 lines (55 loc) · 1.5 KB
/
ask.js
File metadata and controls
60 lines (55 loc) · 1.5 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
exports.handler = (event, context, callback) => {
let axios = require('axios')
let qs = require('querystring')
//trim off white space from the body
let { text } = qs.parse(event.body)
let params = qs.stringify({
site: 'stackoverflow.com',
sort: 'votes',
pagesize: 5,
q: text,
})
let respond = body =>
callback(null, {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
// if the text value is null just send a response skip the api call.
if (!text) {
respond({
response_type: 'in_channel',
text:
'Woops! Looks like you forgot your question! Correct format: `/ask <question_here>`',
})
} else {
axios
.get(`https://api.stackexchange.com/search/advanced?${params}`)
.then(({ data }) => {
respond({
response_type: 'in_channel',
text: `Perhaps one of these links can help!
${data.items
.map(q => {
let title = unescapeHtml(q.title)
return `⬆️ *${q.score.toLocaleString()}* - <${q.link}|${title}>`
})
.join('\n')}`,
})
})
.catch(error => respond({ text: error.message }))
}
}
function unescapeHtml(text) {
let entities = require('./entities.json')
return text.replace(/&\w+;/g, match => {
for (const key of Object.keys(entities)) {
if (key === match) {
return entities[match]['characters']
}
}
return match
})
}