Skip to content

Instantly share code, notes, and snippets.

@NotNite
Created May 18, 2023 17:28
Show Gist options
  • Save NotNite/c72a1d733a38c3b4e39dff9dfcca2d47 to your computer and use it in GitHub Desktop.
Save NotNite/c72a1d733a38c3b4e39dff9dfcca2d47 to your computer and use it in GitHub Desktop.
screeps-webhook.js
const https = require("https");
function ivmWrap(sandbox, name, func) {
const ivm = require("isolated-vm");
const sandboxContext = sandbox.getContext();
const sandboxGlobal = sandboxContext.global;
const sandboxIsolate = sandbox.getIsolate();
sandboxGlobal.setSync("_notnet_ivm", ivm);
sandboxGlobal.setSync("_notnet_" + name, new ivm.Reference(func));
const bootstrap = sandboxIsolate.compileScriptSync(`(function() {
let ivm = _notnet_ivm;
delete _notnet_ivm;
let temp = _notnet_${name};
delete _notnet_${name};
if (global.notnet == undefined) {
global.notnet = {};
}
global.notnet.${name} = function(...args) {
temp.applyIgnored(undefined, args.map(arg => new ivm.ExternalCopy(arg).copyInto()));
}
})();`);
bootstrap.runSync(sandboxContext);
}
// https://stackoverflow.com/a/67094088
function post(url, data) {
const dataString = JSON.stringify(data);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": dataString.length
},
timeout: 1000
};
return new Promise((resolve, reject) => {
const req = https.request(url, options, (res) => {
const body = [];
res.on("data", (chunk) => body.push(chunk));
res.on("end", () => {
const resString = Buffer.concat(body).toString();
resolve(resString);
});
});
req.on("error", (err) => {
reject(err);
});
req.on("timeout", () => {
req.destroy();
reject(new Error("Request time out"));
});
req.write(dataString);
req.end();
});
}
module.exports = function(config) {
if (config.engine) {
config.engine.on("playerSandbox", function(sandbox, userID) {
ivmWrap(sandbox, "webhook", async function(channel, token, data) {
const url = "https://canary.discord.com/api/webhooks/" + channel + "/" + token;
return post(url, data);
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment