diff --git a/src/WikiBattle.js b/src/WikiBattle.js index f6752c6..ca4c60b 100644 --- a/src/WikiBattle.js +++ b/src/WikiBattle.js @@ -117,7 +117,8 @@ export default class WikiBattle extends EventEmitter { async sendHint () { debug('sending hint for', this.goal) const page = await wiki.get(this.goal) - this.emitSocket('hint', page.getHint()) + const hint = await page.getHint() + this.emitSocket('hint', hint) } /** diff --git a/src/wiki.js b/src/wiki.js index 993ac0f..58a59cb 100644 --- a/src/wiki.js +++ b/src/wiki.js @@ -1,7 +1,6 @@ import qs from 'querystring' import fs from 'fs' import fetch from 'node-fetch' -import * as cheerio from 'cheerio' const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')) @@ -43,19 +42,21 @@ class WikiPage { * Extract a short hint text from the article content. */ - getHint () { - try { - const hint = cheerio('.mw-parser-output > p', this.content) - .filter((i, el) => cheerio(el).text().trim() !== '') - .first() - .text() - .replace(/\[\d+]/gm, '') - return hint.length > HINT_LENGTH - ? `${hint.substr(0, HINT_LENGTH)}…` - : hint - } catch (e) { - return `(Could not load hint: [${e.message}])` - } + async getHint () { + const query = qs.stringify({ + action: 'query', + format: 'json', + prop: 'extracts', + titles: this.title, + exchars: HINT_LENGTH.toString(), + explaintext: true + }) + + const response = await fetch(`https://en.wikipedia.org/w/api.php?${query}`) + const body = await response.json() + const hint = Object.values(body.query.pages)[0].extract + return hint + .replace(/\[((Note )?\d+|\w)]/gmi, '') } /**