UNPKG

psyduck-plugin-quotes

Version:
221 lines (220 loc) 10.6 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); require("reflect-metadata"); const command_line_args_1 = __importDefault(require("command-line-args")); const lodash_1 = __importDefault(require("lodash")); const moment_1 = __importDefault(require("moment")); const psyduck_models_1 = require("psyduck-models"); const typeorm_1 = require("typeorm"); exports.commandOptions = [ { name: 'pluck', alias: 'p', type: Number }, { name: 'help', alias: 'h', type: Boolean }, { name: 'user', alias: 'u', type: String, defaultOption: true } ]; exports.userFormatRegex = new RegExp(/^(<@.+>)|(<!.+>)$/); var CommandType; (function (CommandType) { CommandType[CommandType["Quote"] = 0] = "Quote"; CommandType[CommandType["Random"] = 1] = "Random"; })(CommandType = exports.CommandType || (exports.CommandType = {})); class PsyduckQuotes { constructor(options) { this.connectionOptions = options; } connect() { typeorm_1.createConnection(Object.assign({}, this.connectionOptions, { synchronize: true, logging: false, entities: [ psyduck_models_1.PluginQuoteUser, psyduck_models_1.UserQuote ] })).then((connection) => __awaiter(this, void 0, void 0, function* () { this.users = connection.getRepository(psyduck_models_1.PluginQuoteUser); this.quotes = connection.getRepository(psyduck_models_1.UserQuote); })).catch(error => console.log(error)); } onMessage(message) { if (message.author.bot) { return; } if (message.content.length <= 1) { return; } const dupe = RegExp(/^(.)\1*$/gm); if (dupe.test(message.content)) { return; } if (message.content.startsWith('!')) { const commandCode = message.content.slice(1, message.content.indexOf(' ')); if (lodash_1.default.includes(['quote', 'q', 'grab', 'g'], commandCode)) { this.prepareHandler(message, CommandType.Quote); } else if (lodash_1.default.includes(['random', 'r'], commandCode)) { this.prepareHandler(message, CommandType.Random); } } } parseParameters(messageContent) { const params = messageContent.match(/ (?=\S)[^'\s]*(?:'[^\\']*(?:\\[\s\S][^\\']*)*'[^'\s]*)*/g) || []; return params.map(p => p.trim()); } hydrateOptions(parameters) { return command_line_args_1.default(exports.commandOptions, { argv: parameters, partial: true }); } extractUserId(userId) { const matches = userId.match(/(?<=@|!)(.*)(?=>)/gm); if (matches && matches.length === 1) { return matches[0].replace('!', ''); } return undefined; } prepareHandler(message, commandType) { const parameters = this.parseParameters(message.content); if (parameters.length > 0) { const options = this.hydrateOptions(parameters); if (options.help === true) { this.sendHelp(message); } else { if (!options.user || !exports.userFormatRegex.test(options.user)) { if (commandType === CommandType.Quote) { message.channel.send(`Unable to quote. User missing or wrong format.`); } else if (commandType === CommandType.Random) { message.channel.send(`Unable to recall. User missing or wrong format.`); } } else { const userId = this.extractUserId(options.user); if (!userId) { message.channel.send('Unable to parse user id from supplied parameters.'); } if (userId === message.author.id) { if (commandType === CommandType.Quote) { message.channel.send('It looks like you are trying to quote yourself! Don\'t take all the fun out of it!'); } else if (commandType === CommandType.Random) { message.channel.send('It looks like you are trying to recall yourself! Don\'t take all the fun out of it!'); } } else { if (commandType === CommandType.Quote) { this.saveQuote(message, userId, options.pluck); } else if (commandType === CommandType.Random) { this.recallQuote(message, userId); } } } } } } sendHelp(message) { const embed = { 'title': 'Psyduck Quote Plugin Help', 'description': 'Use this plugin to quote users and recall random quotes from the past.', 'url': 'https://github.com/galactic0wl/psyduck-plugin-quotes', 'color': 3201505, 'author': { 'name': 'Marky Mark', 'url': 'https://github.com/galactic0wl/psyduck-plugin-quotes', 'icon_url': 'https://cdn.discordapp.com/avatars/341668692133806080/a_252e33ff6363f93849e75a5decf9f10a.gif' }, 'fields': [ { 'name': 'Commands', 'value': 'The following commands are available to standard users.\n\n' }, { 'name': '[q]uote & [g]rab', 'value': 'To save a quote from a user run `!q @MentionUser` to grab the last message. If you would like to target a specific message within reason you can run `!quote @MentionUser -p 3` to save the second to the last message of the user, or, 3 messages up.\n\n**Parameters** ```--pluck <count> or -p <count>```' }, { 'name': '[r]andom', 'value': 'To recall a quote from a user run `!r @MentionUser` to grab a random message from the past.' } ] }; message.channel.send({ embed }); } getUser(userId) { return __awaiter(this, void 0, void 0, function* () { return yield this.users.findOne({ user: { id: userId } }, { relations: ['quotes'] }); }); } createUser(guildId, serverName, guildAvatarUrl, userId, userName, avatarUrl) { const user = new psyduck_models_1.PluginQuoteUser(); const guildUser = new psyduck_models_1.GuildUser(); guildUser.id = userId; guildUser.userName = userName; guildUser.avatarUrl = avatarUrl; const guild = new psyduck_models_1.Guild(); guild.id = guildId; guild.serverName = serverName; guild.avatarUrl = guildAvatarUrl; guildUser.guild = guild; user.user = guildUser; user.quotes = []; return user; } recallQuote(message, userId) { return __awaiter(this, void 0, void 0, function* () { const user = yield this.getUser(userId); if (!user || user.quotes.length === 0) { message.channel.send(`Our records indicated that the user has zero quotes. While this is unfortunate, it may be resolved.`); } else { const quote = lodash_1.default.sample(user.quotes); message.channel.send(`Remember this one <@${userId}>? '${quote.content}' - Snagged by <@${quote.capturerId}> at ${quote.captureTime}`); } }); } buildQuote(capturerId, content) { const quote = new psyduck_models_1.UserQuote(); quote.capturerId = capturerId; quote.content = content; quote.captureTime = moment_1.default().format('ddd MMM DD YYYY h:mm A'); return quote; } saveQuote(message, userId, pluck = 1) { return __awaiter(this, void 0, void 0, function* () { const messageMap = yield message.channel.fetchMessages({ limit: 100 }); const messages = [...messageMap.values()].filter(m => m.author.id === userId); if (messages.length > 0) { if (messages.length < pluck) { message.channel.send('You attempted to pluck a message out of my range. Please try again.'); } else { let user = yield this.getUser(userId); if (!user) { user = this.createUser(message.guild.id, message.guild.name, message.guild.iconURL, message.author.id, message.author.username, message.author.avatarURL); user.quotes.push(this.buildQuote(message.author.id, messages[pluck - 1].content)); } else { if (user.quotes.filter(u => u.content === messages[pluck - 1].content).length <= 0) { user.quotes.push(this.buildQuote(message.author.id, messages[pluck - 1].content)); } else { message.channel.send('It looks like I already have a record of this quote.'); return; } } yield this.users.save(user); message.channel.send(`Plucked: ${messages[pluck - 1]}`); } } }); } } exports.default = PsyduckQuotes;