-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathwikipedia.coffee
74 lines (63 loc) · 2.28 KB
/
wikipedia.coffee
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
# Description:
# Wikipedia Public API
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot wiki search <query> - Returns the first 5 Wikipedia articles matching the search <query>
# hubot wiki summary <article> - Returns a one-line description about <article>
#
# Author:
# MrSaints
WIKI_API_URL = "https://en.wikipedia.org/w/api.php"
WIKI_EN_URL = "https://en.wikipedia.org/wiki"
module.exports = (robot) ->
robot.respond /wiki search (.+)/i, id: "wikipedia.search", (res) ->
search = res.match[1].trim()
params =
action: "opensearch"
format: "json"
limit: 5
search: search
wikiRequest res, params, (object) ->
if object[1].length is 0
res.reply "No articles were found using search query: \"#{search}\". Try a different query."
return
for article in object[1]
res.send "#{article}: #{createURL(article)}"
robot.respond /wiki summary (.+)/i, id: "wikipedia.summary", (res) ->
target = res.match[1].trim()
params =
action: "query"
exintro: true
explaintext: true
format: "json"
redirects: true
prop: "extracts"
titles: target
wikiRequest res, params, (object) ->
for id, article of object.query.pages
if id is "-1"
res.reply "The article you have entered (\"#{target}\") does not exist. Try a different article."
return
if article.extract is ""
summary = "No summary available"
else
summary = article.extract.split(". ")[0..1].join ". "
res.send "#{article.title}: #{summary}."
res.reply "Original article: #{createURL(article.title)}"
return
createURL = (title) ->
"#{WIKI_EN_URL}/#{encodeURIComponent(title)}"
wikiRequest = (res, params = {}, handler) ->
res.http(WIKI_API_URL)
.query(params)
.get() (err, httpRes, body) ->
if err
res.reply "An error occurred while attempting to process your request: #{err}"
return robot.logger.error err
handler JSON.parse(body)