import sql from "../sql.js"; let _query_get = ` with ranked_quotes as ( select nick, item, rank() over (partition by nick order by id), count(*) over (partition by nick) as total from nxy_quotes ) select * from ranked_quotes where nick ilike $1 {where} order by {order} {limit} {offset} `; let _query_add = ` insert into nxy_quotes (nick, item, channel, created_by) values ($1, $2, $3, $4); `; module.exports = bot => { bot._trigger.set("quotes", new bot.trigger({ call: /^(\.|\/)q .*/i, active: true, f: e => { let args = e.message.trim().substring(3).split(" "); const cmd = args[0].toLowerCase(); let nick; switch(cmd) { case "add": // add quote if(args.length < 3) return e.reply("ob du behindert bist."); args.shift(); nick = args[0].match(/?/)[1]; args.shift(); let quote = args.join(" "); sql.any(_query_add, [ nick, quote, `${e.network}.${e.channel}`, e.user.nick ]) .then(rows => { }) .catch(err => { e.reply("duplicate!"); }); break; default: // get quote let nick = cmd; let index = 0 , params = [nick] , offset = 0 , order = "rank asc" , rand = false , where = "" , limit = "limit 1" , query = _query_get; if(args.length >= 2) { if(isNaN(args[1])) { where = "and item ilike $2"; params.push(`%${args[1]}%`); limit = ""; } else { index = parseInt(args[1]); order = (index < 0 ? "rank desc" : "rank asc"); offset = Math.abs(index) - 1; } } else rand = true; query = query .replace("{where}", where) .replace("{limit}", limit) .replace("{order}", rand ? "random()" : order) .replace("{offset}", rand ? "" : `offset ${offset}`); sql.any(query, params) .then(rows => { if(!rows[0]) return e.reply("index nicht vorhanden"); if(rows.length > 1) { let rank = 1; let index = rank - 1; if (args[2] && !isNaN(args[2])) { rank = parseInt(args[2]); index = rank - 1; } if(rank < 0) { index = rows.length - Math.abs(rank); rank = index + 1; } if (!rows[index]) return e.reply("index nicht vorhanden"); else e.reply(`[${rank}/${rows.length}] <${rows[index].nick}> ${rows[index].item}`) } else e.reply(`[${rows[0].rank}/${rows[0].total}] <${rows[0].nick}> ${rows[0].item}`) }) .catch(err => console.log(err)); break; } } })); };