misc.mcserver: actually check thhat we have an image to upload

This commit is contained in:
Cynthia Foxwell 2023-07-09 18:05:23 -06:00
parent 3d600c8c9a
commit 2499ce6b36
1 changed files with 37 additions and 44 deletions

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,12 +21,11 @@ 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=${ `https://www.googleapis.com/youtube/v3/search?key=${hf.apikeys.google
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());
@ -55,12 +54,11 @@ 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=${ `https://www.googleapis.com/youtube/v3/search?key=${hf.apikeys.google
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());
@ -82,7 +80,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(" ");
@ -116,16 +114,15 @@ 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: `[${ value: `[${extra[x].subpods[0].plaintext.length > 0
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;
@ -163,7 +160,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, {
@ -185,9 +182,8 @@ gimg.callback = async function (msg, line) {
url: image.url, url: image.url,
}, },
footer: { footer: {
text: `Image ${Number(index) + 1}/${ text: `Image ${Number(index) + 1}/${images.length
images.length }. Rerun to get a different image.`,
}. Rerun to get a different image.`,
}, },
}, },
], ],
@ -199,7 +195,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, {
@ -229,7 +225,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"';
@ -258,16 +254,14 @@ 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}#${ content: `**${msg.author.username}#${msg.author.discriminator
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" : ""
}** 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",
@ -281,7 +275,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;
@ -370,7 +364,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];
@ -436,7 +430,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.";
@ -500,7 +494,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();
@ -510,13 +504,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++;
} }
@ -524,14 +518,13 @@ 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)}${ content: `Generated in ${formatTime(Date.now() - start)}${retries > 0 ? " with " + retries + " retries" : ""
retries > 0 ? " with " + retries + " retries" : "" }`,
}`,
embeds: [], embeds: [],
files: images, files: images,
}; };
@ -558,7 +551,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.";
@ -603,7 +596,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;
@ -623,7 +616,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()
@ -751,7 +744,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(":");
@ -773,18 +766,18 @@ mcserver.callback = async function (msg, line) {
port: port, port: port,
timeout: 60000, timeout: 60000,
}, },
function () { function() {
logger.verbose("mcserver", "connect"); logger.verbose("mcserver", "connect");
client.write(HANDSHAKE_PACKET); client.write(HANDSHAKE_PACKET);
} }
); );
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);
@ -801,7 +794,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") {
@ -851,7 +844,7 @@ mcserver.callback = async function (msg, line) {
url: "attachment://icon.png", url: "attachment://icon.png",
}, },
}, },
file: { file: image && {
file: image, file: image,
name: "icon.png", name: "icon.png",
}, },