@minhducsun2002/paged-embeds
Version:
Discord embeds pagination wrapper
74 lines (73 loc) • 3.14 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const deURIfy = (s) => decodeURIComponent(s);
class PagedEmbeds extends events_1.EventEmitter {
constructor() {
super();
this._embeds = [];
this._currentIndex = 0;
this._hooks = new Map();
}
setEmbeds(m) {
if (!Array.isArray(m))
throw new TypeError(`Argument to setEmbeds must be an array of MessageEmbeds!`);
this._embeds = m;
return this;
}
setChannel(c) {
this._channel = c;
return this;
}
addHandler(e, h) {
this._hooks.set(deURIfy(e.toString()), [e, h]);
return this;
}
removeHandler(e) {
this._hooks.delete(deURIfy(e.toString()));
return this;
}
setIndex(i) {
if (typeof i !== 'number')
throw new TypeError(`Argument to setIndex must be a number!`);
this._currentIndex = i;
return this;
}
get hooks() { return this._hooks; }
;
run(opts, content = '') {
return __awaiter(this, void 0, void 0, function* () {
if (!this._channel)
throw new Error(`A channel must be set!`);
this._msg = yield this._channel.send(content, this._embeds[this._currentIndex]);
let collector = this._msg.createReactionCollector((r) => this._hooks.has(deURIfy(r.emoji.toString())), opts);
collector.on('collect', (r, u) => __awaiter(this, void 0, void 0, function* () {
if (u.id === this._msg.author.id)
return;
let { index, embed } = this._hooks.get(deURIfy(r.emoji.toString()))[1](this._currentIndex, this._embeds, r, collector, u);
if (!embed)
embed = this._embeds;
if (!index)
if (typeof index !== 'number')
// in case 0 is passed, still count
index = ((this._currentIndex + 1) % embed.length + embed.length) % embed.length;
this._currentIndex = index;
this._embeds = embed;
let { content } = yield this._msg.fetch();
this._msg.edit(content, { embed: embed[index] });
}));
this._hooks.forEach(([e]) => this._msg.react(e.toString()));
return collector;
});
}
}
exports.PagedEmbeds = PagedEmbeds;