HiddenPhox/src/modules/misc.js

865 lines
22 KiB
JavaScript
Raw Normal View History

2022-08-03 04:23:46 +00:00
const Command = require("../lib/command.js");
2023-06-28 06:08:22 +00:00
const logger = require("../lib/logger.js");
2022-08-03 04:23:46 +00:00
const CATEGORY = "misc";
2023-07-10 00:10:09 +00:00
const {librex} = require("../../config.json");
2022-08-03 04:23:46 +00:00
const {
2023-09-15 03:09:20 +00:00
formatTime,
2022-08-03 04:23:46 +00:00
hastebin,
parseHtmlEntities,
formatUsername,
2023-09-15 03:09:20 +00:00
safeString,
2022-08-03 04:23:46 +00:00
} = require("../lib/utils.js");
const GoogleImages = require("google-images");
2023-07-10 00:10:09 +00:00
const {tinycolor, random: randomColor} = require("@ctrl/tinycolor");
2023-04-27 00:24:08 +00:00
const sharp = require("sharp");
2023-06-28 06:00:12 +00:00
const net = require("node:net");
2022-08-03 04:23:46 +00:00
const imagesClient = new GoogleImages(hf.apikeys.gimg, hf.apikeys.google);
const yt = new Command("youtube");
yt.addAlias("yt");
yt.category = CATEGORY;
yt.helpText = "Search YouTube";
yt.usage = "[search term]";
2023-07-10 00:10:09 +00:00
yt.callback = async function (msg, line) {
2022-08-03 04:23:46 +00:00
if (!line) return "Arguments are required.";
const req = await fetch(
2023-09-13 04:24:17 +00:00
`${hf.config.piped_api}/search?q=${encodeURIComponent(line)}&filter=videos`
2022-08-03 04:23:46 +00:00
).then((x) => x.json());
const topVid = req.items[0];
let out = `**${safeString(
2023-09-13 04:24:17 +00:00
parseHtmlEntities(topVid.title)
2022-08-03 04:23:46 +00:00
)}** | \`${safeString(
2023-09-13 04:24:17 +00:00
parseHtmlEntities(topVid.uploaderName)
)}\`\nhttps://youtube.com${topVid.url}\n\n**__See Also:__**\n`;
2022-08-03 04:23:46 +00:00
2023-09-13 04:24:17 +00:00
for (let i = 1; i < 5; i++) {
2022-08-03 04:23:46 +00:00
const vid = req.items[i];
2023-09-13 04:24:17 +00:00
if (!vid) continue;
2022-08-03 04:23:46 +00:00
out += `- **${safeString(
2023-11-16 19:25:56 +00:00
parseHtmlEntities(vid.title)
2022-08-03 04:23:46 +00:00
)}** | By: \`${safeString(
2023-09-13 04:24:17 +00:00
parseHtmlEntities(vid.uploaderName)
)}\` | <https://youtube.com${vid.url}>\n`;
2022-08-03 04:23:46 +00:00
}
return out;
};
hf.registerCommand(yt);
const fyt = new Command("fyt");
fyt.category = CATEGORY;
fyt.helpText = "Search YouTube and take the first result.";
fyt.usage = "[search term]";
2023-07-10 00:10:09 +00:00
fyt.callback = async function (msg, line) {
2022-08-03 04:23:46 +00:00
if (!line) return "Arguments are required.";
const req = await fetch(
2023-09-13 04:24:17 +00:00
`${hf.config.piped_api}/search?q=${encodeURIComponent(line)}&filter=videos`
2022-08-03 04:23:46 +00:00
).then((x) => x.json());
const vid = req.items[0];
2023-09-13 04:24:17 +00:00
return `**${safeString(parseHtmlEntities(vid.title))}** | \`${safeString(
parseHtmlEntities(vid.uploaderName)
)}\`\nhttps://youtube.com${vid.url}`;
2022-08-03 04:23:46 +00:00
};
hf.registerCommand(fyt);
const WA_NO_ANSWER = "<:ms_cross:503341994974773250> No answer.";
const wolfram = new Command("wolfram");
wolfram.category = CATEGORY;
wolfram.helpText = "Wolfram Alpha";
wolfram.usage = "<-v> [query]";
wolfram.addAlias("wa");
2023-01-20 19:20:48 +00:00
wolfram.addAlias("calc");
2023-07-10 00:10:09 +00:00
wolfram.callback = async function (msg, line, args, {verbose, v}) {
2022-11-30 01:15:41 +00:00
const _verbose = verbose ?? v;
2022-11-30 19:49:03 +00:00
const query = args.join(" ");
2022-08-03 04:23:46 +00:00
const req = await fetch(
`http://api.wolframalpha.com/v2/query?input=${encodeURIComponent(
2022-11-30 02:40:59 +00:00
query
2022-08-03 04:23:46 +00:00
)}&appid=LH2K8H-T3QKETAGT3&output=json`
).then((x) => x.json());
const data = req.queryresult.pods;
if (!data) return WA_NO_ANSWER;
// fake no answer
//if (data[0].subpods[0].plaintext.includes("geoIP")) return WA_NO_ANSWER;
2022-08-03 04:23:46 +00:00
2022-11-30 01:15:41 +00:00
if (_verbose) {
2022-08-03 04:23:46 +00:00
const embed = {
2022-11-30 02:40:59 +00:00
title: `Result for: \`${safeString(query)}\``,
2022-08-03 04:23:46 +00:00
fields: [],
footer: {
icon_url: "http://www.wolframalpha.com/share.png",
text: "Powered by Wolfram Alpha",
},
image: {
url: data[1].subpods[0].img.src,
},
};
const extra = data.slice(1, 6);
for (const x in extra) {
embed.fields.push({
name: extra[x].title,
2023-07-10 00:10:09 +00:00
value: `[${
extra[x].subpods[0].plaintext.length > 0
2022-08-03 04:23:46 +00:00
? extra[x].subpods[0].plaintext
: "<click for image>"
2023-07-10 00:10:09 +00:00
}](${extra[x].subpods[0].img.src})`,
2022-08-03 04:23:46 +00:00
inline: true,
});
}
2023-07-10 00:10:09 +00:00
return {embed};
2022-08-03 04:23:46 +00:00
} else {
let image;
if (data[1].subpods[0].img.src)
try {
const res = await fetch(data[1].subpods[0].img.src);
if (res) {
const imgData = await res.arrayBuffer();
image = Buffer.from(imgData);
}
} catch {
//
}
let string = "";
if (data[1].subpods[0].plaintext.length > 0)
string = safeString(data[1].subpods[0].plaintext);
2022-11-30 02:40:59 +00:00
if (string.length > 2000 - (6 + safeString(query).length))
2022-08-03 04:23:46 +00:00
string = "Output too long: " + (await hastebin(string));
return {
2022-11-30 02:40:59 +00:00
content: `\`${safeString(query)}\` -> ${string.length > 0 ? string : ""}`,
2022-08-03 04:23:46 +00:00
file: image && {
file: image,
name: "wolfram_output.gif",
},
};
}
};
hf.registerCommand(wolfram);
const gimg = new Command("gimg");
gimg.category = CATEGORY;
gimg.helpText = "Search Google Images";
gimg.usage = "[query]";
gimg.addAlias("img");
2023-07-10 00:10:09 +00:00
gimg.callback = async function (msg, line) {
2022-08-03 04:23:46 +00:00
if (!line) return "No arguments given.";
const images = await imagesClient.search(line, {
safe:
msg.channel.nsfw && !msg.channel?.topic.includes("[no_nsfw]")
? "off"
: "high",
});
const index = Math.floor(Math.random() * images.length);
const image = images[index];
return {
embeds: [
{
title: image.description,
url: image.parentPage,
image: {
url: image.url,
},
footer: {
2023-07-10 00:10:09 +00:00
text: `Image ${Number(index) + 1}/${
images.length
}. Rerun to get a different image.`,
2022-08-03 04:23:46 +00:00
},
},
],
};
};
hf.registerCommand(gimg);
const fimg = new Command("fimg");
fimg.category = CATEGORY;
fimg.helpText = "Send first result from Google Images";
fimg.usage = "[query]";
2023-07-10 00:10:09 +00:00
fimg.callback = async function (msg, line) {
2022-08-03 04:23:46 +00:00
if (!line) return "No arguments given.";
const images = await imagesClient.search(line, {
safe:
msg.channel.nsfw && !msg.channel?.topic.includes("[no_nsfw]")
? "off"
: "high",
});
const image = images[0];
return {
embeds: [
{
title: image.description,
url: image.parentPage,
image: {
url: image.url,
},
},
],
};
};
hf.registerCommand(fimg);
const poll = new Command("poll");
poll.category = CATEGORY;
poll.helpText = "Start a poll";
poll.usage = "[topic] [option 1] [option 2] [...option 3-10]";
2023-07-10 00:10:09 +00:00
poll.callback = async function (msg, line, [topic, ...options]) {
2022-08-03 04:23:46 +00:00
if (!line || !topic)
return 'Usage: hf!poll "topic" "option 1" "option 2" "...options 3-10"';
const arrOptions = [...options].slice(0, 10);
if (arrOptions.length < 2) return "A minimum of two options are required.";
const reactions = [];
let displayString = `**${formatUsername(
2023-09-15 03:09:20 +00:00
msg.author
)}** has started a poll:\n## __${topic}__\n`;
2022-08-03 04:23:46 +00:00
for (let i = 0; i < arrOptions.length; i++) {
displayString +=
(i === 9 ? "\ud83d\udd1f" : `${i + 1}\u20e3`) +
": " +
arrOptions[i] +
"\n";
reactions[i] = i === 9 ? "\ud83d\udd1f" : `${i + 1}\u20e3`;
}
return {
content: displayString,
addReactions: reactions,
};
};
hf.registerCommand(poll);
const vote = new Command("vote");
vote.category = CATEGORY;
vote.helpText = "Start a yes/no vote";
vote.usage = "[topic]";
2023-07-10 00:10:09 +00:00
vote.callback = async function (msg, line, topic, {maybe}) {
2022-11-30 01:15:41 +00:00
if (!topic) return "No topic given.";
2023-04-20 16:26:42 +00:00
topic = topic.join(" ");
2022-08-03 04:23:46 +00:00
return {
content: `**${formatUsername(
2023-09-15 03:09:20 +00:00
msg.author
)}** has started a vote:\n## __${topic}__\n<:ms_tick:503341995348066313>: Yes\n<:ms_cross:503341994974773250>: No${
2023-07-10 00:10:09 +00:00
maybe ? "\n<:ms_tilda:581268710925271095>: Maybe/Uncertain" : ""
}`,
2022-08-03 04:23:46 +00:00
addReactions: [
":ms_tick:503341995348066313",
":ms_cross:503341994974773250",
2022-11-30 01:15:41 +00:00
maybe && ":ms_tilda:581268710925271095",
].filter((x) => x != null),
2022-08-03 04:23:46 +00:00
};
};
hf.registerCommand(vote);
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
2022-08-16 20:30:58 +00:00
const anonradio = new Command("anonradio");
anonradio.category = CATEGORY;
anonradio.helpText = "aNONradio.net schedule";
2023-07-10 00:10:09 +00:00
anonradio.callback = async function () {
2022-08-03 04:23:46 +00:00
const now = new Date();
2022-12-10 23:19:21 +00:00
let playing;
try {
playing = await fetch("https://anonradio.net/playing").then((res) =>
res.text()
);
} catch (err) {
try {
playing = await fetch("http://anonradio.net/playing").then((res) =>
res.text()
);
2022-12-18 19:37:00 +00:00
} catch (err) {
//
}
2022-12-10 23:19:21 +00:00
}
2022-12-10 23:16:39 +00:00
let schedule;
try {
schedule = await fetch("https://anonradio.net/schedule/").then((res) =>
res.text()
2022-08-20 04:54:31 +00:00
);
2022-12-10 23:16:39 +00:00
} catch (err) {
try {
schedule = await fetch("http://anonradio.net/schedule/").then((res) =>
res.text()
);
2022-12-18 19:37:00 +00:00
} catch (err) {
//
}
2022-12-10 23:16:39 +00:00
}
2022-12-10 23:19:21 +00:00
if (!playing || !schedule) return "Failed to fetch schedule.";
const icecast = await fetch("http://anonradio.net:8010/status-json.xsl")
.then((res) => res.text())
.then((data) =>
JSON.parse(data.replace(/"title": - ,/g, '"title":" - ",'))
);
2022-08-03 04:23:46 +00:00
let lines = schedule.split("\n");
lines = lines.slice(4, lines.length - 2);
const parsedLines = [];
for (const line of lines) {
const [_, time, id, name] = line.match(/^(.{3,4} .{4})\s+(.+?) {2}(.+?)$/);
const tmp = time.split(" ");
const day = tmp[0];
let hour = tmp[1];
const currentDay = now.getUTCDay();
const targetDay = DAYS.indexOf(day);
const delta = (targetDay + 7 - currentDay) % 7;
let currentYear = now.getUTCFullYear();
const currentMonth = now.getUTCMonth() + 1;
const currentDateDay = now.getUTCDate();
let targetMonth = currentMonth;
const lastDay = new Date(currentYear, currentMonth, 0).getDate();
let targetDateDay = currentDateDay + delta;
if (targetDateDay > lastDay) {
targetMonth = currentMonth === 12 ? 1 : currentMonth + 1;
targetDateDay = 1;
if (currentMonth === 12) currentYear++;
}
hour = hour.slice(0, 2) + ":" + hour.slice(-2);
const timestamp =
Date.parse(
`${DAYS[targetDay]}, ${currentYear}-${targetMonth}-${targetDateDay} ${hour} UTC`
) / 1000;
2022-09-10 03:18:21 +00:00
let nameOut = name;
if (time == "Sat 0300")
nameOut = name.replace(
"Open Mic - Anyone can stream",
"Synth Battle Royale"
);
parsedLines.push({
timestamp,
id,
name: nameOut.replace(" <- Up NEXT", ""),
});
2022-08-03 04:23:46 +00:00
}
2023-07-10 00:10:09 +00:00
let liveNow = {name: "ident", id: "aNONradio"};
if (parsedLines[0].name.includes("<- Live NOW")) {
liveNow = parsedLines.splice(0, 1)[0];
liveNow.name = liveNow.name.replace(" <- Live NOW", "");
}
2022-08-03 04:23:46 +00:00
2022-08-16 20:30:58 +00:00
let title = "";
let subtitle = "";
if (playing.includes("listeners with a daily peak of")) {
title = `${liveNow.name} (\`${liveNow.id}\`)`;
subtitle = playing;
} else {
const [_, current, peakDay, peakMonth, dj, metadata] = playing.match(
2022-08-16 20:32:50 +00:00
/\[(\d+)\/(\d+)\/(\d+)\] \((.+?)\): (.+)/
2022-08-16 20:30:58 +00:00
);
if (
metadata == "https://archives.anonradio.net" ||
liveNow.name == "Synth Battle Royale"
) {
2022-08-16 20:30:58 +00:00
title = `${liveNow.name} (\`${dj}\`)`;
} else {
title = `${metadata} (\`${dj}\`)`;
}
subtitle = `${current} listening with a daily peak of ${peakDay} and ${peakMonth} peak for the month.`;
}
2022-08-20 04:48:02 +00:00
let openmicTime = "";
if (liveNow.id == "openmic") {
const streamData = icecast.icestats.source.find(
(src) => src.listenurl == "http://anonradio.net:8010/openmic"
);
if (streamData && streamData.stream_start_iso8601) {
const startTime = new Date(streamData.stream_start_iso8601).getTime();
2022-08-20 04:56:00 +00:00
openmicTime = `-\\*- OpenMIC DJ has been streaming for ${formatTime(
2022-08-20 04:48:02 +00:00
Date.now() - startTime
2022-08-20 04:56:00 +00:00
)} -\\*-\n`;
2022-08-20 04:48:02 +00:00
}
}
2022-08-03 04:23:46 +00:00
return {
embeds: [
{
2022-08-16 20:30:58 +00:00
title: subtitle,
2022-08-03 04:23:46 +00:00
author: {
2022-08-16 20:30:58 +00:00
name: title,
url: "http://anonradio.net:8000/anonradio",
2022-08-03 04:23:46 +00:00
},
2022-08-20 04:48:02 +00:00
description: openmicTime + "__Schedule:__",
2022-08-03 04:23:46 +00:00
fields: parsedLines.map((line) => ({
inline: true,
name: `${line.name} (\`${line.id}\`)`,
value: `<t:${line.timestamp}:R>`,
})),
},
],
};
};
2022-08-16 20:30:58 +00:00
hf.registerCommand(anonradio);
2022-08-03 04:23:46 +00:00
const REGEX_IPV4 = /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$/;
const shodan = new Command("shodan");
shodan.category = CATEGORY;
shodan.helpText = "Look up an IP on Shodan InternetDB";
2023-07-10 00:10:09 +00:00
shodan.callback = async function (msg, line) {
2022-08-03 04:23:46 +00:00
if (!line || line == "") return "Arguments required.";
if (!REGEX_IPV4.test(line)) return "Invalid IP address.";
const data = await fetch("https://internetdb.shodan.io/" + line).then((res) =>
res.json()
);
if (data.detail) return data.detail;
return {
embed: {
title: `Results for \`${data.ip}\``,
fields: [
{
name: "Hostnames",
value:
data.hostnames.length > 0
? data.hostnames.map((str) => `\`${str}\``).join(" ")
2022-08-03 04:23:46 +00:00
: "None",
inline: true,
},
{
name: "Open ports",
value: data.ports.length > 0 ? data.ports.join(", ") : "None",
inline: true,
},
{
name: "Tags",
value:
data.tags.length > 0
? data.tags.map((str) => `\`${str}\``).join(", ")
: "None",
inline: true,
},
{
name: "CPEs",
value:
data.cpes.length > 0
? data.cpes.map((str) => `\`${str}\``).join(" ")
2022-08-03 04:23:46 +00:00
: "None",
inline: true,
},
{
name: "Vulnerabilities",
value:
data.vulns.length > 0
? data.vulns.map((str) => `\`${str}\``).join(" ")
2022-08-03 04:23:46 +00:00
: "None",
inline: true,
},
],
},
};
};
hf.registerCommand(shodan);
const GENERATE_HEADERS = {
Accept: "application/json",
"Content-Type": "application/json",
};
const generate = new Command("generate");
generate.category = CATEGORY;
generate.helpText = "Generate images from prompt via craiyon";
2023-07-10 00:10:09 +00:00
generate.callback = async function (msg, line) {
2022-08-03 04:23:46 +00:00
if (!line || line.length === 0) return "Arguments required.";
msg.channel.sendTyping();
const start = Date.now();
let retries = 0;
let request = await fetch("https://backend.craiyon.com/generate", {
method: "POST",
headers: GENERATE_HEADERS,
2023-07-10 00:10:09 +00:00
body: JSON.stringify({prompt: line}),
2022-08-03 04:23:46 +00:00
});
while (request.status !== 200) {
request = await fetch("https://backend.craiyon.com/generate", {
method: "POST",
headers: GENERATE_HEADERS,
2023-07-10 00:10:09 +00:00
body: JSON.stringify({prompt: line}),
2022-08-03 04:23:46 +00:00
});
retries++;
}
const data = await request.json();
const images = data.images
.map((img) => Buffer.from(img, "base64"))
2023-07-10 00:10:09 +00:00
.map((img, index) => ({contents: img, name: `${index}.jpg`}));
2022-08-03 04:23:46 +00:00
const title = `Responses for "${safeString(line)}"`;
const out = {
2023-07-10 00:10:09 +00:00
content: `Generated in ${formatTime(Date.now() - start)}${
retries > 0 ? " with " + retries + " retries" : ""
}`,
2022-08-03 04:23:46 +00:00
embeds: [],
2022-10-16 22:32:16 +00:00
files: images,
2022-08-03 04:23:46 +00:00
};
let splitIndex = 0;
for (const index in images) {
if (index % 3 == 0) splitIndex++;
out.embeds.push({
title,
url: "https://www.craiyon.com/?" + splitIndex,
image: {
url: `attachment://${index}.jpg`,
},
});
}
return out;
};
hf.registerCommand(generate);
2023-01-18 00:29:36 +00:00
const search = new Command("search");
search.category = CATEGORY;
search.helpText = "Search, powered by LibreX";
search.addAlias("g");
search.addAlias("google");
search.addAlias("ddg");
2023-07-10 00:10:09 +00:00
search.callback = async function (msg, line, args, {results = 2}) {
2023-01-18 00:39:43 +00:00
const query = args.join(" ");
2023-01-18 00:29:36 +00:00
if (!librex) return "LibreX instance not defined.";
if (!query || query == "") return "Search query required.";
2023-01-18 00:29:36 +00:00
2023-01-18 00:39:43 +00:00
const encodedQuery = encodeURIComponent(query);
2023-01-18 00:29:36 +00:00
if (line.startsWith("!")) {
const url = `https://api.duckduckgo.com/?q=${encodedQuery}&format=json`;
2023-01-18 00:29:36 +00:00
const res = await fetch(url);
if (res.url != url) return res.url;
}
2023-09-17 22:28:21 +00:00
const res = await fetch(`${librex}/api.php?q=${encodedQuery}&p=0&t=0`).then(
(res) => res.json()
);
const searchResults = res
.filter((result) => !("did_you_mean" in result))
.splice(0, Number(results));
2023-01-18 00:29:36 +00:00
let out = `__**Results for \`${safeString(query)}\`**__\n`;
for (const result of searchResults) {
2023-01-18 00:29:36 +00:00
if (result.special_response) {
2023-04-20 16:26:42 +00:00
out +=
"> " +
safeString(
parseHtmlEntities(
result.special_response.response.split("\n").join("\n> ")
)
);
out += `\n<${encodeURI(result.special_response.source)}>`;
2023-01-18 00:29:36 +00:00
} else {
2023-04-20 16:26:42 +00:00
out += `**${safeString(parseHtmlEntities(result.title))}** - <${encodeURI(
result.url
)}>`;
2023-01-18 03:56:35 +00:00
out += `\n> ${safeString(parseHtmlEntities(result.description))}`;
2023-01-18 00:29:36 +00:00
}
out += "\n\n";
}
return out.trim();
};
hf.registerCommand(search);
2023-04-27 00:24:08 +00:00
const color = new Command("color");
color.category = CATEGORY;
color.helpText = "Show information on a color or get a random color";
2023-07-10 00:10:09 +00:00
color.callback = async function (msg, line, args, {truerandom}) {
2023-04-27 00:24:08 +00:00
let color = tinycolor(line),
random = false;
if (!line || line == "" || args.length == 0) {
color = truerandom
? tinycolor(Math.floor(Math.random() * 0xffffff))
: randomColor();
random = true;
}
if (!color.isValid) {
return "Color not valid.";
}
const image = await sharp({
create: {
width: 128,
height: 128,
channels: 3,
2023-07-10 00:10:09 +00:00
background: {r: color.r, g: color.g, b: color.b},
2023-04-27 00:24:08 +00:00
},
})
.png()
.toBuffer();
const fileName = `${color.toHex()}.png`;
2023-04-27 00:37:19 +00:00
const fields = [
{
name: "Hex",
value: color.toHexString(),
inline: true,
},
{
name: "RGB",
value: color.toRgbString(),
inline: true,
},
{
name: "HSL",
value: color.toHslString(),
inline: true,
},
{
name: "HSV",
value: color.toHsvString(),
inline: true,
},
{
name: "Integer",
value: color.toNumber(),
inline: true,
},
];
if (color.toName() != false) {
fields.splice(0, 0, {
name: "Name",
value: color.toName(),
inline: true,
});
}
2023-04-27 00:24:08 +00:00
return {
embeds: [
{
title: random ? "Random Color" : "",
color: color.toNumber(),
thumbnail: {
url: `attachment://${fileName}`,
},
2023-04-27 00:37:19 +00:00
fields,
2023-04-27 00:24:08 +00:00
},
],
file: {
file: image,
name: fileName,
},
};
};
hf.registerCommand(color);
2023-06-28 06:00:12 +00:00
function writeVarInt(value) {
let buf = Buffer.alloc(0);
do {
let temp = value & 0b01111111;
value >>>= 7;
if (value != 0) {
temp |= 0b10000000;
}
buf = Buffer.concat([buf, Buffer.from([temp])]);
} while (value != 0);
return buf;
}
const ident = Buffer.from("HiddenPhox (c7.pm) ", "utf8");
const identPort = Buffer.alloc(2);
identPort.writeUInt16BE(3);
const handshake = Buffer.concat([
writeVarInt(0x0),
writeVarInt(1073741953),
writeVarInt(ident.length),
ident,
identPort,
writeVarInt(1),
]);
const handshakeWithLength = Buffer.concat([
writeVarInt(handshake.length),
handshake,
]);
const status = Buffer.concat([writeVarInt(1), writeVarInt(0x0)]);
2023-06-28 06:01:47 +00:00
const HANDSHAKE_PACKET = Buffer.concat([handshakeWithLength, status]);
2023-06-28 06:00:12 +00:00
const formattingToAnsi = {
r: "0",
l: "1",
m: "9",
n: "4",
o: "3",
0: "30",
1: "34",
2: "32",
3: "36",
4: "31",
5: "35",
6: "33",
7: "37",
8: "90",
9: "94",
a: "92",
b: "96",
c: "91",
d: "95",
e: "93",
f: "97",
};
const mcserver = new Command("mcserver");
mcserver.category = CATEGORY;
mcserver.helpText = "Query a Minecraft server";
2023-07-10 00:10:09 +00:00
mcserver.callback = async function (msg, line) {
2023-06-28 06:00:12 +00:00
if (!line || line == "") return "Arguments required.";
2023-06-28 06:08:22 +00:00
const split = line.split(":");
const ip = split[0];
const port = split[1] ?? 25565;
2023-06-28 06:00:12 +00:00
await msg.addReaction("\uD83C\uDFD3");
2023-06-28 06:00:12 +00:00
const data = await new Promise((resolve, reject) => {
2023-06-28 06:10:27 +00:00
logger.verbose("mcserver", "querying", ip, port);
2023-06-28 06:00:12 +00:00
2023-06-28 06:13:32 +00:00
const client = net.createConnection(
{
host: ip,
port: port,
2023-07-10 00:10:09 +00:00
timeout: 180000,
2023-06-28 06:13:32 +00:00
},
2023-07-10 00:10:09 +00:00
function () {
2023-06-28 06:13:32 +00:00
logger.verbose("mcserver", "connect");
client.write(HANDSHAKE_PACKET);
}
);
2023-07-10 00:10:09 +00:00
const timeout = setTimeout(() => {
logger.verbose("mcserver", "timeout");
client.destroy();
resolve("timeout");
}, 180000);
2023-06-28 06:00:12 +00:00
let totalData = Buffer.alloc(0);
2023-07-10 00:10:09 +00:00
client.on("data", function (data) {
2023-06-28 06:01:08 +00:00
totalData = Buffer.concat([totalData, data]);
2023-06-28 06:10:27 +00:00
logger.verbose("mcserver", "data", data.length, totalData.length);
2023-06-28 06:00:12 +00:00
});
2023-07-10 00:10:09 +00:00
client.on("close", function (err) {
2023-06-28 06:08:22 +00:00
if (err) {
2023-06-28 06:10:27 +00:00
logger.verbose("mcserver", "close with error", err);
2023-06-28 06:08:22 +00:00
return reject(err);
}
2023-06-28 06:00:12 +00:00
const dataAsString = totalData.toString().trim();
console.log(dataAsString);
const json = JSON.parse(
dataAsString.slice(
dataAsString.indexOf("{"),
dataAsString.lastIndexOf("}") + 1
)
);
2023-06-28 06:10:27 +00:00
logger.verbose("mcserver", "close", json);
2023-06-28 06:00:12 +00:00
clearTimeout(timeout);
return resolve(json);
});
2023-07-10 00:10:09 +00:00
client.on("timeout", function () {});
2023-06-28 06:00:12 +00:00
});
if (data == "timeout") {
await msg.removeReaction("\uD83C\uDFD3");
2023-06-28 06:00:12 +00:00
return "Timed out trying to query.";
} else {
await msg.removeReaction("\uD83C\uDFD3");
2023-06-28 06:00:12 +00:00
const motd = data.description.text.replace(
/\u00a7([a-f0-9k-or])/gi,
(formatting) => {
const ansi = formattingToAnsi[formatting];
return ansi ? `\x1b[${ansi}m` : "";
}
);
const players = data.players?.sample?.map((player) => player.name) ?? [];
const totalPlayers = `(${data.players.online}/${data.players.max})`;
let image;
if (data.favicon) {
2023-06-28 06:01:08 +00:00
image = Buffer.from(
data.favicon.slice(data.favicon.indexOf(",")),
"base64"
);
2023-06-28 06:00:12 +00:00
}
return {
embed: {
title: `Server info for: \`${line}\``,
fields: [
{
name: "MOTD",
value: `\`\`\`ansi\n${motd}\n\`\`\``,
},
{
name: "Version",
value: `${data.version.name} (\`${data.version.protocol}\`)`,
inline: true,
},
{
name: `Players ${players.length > 0 ? totalPlayers : ""}`,
value: players.length > 0 ? players.join(", ") : totalPlayers,
inline: players.length == 0,
},
],
thumbnail: image && {
url: "attachment://icon.png",
},
},
file: image && {
2023-06-28 06:00:12 +00:00
file: image,
name: "icon.png",
},
};
}
};
hf.registerCommand(mcserver);