Skip to content

Commit

Permalink
Use Wikimedia extracts API to retrieve hints (#278)
Browse files Browse the repository at this point in the history
Furthermore, filter out more references from hints.
  • Loading branch information
Lichtschalter-5000 authored Oct 15, 2024
1 parent f3e153f commit 2b59dcb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 15 deletions.
3 changes: 2 additions & 1 deletion src/WikiBattle.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

/**
Expand Down
29 changes: 15 additions & 14 deletions src/wiki.js
Original file line number Diff line number Diff line change
@@ -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'))

Expand Down Expand Up @@ -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, '')
}

/**
Expand Down

0 comments on commit 2b59dcb

Please sign in to comment.