117 lines
3.1 KiB
JavaScript
117 lines
3.1 KiB
JavaScript
import sql from "../sql.mjs";
|
|
import fetch from "flumm-fetch-cookies";
|
|
|
|
let _query_get = `
|
|
with ranked_quotes as (
|
|
select nick,
|
|
item,
|
|
rank() over (partition by lower(nick) order by id),
|
|
count(*) over (partition by lower(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);
|
|
`;
|
|
|
|
export default async bot => {
|
|
|
|
return [{
|
|
name: "qrnd",
|
|
call: /^(\.|\/)q(rnd)?$/i,
|
|
set: "all",
|
|
f: async e => {
|
|
const res = await (await fetch("https://nxy.totally.rip/api/quotes.php?c=nick,item")).json();
|
|
const quote = res.data.quotes[~~(Math.random() * res.data.quotes.length)];
|
|
e.reply(`<[b]${quote.nick}[/b]> [i]${quote.item}[/i]`);
|
|
}
|
|
}, {
|
|
name: "quotes",
|
|
call: /^(\.|\/)q .*/i,
|
|
set: "nxy",
|
|
f: async 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(/<?[~&@%+]?([a-zA-Z0-9_\-^`|\\\[\]{}]+)>?/)[1];
|
|
args.shift();
|
|
let quote = args.join(" ");
|
|
|
|
try {
|
|
await sql.query(_query_add, [ nick, quote, `${e.network}.${e.channel}`, e.user.nick ]);
|
|
} catch(e) {
|
|
return e.reply("duplicate!");
|
|
}
|
|
break;
|
|
default: // get quote
|
|
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}`);
|
|
|
|
const rows = (await sql.query(query, params)).rows;
|
|
|
|
if (!rows || rows.length === 0)
|
|
return e.reply("index nicht vorhanden");
|
|
|
|
let rank = 1;
|
|
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");
|
|
|
|
e.reply(`[${rows[index].rank}/${rows[index].total}] <${rows[index].nick}> ${rows[index].item}`);
|
|
break;
|
|
}
|
|
}
|
|
}];
|
|
};
|