misc.mcserver: 3 min timeout, why not

This commit is contained in:
Cynthia Foxwell 2023-07-09 18:10:09 -06:00
parent 2499ce6b36
commit 550ac7c0b3

View file

@ -2,7 +2,7 @@ const Command = require("../lib/command.js");
const logger = require("../lib/logger.js"); const logger = require("../lib/logger.js");
const CATEGORY = "misc"; const CATEGORY = "misc";
const { librex } = require("../../config.json"); const {librex} = require("../../config.json");
const { const {
hastebin, hastebin,
safeString, safeString,
@ -10,7 +10,7 @@ const {
formatTime, formatTime,
} = require("../lib/utils.js"); } = require("../lib/utils.js");
const GoogleImages = require("google-images"); const GoogleImages = require("google-images");
const { tinycolor, random: randomColor } = require("@ctrl/tinycolor"); const {tinycolor, random: randomColor} = require("@ctrl/tinycolor");
const sharp = require("sharp"); const sharp = require("sharp");
const net = require("node:net"); const net = require("node:net");
@ -21,11 +21,12 @@ yt.addAlias("yt");
yt.category = CATEGORY; yt.category = CATEGORY;
yt.helpText = "Search YouTube"; yt.helpText = "Search YouTube";
yt.usage = "[search term]"; yt.usage = "[search term]";
yt.callback = async function(msg, line) { yt.callback = async function (msg, line) {
if (!line) return "Arguments are required."; if (!line) return "Arguments are required.";
const req = await fetch( const req = await fetch(
`https://www.googleapis.com/youtube/v3/search?key=${hf.apikeys.google `https://www.googleapis.com/youtube/v3/search?key=${
hf.apikeys.google
}&maxResults=5&part=snippet&type=video&q=${encodeURIComponent(line)}` }&maxResults=5&part=snippet&type=video&q=${encodeURIComponent(line)}`
).then((x) => x.json()); ).then((x) => x.json());
@ -54,11 +55,12 @@ const fyt = new Command("fyt");
fyt.category = CATEGORY; fyt.category = CATEGORY;
fyt.helpText = "Search YouTube and take the first result."; fyt.helpText = "Search YouTube and take the first result.";
fyt.usage = "[search term]"; fyt.usage = "[search term]";
fyt.callback = async function(msg, line) { fyt.callback = async function (msg, line) {
if (!line) return "Arguments are required."; if (!line) return "Arguments are required.";
const req = await fetch( const req = await fetch(
`https://www.googleapis.com/youtube/v3/search?key=${hf.apikeys.google `https://www.googleapis.com/youtube/v3/search?key=${
hf.apikeys.google
}&maxResults=2&part=snippet&type=video&q=${encodeURIComponent(line)}` }&maxResults=2&part=snippet&type=video&q=${encodeURIComponent(line)}`
).then((x) => x.json()); ).then((x) => x.json());
@ -80,7 +82,7 @@ wolfram.helpText = "Wolfram Alpha";
wolfram.usage = "<-v> [query]"; wolfram.usage = "<-v> [query]";
wolfram.addAlias("wa"); wolfram.addAlias("wa");
wolfram.addAlias("calc"); wolfram.addAlias("calc");
wolfram.callback = async function(msg, line, args, { verbose, v }) { wolfram.callback = async function (msg, line, args, {verbose, v}) {
const _verbose = verbose ?? v; const _verbose = verbose ?? v;
const query = args.join(" "); const query = args.join(" ");
@ -114,15 +116,16 @@ wolfram.callback = async function(msg, line, args, { verbose, v }) {
for (const x in extra) { for (const x in extra) {
embed.fields.push({ embed.fields.push({
name: extra[x].title, name: extra[x].title,
value: `[${extra[x].subpods[0].plaintext.length > 0 value: `[${
extra[x].subpods[0].plaintext.length > 0
? extra[x].subpods[0].plaintext ? extra[x].subpods[0].plaintext
: "<click for image>" : "<click for image>"
}](${extra[x].subpods[0].img.src})`, }](${extra[x].subpods[0].img.src})`,
inline: true, inline: true,
}); });
} }
return { embed }; return {embed};
} else { } else {
let image; let image;
@ -160,7 +163,7 @@ gimg.category = CATEGORY;
gimg.helpText = "Search Google Images"; gimg.helpText = "Search Google Images";
gimg.usage = "[query]"; gimg.usage = "[query]";
gimg.addAlias("img"); gimg.addAlias("img");
gimg.callback = async function(msg, line) { gimg.callback = async function (msg, line) {
if (!line) return "No arguments given."; if (!line) return "No arguments given.";
const images = await imagesClient.search(line, { const images = await imagesClient.search(line, {
@ -182,8 +185,9 @@ gimg.callback = async function(msg, line) {
url: image.url, url: image.url,
}, },
footer: { footer: {
text: `Image ${Number(index) + 1}/${images.length text: `Image ${Number(index) + 1}/${
}. Rerun to get a different image.`, images.length
}. Rerun to get a different image.`,
}, },
}, },
], ],
@ -195,7 +199,7 @@ const fimg = new Command("fimg");
fimg.category = CATEGORY; fimg.category = CATEGORY;
fimg.helpText = "Send first result from Google Images"; fimg.helpText = "Send first result from Google Images";
fimg.usage = "[query]"; fimg.usage = "[query]";
fimg.callback = async function(msg, line) { fimg.callback = async function (msg, line) {
if (!line) return "No arguments given."; if (!line) return "No arguments given.";
const images = await imagesClient.search(line, { const images = await imagesClient.search(line, {
@ -225,7 +229,7 @@ const poll = new Command("poll");
poll.category = CATEGORY; poll.category = CATEGORY;
poll.helpText = "Start a poll"; poll.helpText = "Start a poll";
poll.usage = "[topic] [option 1] [option 2] [...option 3-10]"; poll.usage = "[topic] [option 1] [option 2] [...option 3-10]";
poll.callback = async function(msg, line, [topic, ...options]) { poll.callback = async function (msg, line, [topic, ...options]) {
if (!line || !topic) if (!line || !topic)
return 'Usage: hf!poll "topic" "option 1" "option 2" "...options 3-10"'; return 'Usage: hf!poll "topic" "option 1" "option 2" "...options 3-10"';
@ -254,14 +258,16 @@ const vote = new Command("vote");
vote.category = CATEGORY; vote.category = CATEGORY;
vote.helpText = "Start a yes/no vote"; vote.helpText = "Start a yes/no vote";
vote.usage = "[topic]"; vote.usage = "[topic]";
vote.callback = async function(msg, line, topic, { maybe }) { vote.callback = async function (msg, line, topic, {maybe}) {
if (!topic) return "No topic given."; if (!topic) return "No topic given.";
topic = topic.join(" "); topic = topic.join(" ");
return { return {
content: `**${msg.author.username}#${msg.author.discriminator content: `**${msg.author.username}#${
}** has started a vote:\n## __${topic}__\n<:ms_tick:503341995348066313>: Yes\n<:ms_cross:503341994974773250>: No${maybe ? "\n<:ms_tilda:581268710925271095>: Maybe/Uncertain" : "" msg.author.discriminator
}`, }** has started a vote:\n## __${topic}__\n<:ms_tick:503341995348066313>: Yes\n<:ms_cross:503341994974773250>: No${
maybe ? "\n<:ms_tilda:581268710925271095>: Maybe/Uncertain" : ""
}`,
addReactions: [ addReactions: [
":ms_tick:503341995348066313", ":ms_tick:503341995348066313",
":ms_cross:503341994974773250", ":ms_cross:503341994974773250",
@ -275,7 +281,7 @@ const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const anonradio = new Command("anonradio"); const anonradio = new Command("anonradio");
anonradio.category = CATEGORY; anonradio.category = CATEGORY;
anonradio.helpText = "aNONradio.net schedule"; anonradio.helpText = "aNONradio.net schedule";
anonradio.callback = async function() { anonradio.callback = async function () {
const now = new Date(); const now = new Date();
let playing; let playing;
@ -364,7 +370,7 @@ anonradio.callback = async function() {
}); });
} }
let liveNow = { name: "ident", id: "aNONradio" }; let liveNow = {name: "ident", id: "aNONradio"};
if (parsedLines[0].name.includes("<- Live NOW")) { if (parsedLines[0].name.includes("<- Live NOW")) {
liveNow = parsedLines.splice(0, 1)[0]; liveNow = parsedLines.splice(0, 1)[0];
@ -430,7 +436,7 @@ const REGEX_IPV4 = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/;
const shodan = new Command("shodan"); const shodan = new Command("shodan");
shodan.category = CATEGORY; shodan.category = CATEGORY;
shodan.helpText = "Look up an IP on Shodan InternetDB"; shodan.helpText = "Look up an IP on Shodan InternetDB";
shodan.callback = async function(msg, line) { shodan.callback = async function (msg, line) {
if (!line || line == "") return "Arguments required."; if (!line || line == "") return "Arguments required.";
if (!REGEX_IPV4.test(line)) return "Invalid IP address."; if (!REGEX_IPV4.test(line)) return "Invalid IP address.";
@ -494,7 +500,7 @@ const GENERATE_HEADERS = {
const generate = new Command("generate"); const generate = new Command("generate");
generate.category = CATEGORY; generate.category = CATEGORY;
generate.helpText = "Generate images from prompt via craiyon"; generate.helpText = "Generate images from prompt via craiyon";
generate.callback = async function(msg, line) { generate.callback = async function (msg, line) {
if (!line || line.length === 0) return "Arguments required."; if (!line || line.length === 0) return "Arguments required.";
msg.channel.sendTyping(); msg.channel.sendTyping();
@ -504,13 +510,13 @@ generate.callback = async function(msg, line) {
let request = await fetch("https://backend.craiyon.com/generate", { let request = await fetch("https://backend.craiyon.com/generate", {
method: "POST", method: "POST",
headers: GENERATE_HEADERS, headers: GENERATE_HEADERS,
body: JSON.stringify({ prompt: line }), body: JSON.stringify({prompt: line}),
}); });
while (request.status !== 200) { while (request.status !== 200) {
request = await fetch("https://backend.craiyon.com/generate", { request = await fetch("https://backend.craiyon.com/generate", {
method: "POST", method: "POST",
headers: GENERATE_HEADERS, headers: GENERATE_HEADERS,
body: JSON.stringify({ prompt: line }), body: JSON.stringify({prompt: line}),
}); });
retries++; retries++;
} }
@ -518,13 +524,14 @@ generate.callback = async function(msg, line) {
const data = await request.json(); const data = await request.json();
const images = data.images const images = data.images
.map((img) => Buffer.from(img, "base64")) .map((img) => Buffer.from(img, "base64"))
.map((img, index) => ({ contents: img, name: `${index}.jpg` })); .map((img, index) => ({contents: img, name: `${index}.jpg`}));
const title = `Responses for "${safeString(line)}"`; const title = `Responses for "${safeString(line)}"`;
const out = { const out = {
content: `Generated in ${formatTime(Date.now() - start)}${retries > 0 ? " with " + retries + " retries" : "" content: `Generated in ${formatTime(Date.now() - start)}${
}`, retries > 0 ? " with " + retries + " retries" : ""
}`,
embeds: [], embeds: [],
files: images, files: images,
}; };
@ -551,7 +558,7 @@ search.helpText = "Search, powered by LibreX";
search.addAlias("g"); search.addAlias("g");
search.addAlias("google"); search.addAlias("google");
search.addAlias("ddg"); search.addAlias("ddg");
search.callback = async function(msg, line, args, { results = 2 }) { search.callback = async function (msg, line, args, {results = 2}) {
const query = args.join(" "); const query = args.join(" ");
if (!librex) return "LibreX instance not defined."; if (!librex) return "LibreX instance not defined.";
if (!query || query == "") return "Search query required."; if (!query || query == "") return "Search query required.";
@ -596,7 +603,7 @@ hf.registerCommand(search);
const color = new Command("color"); const color = new Command("color");
color.category = CATEGORY; color.category = CATEGORY;
color.helpText = "Show information on a color or get a random color"; color.helpText = "Show information on a color or get a random color";
color.callback = async function(msg, line, args, { truerandom }) { color.callback = async function (msg, line, args, {truerandom}) {
let color = tinycolor(line), let color = tinycolor(line),
random = false; random = false;
@ -616,7 +623,7 @@ color.callback = async function(msg, line, args, { truerandom }) {
width: 128, width: 128,
height: 128, height: 128,
channels: 3, channels: 3,
background: { r: color.r, g: color.g, b: color.b }, background: {r: color.r, g: color.g, b: color.b},
}, },
}) })
.png() .png()
@ -744,7 +751,7 @@ const formattingToAnsi = {
const mcserver = new Command("mcserver"); const mcserver = new Command("mcserver");
mcserver.category = CATEGORY; mcserver.category = CATEGORY;
mcserver.helpText = "Query a Minecraft server"; mcserver.helpText = "Query a Minecraft server";
mcserver.callback = async function(msg, line) { mcserver.callback = async function (msg, line) {
if (!line || line == "") return "Arguments required."; if (!line || line == "") return "Arguments required.";
const split = line.split(":"); const split = line.split(":");
@ -755,29 +762,31 @@ mcserver.callback = async function(msg, line) {
const data = await new Promise((resolve, reject) => { const data = await new Promise((resolve, reject) => {
logger.verbose("mcserver", "querying", ip, port); logger.verbose("mcserver", "querying", ip, port);
const timeout = setTimeout(() => {
logger.verbose("mcserver", "timeout");
resolve("timeout");
}, 60000);
const client = net.createConnection( const client = net.createConnection(
{ {
host: ip, host: ip,
port: port, port: port,
timeout: 60000, timeout: 180000,
}, },
function() { function () {
logger.verbose("mcserver", "connect"); logger.verbose("mcserver", "connect");
client.write(HANDSHAKE_PACKET); client.write(HANDSHAKE_PACKET);
} }
); );
const timeout = setTimeout(() => {
logger.verbose("mcserver", "timeout");
client.destroy();
resolve("timeout");
}, 180000);
let totalData = Buffer.alloc(0); let totalData = Buffer.alloc(0);
client.on("data", function(data) { client.on("data", function (data) {
totalData = Buffer.concat([totalData, data]); totalData = Buffer.concat([totalData, data]);
logger.verbose("mcserver", "data", data.length, totalData.length); logger.verbose("mcserver", "data", data.length, totalData.length);
}); });
client.on("close", function(err) { client.on("close", function (err) {
if (err) { if (err) {
logger.verbose("mcserver", "close with error", err); logger.verbose("mcserver", "close with error", err);
return reject(err); return reject(err);
@ -794,7 +803,7 @@ mcserver.callback = async function(msg, line) {
clearTimeout(timeout); clearTimeout(timeout);
return resolve(json); return resolve(json);
}); });
client.on("timeout", function() { }); client.on("timeout", function () {});
}); });
if (data == "timeout") { if (data == "timeout") {