Closed groowyCZ closed 2 years ago
Code tested only separately from the bot in NPM runkit. Further testing recommended.
Code tested in NPM runkit:
require('request') const request = require("request-promise") class TestVehicle { constructor() { this.XKCD_BASE_URL = "https://xkcd.com/"; this.XKCD_API_SUFFIX = "/info.0.json"; } async apiRequest(location) { return await request({ uri: this.XKCD_BASE_URL + location, json: true, headers: { 'User-Agent': 'WilsonBot', }, }); } parseComic(xkcdResponseJSON) { let comic = {}; comic.id = xkcdResponseJSON.num; comic.title = xkcdResponseJSON.safe_title; comic.description = xkcdResponseJSON.alt; comic.image = xkcdResponseJSON.img; comic.url = this.XKCD_BASE_URL + xkcdResponseJSON.num; return comic; } async fetchLatestComic() { let responseJSON = await this.apiRequest(this.XKCD_API_SUFFIX); return this.parseComic(responseJSON); } async fetchComicByID(id) { let responseJSON; try { responseJSON = await this.apiRequest(id + this.XKCD_API_SUFFIX); } catch(e) { return {error: "Couldn't find that ID."}; } return this.parseComic(responseJSON); } async fetchRandomComic(id) { let latestComic = await this.fetchLatestComic(); let randomComicID = 1 + Math.floor(Math.random() * latestComic.id); return await this.fetchComicByID(randomComicID); } fetchComic(arg) { if (arg === "latest") { return this.fetchLatestComic(); } else if (arg) { return this.fetchComicByID(arg); } else { return this.fetchRandomComic(); } } } let tv = new TestVehicle() tv.fetchComic("latest").then(x => { if (x.error) { console.log(x.error); } else { console.log(x); } }).catch(e => console.error(e));
Perfect, thank you!
Code tested only separately from the bot in NPM runkit. Further testing recommended.
Code tested in NPM runkit: