codename-t/show.js
2022-12-07 13:56:22 -05:00

491 lines
18 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { Embed } = require("discord.js");
const fs = require("fs");
const dateFormat = require("dateformat");
require('dotenv').config()
const cmd = require('cmd-promise')
var portastic = require('portastic');
const { stderr } = require("process");
let jsonfile = require('jsonfile')
let rand = Math.floor(Math.random() * 99999999999999);
let code
let ifApt
const date = require('date-and-time');
const now = new Date();
const { EmbedBuilder } = require('discord.js');
const Dockerode = require('simple-dockerode');
var docker = new Dockerode({ socketPath: '/var/run/docker.sock' });
let finished
let end = "<=================================END===========================>"
module.exports = {
name: "x",
description: "Execute a command non-interactively.",
options: [{
"name": "cmd",
"description": "Command to Execute",
"required": true,
"type": 3 // 6 is type USER
}],
run: async (client, interaction) => {
console.log("RUN")
await cmd('bash /home/opc/check_exist.sh ' + interaction.user.id).then(out => {
console.log('out =', out)
if (out.stdout != 1) {
(async () => {
finished = 1
console.log(end)
return await interaction.editReply("Sorry, you do not have a container currently, generate one using /generate")
})();
}
}).catch(err => {
console.log('err =', err)
})
console.log("Begin Done")
if (finished == 1) {
finished = 0
return
} else {
// await interaction.deferReply();
const path = 'cache/' + interaction.user.id
const isNotDefined = require("is-not-defined");
if (isNotDefined(interaction.options._hoistedOptions)) {
(async () => {
await interaction.editReply("You must supply a command.")
})();
return
}
let code = interaction.options._hoistedOptions[0].value
if (code.startsWith("apt install") || code.startsWith("yum install")) {
if (!code.includes("-y")) {
code = code + " -y"
console.log(code)
}
}
if (code.startsWith("pacman install")) {
if (!code.includes("--noconfirm")) {
code = code + " --noconfirm"
console.log(code)
}
}
if (code.startsWith("neofetch")) {
code = "neofetch --stdout"
}
if (fs.existsSync(path)) {
console.log("")
}
else {
console.log("No Channel PWD Found! Generating!")
fs.writeFile('./cache/' + interaction.user.id, "{\"pwd\":\"/\"}", function (err) {
});
}
commandToRun = code
if (commandToRun == "yes") return console.log("yes Blocked")
/**
*
* Start of Print Working Directory
*
*/
if (commandToRun == "pwd") {
goNoFurther = true
// check for channel pwd support file
if (fs.existsSync(path)) {
console.log("Channel PWD is active")
jsonfile = require('jsonfile')
jsonfile.readFile(path, function (err, pwdata) {
// console.log(pwdata)
(async () => {
await interaction.editReply("```" + pwdata.pwd + "```")
})();
goNoFurther = false;
if (err) console.error(err)
})
}
function escapeDoubleQuotes(str) {
return str.replace(/\\([\s\S])|(")/g, "\\$1$2"); // thanks @slevithan!
}
}
/**
*
* Main
*
*/
if (commandToRun == "pwd") return
// /**
// *
// * Start of Write
// *
// */
// console.log("cmd: " + commandToRun)
// if (commandToRun.startsWith("write")) {
// const echoFile = require('write');
// const cmd = require('cmd-promise')
// re = /\{([\s\S)]+)\}/;
// re2 = /\^(.*)\^/;
// if (commandToRun.toString().includes("\n")) console.log("YES! BREAK")
// let cdcmdtest = commandToRun // First index is removed and array is returned.
// jsonfile.readFile(path, function (err, pwdata) {
// if (err) console.error(err)
// // Regular Expression To find Sections fo command
// let codeToSend = cdcmdtest.match(re)[1]; // yes, start at 0, not 1. I hate that too.
// console.log("codeToSend: " + codeToSend)
// let fileToSend = cdcmdtest.match(re2)[1]; // yes, start at 0, not 1. I hate that too.
// console.log("file: " + fileToSend)
// // let usrcmd = cdcmdtest.slice(0).join(" ");
// jsonfile.readFile(path, function (err, pwdata) {
// if (err) console.error(err)
// //await interaction.editReply(pwdata.pwd);
// const cmd = require('cmd-promise')
// // let usrcmd = cdcmdtest.slice(0).join(" ");
// console.log("/tmp/tmpfile/" + rand + "/" + fileToSend)
// echoFile.sync("/tmp/tmpfile/" + rand + "/" + fileToSend, codeToSend, {
// newline: true
// });
// console.log('docker cp ' + "/tmp/tmpfile/" + rand + "/" + fileToSend + ' ' + interaction.user.id + ':' + pwdata.pwd)
// cmd('docker cp ' + "/tmp/tmpfile/" + + rand + "/" + fileToSend + ' ' + interaction.user.id + ':' + pwdata.pwd).then(out => {
// console.log('out =', out)
// try {
// fs.unlinkSync("/tmp/tmpfile/" + + rand + "/" + fileToSend)
// console.log("tmpfileremoved")
// rand = Math.floor(Math.random() * 99999999999999);
// } catch (err) {
// console.error(err)
// }
// }).catch(err => {
// console.log('err =', err)
// })
// (async () => {
// await interaction.editReply("File Saved as " + fileToSend);
// })();
// })
// })
// }
/**
*
* Start of CDX
*
*/
// if (commandToRun == "gobk") {
// // check for channel pwd support file
// if (fs.existsSync(path)) {
// console.log("Channel PWD is active")
// jsonfile.readFile(path, function (err, pwdata) {
// if (err) console.error(err)
// console.log(RemoveLastDirectoryPartOf(pwdata.pwd))
// //console.log(dir)
// if (RemoveLastDirectoryPartOf(pwdata.pwd).length == 0) {
// obj = {
// pwd: "/"
// }
// } else {
// obj = {
// pwd: RemoveLastDirectoryPartOf(pwdata.pwd)
// }
// }
// jsonfile.writeFile(path, obj, function (err) {
// (async () => {
// await interaction.editReply(obj.pwd);
// })();
// if (err) console.error(err)
// })
// });
// function RemoveLastDirectoryPartOf(the_url) {
// var the_arr = the_url.split('/');
// the_arr.pop();
// return (the_arr.join('/'));
// }
// function startsWith(str, word) {
// return str.lastIndexOf(word, 0) === 0;
// }
// }
// }
/**
*
* End of CDX
*
*/
/**
*
* Start of CD
*
*/
if (commandToRun.startsWith("cd")) {
console.log("test")
argscmd = interaction.options._hoistedOptions[0].value
if (argscmd == "..") {
(async () => {
await interaction.editReply("please use the gobk command to go back a directory")
})();
return
}
// check for channel pwd support file
if (fs.existsSync(path)) {
console.log("Channel PWD is active")
jsonfile = require('jsonfile')
jsonfile.readFile(path, function (err, pwdata) {
let argscmd = commandToRun.replace("cd ", "")
let dir = argscmd; // yes, start at 0, not 1. I hate that too.
if (startsWith(argscmd, "/") == false) {
const cmd = require('cmd-promise')
if (!argscmd) {
(async () => {
await interaction.editReply("Give my Syntax Please")
})();
return
}
let dir = commandToRun; // yes, start at 0, not 1. I hate that too.
let data
jsonfile.readFile(path, function (err, pwdata) {
if (err) console.error(err)
console.log(dir)
data = pwdata.pwd + "/" + argscmd
if (pwdata.pwd == "/") {
data = "/" + argscmd
}
if (argscmd == "~") {
data = "/root"
}
if (argscmd.includes("~") && argscmd.includes("/")) {
data = "/root" + "/" + argscmd.replace("~", "")
}
if (argscmd.includes("..") || argscmd.includes("../")) { // check if the user is trying to go back a directory
console.log(argscmd.split("../"))
console.log("user wants to go back " + argscmd.split("../").length + " directories")
function RemoveLastDirectoryPartOf(the_url, num) {
var the_arr = the_url.split('/');
the_arr.splice(-num, num)
return (the_arr.join('/'));
}
data = RemoveLastDirectoryPartOf(pwdata.pwd, argscmd.split("../").length - 1)
}
let final = data.replace(/([^:]\/)\/+/g, "$1")
console.log(final)
const obj = {
pwd: final
}
jsonfile.writeFile(path, obj, function (err) {
(async () => {
await interaction.editReply("Directory Changed to: " + final)
})();
if (err) console.error(err)
})
});
} else {
jsonfile.readFile(path, function (err, pwdata) {
if (err) console.error(err)
console.log('dir:' + dir)
//onsole.log(dir)
const obj = {
pwd: dir.replace(/([^:]\/)\/+/g, "$1")
}
jsonfile.writeFile(path, obj, function (err) {
if (err) console.error(err)
})
goNoFurther = false;
});
(async () => {
await interaction.editReply("Directory Changed to: " + dir.replace(/([^:]\/)\/+/g, "$1"))
})();
}
function RemoveLastDirectoryPartOf(the_url) {
var the_arr = the_url.split('/');
the_arr.pop();
return (the_arr.join('/'));
}
function startsWith(str, word) {
return str.lastIndexOf(word, 0) === 0;
}
})
}
}
/**
*
* End of CD
*
*/
if (commandToRun.startsWith("cd")) return console.log("Skipped At Main")
if (commandToRun.startsWith("write")) return
if (commandToRun == "gobk") return
if (fs.existsSync(path)) {
function RemoveLastDirectoryPartOf(the_url) {
var the_arr = the_url.split('/');
the_arr.pop();
return (the_arr.join('/'));
}
console.log("Channel PWD is active")
jsonfile.readFile(path, function (err, pwdata) {
console.log(pwdata)
if (code == "neofetch") {
code = "neofetch --stdout --color_blocks off"
}
if (code.startsWith("apt")) {
ifApt = "-y"
} else if (code.startsWith("yum")) {
ifApt = "-y"
}
else if (code.startsWith("pacman")) {
ifApt = "--noconfirm"
} else if (code.startsWith("apt-get")) {
ifApt = "-y"
}
else {
ifApt = ""
}
if (code.includes("~")) {
code = code.replace("~", "/root")
}
if (code.includes("..")) {
pwdata.pwd = RemoveLastDirectoryPartOf(pwdata.pwd)
}
// if (code.includes("../")) { // check if the user is trying to go back a directory
// function RemoveLastDirectoryPartOf(the_url, num) {
// var the_arr = the_url.split('/');
// the_arr.splice(-num, num)
// return (the_arr.join('/'));
// }
// console.log(argscmd.split("../"))
// console.log("user wants to go back " + argscmd.split("../").length -1 + " directories in their command")
// pwddata.pwd = RemoveLastDirectoryPartOf(pwdata.pwd, argscmd.split("../").length - 1)
// }
const customerContainer = docker.getContainer(interaction.user.id);
// Simple to grab the stdout and stderr.
customerContainer.exec(['/bin/bash', '-c', 'cd ' + pwdata.pwd + ' && ' + commandToRun], { stdout: true, stderr: true }, (err, out) => {
if (typeof (out) !== 'undefined') {
console.log(out.stdout)
if (out.inspect.ExitCode !== 0) {
if (out.stderr.includes("syntax error")) {
(async () => {
await interaction.editReply("```" + "There is an error in your syntax, please try again." + "```")
console.log(end)
})();
} else {
(async () => {
return await interaction.editReply("```" + out.stderr + "```")
console.log(end)
})();
}
}
if (out.inspect.ExitCode == 0) {
if (!out.stdout) {
const mainEmbed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Command Executed Successfully!')
.setDescription('```' + commandToRun + ' has completed.```')
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
(async () => {
return await interaction.editReply({ embeds: [mainEmbed] })
console.log(end)
})();
} else {
if (out.stdout.length > 2020) {
fs.writeFile('/tmp/paste', "Command: " + code.replace("--stdout --color_blocks off", "") + " | Container Owner: " + interaction.user.username + "\n" + out.stdout, err => {
if (err) {
console.error(err)
return
}
})
cmd("sleep 2; cat /tmp/paste | dpaste").then(pasteout => {
const mainEmbed = new EmbedBuilder()
.setColor('#0099ff')
.addFields(
{ name: 'Please check the below output log:', value: pasteout.stdout.replace("Pro tip: you can password protect your paste just by typing a username and password after your paste command.", "").replace("Paste Saved: ", "").replace("-------------------------------------------------------", "") },
).setTitle("Container Owner: " + interaction.user.username)
.setDescription("The command: " + code.replace("--stdout --color_blocks off", "") + " was too large for discord.")
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
(async () => {
console.log(end)
return await interaction.editReply({ embeds: [mainEmbed] })
})();
})
}
else {
// console.log("ahah " + code)
if (code.includes("dpaste")) {
const mainEmbed = new EmbedBuilder()
.setColor('#0099ff')
.addFields(
{ name: 'View your Paste at the link below!', value: out.stdout.replace("Pro tip: you can password protect your paste just by typing a username and password after your paste command.", "").replace("Paste Saved: ", "").replace("-------------------------------------------------------", "") },
{ name: 'Pro Tip!', value: "You can protect your paste by typing a username and password after dpaste." },
).setTitle("Paste Saved!")
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
(async () => {
return await interaction.editReply({ embeds: [mainEmbed] })
console.log(end)
})();
return
}
if (commandToRun.startsWith("cowsay") || commandToRun.startsWith("figlet")) {
(async () => {
await interaction.editReply("```" + out.stdout + "```")
})();
return
}
if (code.includes("figlet") || code.includes("figlet")) {
(async () => {
return await interaction.editReply("```" + out.stdout + "```")
console.log(end)
})();
}
//<@UserID NUMBER>
(async () => {
await interaction.editReply("```" + "Command: " + code.replace("--stdout --color_blocks off", "") + " | Container Owner: " + interaction.user.username + "\n" + out.stdout + "```")
console.log("<=================================END===========================>")
})();
}
}
}
} else {
(async () => {
await interaction.editReply("```" + "Your container either needs to be generated or is not running." + "```")
return console.log(end)
})();
}
})
})
}
}
},
};