summaryrefslogtreecommitdiff
path: root/server/src/commands/fun/Fact
blob: c942b458622fee519927a4c2551c88a47b6a64ca (plain) (blame)
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
import { Command } from 'discord-akairo';
import { Message } from 'discord.js';
import request from 'node-superfetch';

export default class FactFun extends Command {
    public constructor() {
        super('fact', {
            aliases: ['fact', 'facts'],
            category: 'fun',
            description: {
                content: 'Grabs a  random fact.',
                usage: '',
                examples: [
                    ''
                ]
            },
            ratelimit: 3
        });
    }
    
    public async exec(msg: Message): Promise<Message> {
        const article = await this.randomWikipediaArticle();
        const body = await request.get('https://en.wikipedia.org/w/api.php')
            .query({
                action: 'query',
                prop: 'extracts',
                format: 'json',
                titles: article,
                exintro: '',
                explaintext: '',
                redirects: '',
                //@ts-ignore
                formatversion: 2
            })
            .catch(err => {
                console.error(err);
                msg.reply('Woops, there was an error regarding the (http://en.wikipedia.org) API.');
            });
        //@ts-ignore
        let fact = body.query.pages[0].extract;
        if (fact.length > 200) {
            const facts = fact.split('.');
            fact = `${facts[0]}.`;
            if (fact.length < 200 && facts.length > 1) fact += `${facts[1]}.`;
        }
        return msg.reply(fact);
    }
    
    public async randomWikipediaArticle() {
        const { body } = await request.get('https://en.wikipedia.org/w/api.php')
            .query({
                action: 'query',
                list: 'random',
                //@ts-ignore
                rnnamespace: 0,
                //@ts-ignore
                rnlimit: 1,
                format: 'json',
                //@ts-ignore
                formatversion: 2
            });
        //@ts-ignore
        if (!body.query.random[0].title) return 'Facts are hard to find sometimes.';
        //@ts-ignore
        return body.query.random[0].title;
    }
}