first ever commit1!1!1

This commit is contained in:
ChomeNS 2022-08-14 16:51:45 +07:00
commit 2b92838f38
69 changed files with 3037 additions and 0 deletions

17
.eslintrc.json Normal file
View file

@ -0,0 +1,17 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"google"
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
"linebreak-style": 0,
"require-jsdoc": 0
}
}

11
.gitignore vendored Normal file
View file

@ -0,0 +1,11 @@
/botchatbot.js
/bruhifyBot.js
/commandsHelp.json
/launcher_accounts.json
/makenewscript
/node_modules
/notonline.txt
/package-lock.json
/song.js
/test.js
/testPy.py

7
changelog.json Normal file
View file

@ -0,0 +1,7 @@
[
"Validate command",
"New hash system",
"Fixed cloop command",
"Alias support for *help [command]",
"Music command"
]

16
commands/ayunsudo.js Normal file
View file

@ -0,0 +1,16 @@
module.exports = {
name: 'ayunsudo',
alias: [],
description: 'Sudo everyone on Ayunboom!',
trusted: 1,
usage: '<hash> <c:|command>',
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
for (const property of bot.players.list) {
bot.core.run('essentials:sudo ' + property.UUID + ' ' + args[1]);
}
} else {
throw new Error('Invalid hash');
}
},
};

11
commands/botuser.js Normal file
View file

@ -0,0 +1,11 @@
/* eslint-disable max-len */
module.exports = {
name: 'botuser',
alias: [],
description: 'Shows the bot\'s username and UUID',
usage: '',
trusted: 0,
execute: function(bot) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'The bot\'s username is: ', color: 'white'}, {text: `${bot.username}`, color: 'gold', clickEvent: {action: 'copy_to_clipboard', value: `${bot.username}`}, hoverEvent: {action: 'show_text', contents: [{text: 'Click here to copy the username to your clipboard', color: 'green'}]}}, {text: ' and the uuid is: '}, {text: `${bot.uuid}`, color: 'aqua', clickEvent: {action: 'copy_to_clipboard', value: `${bot.uuid}`}, hoverEvent: {action: 'show_text', contents: [{text: 'Click here to copy the uuid to your clipboard', color: 'green'}]}}]));
},
};

25
commands/botvisibility.js Normal file
View file

@ -0,0 +1,25 @@
/* eslint-disable max-len */
module.exports = {
name: 'botvisibility',
alias: [],
description: 'Changes the bot\'s visibility',
usage: '<hash> <true|false>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
if (args[1]==='true') {
bot.visibility = true;
bot.chat('/essentials:vanish disable');
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'The bot\'s visibility is now ', color: 'white'}, {text: 'visible', color: 'green'}]));
} else if (args[1]==='false') {
bot.visibility = false;
bot.chat('/essentials:vanish enable');
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'The bot\'s visibility is now ', color: 'white'}, {text: 'invisible', color: 'gold'}]));
} else {
throw new SyntaxError('Invalid argument');
}
} else {
throw new Error('Invalid hash');
}
},
};

20
commands/bruhify.js Normal file
View file

@ -0,0 +1,20 @@
/* eslint-disable max-len */
const {MessageEmbed} = require('discord.js');
module.exports = {
name: 'bruhify',
alias: [],
description: 'RecycleBot bruhify but actionbar',
usage: '<message>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
bot.bruhifyText = args.join(' ');
},
discordExecute: function(bot, username, usernameraw, sender, prefix, args, channeldc) {
bot.bruhifyText = args.join(' ');
const Embed = new MessageEmbed()
.setColor('#FFFF00')
.setTitle('Bruhify')
.setDescription(`Bruhify set to: ${bot.bruhifyText}`);
channeldc.send({embeds: [Embed]});
},
};

14
commands/cb.js Normal file
View file

@ -0,0 +1,14 @@
/* eslint-disable max-len */
module.exports = {
name: 'cb',
alias: ['cmd', 'commandblock', 'run'],
desription: 'Executes a command in the command core',
usage: '<command>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
bot.core.run(args.join(' '));
},
discordExecute: function(bot, username, usernameraw, sender, prefix, args, channeldc) {
bot.core.run(args.join(' '));
},
};

29
commands/changelog.js Normal file
View file

@ -0,0 +1,29 @@
/* eslint-disable max-len */
const changelog = require('../changelog.json');
const {MessageEmbed} = require('discord.js');
module.exports = {
name: 'changelog',
alias: ['changelogs'],
description: 'Shows the bot\'s changelog',
usage: '',
trusted: 0,
execute: function(bot) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Changelogs:', color: 'green'}]));
changelog.forEach((message, number) => {
number += 1;
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: `${number}`, color: 'gray'}, {text: ' - ', color: 'dark_gray'}, {text: message, color: 'gray'}]));
});
},
discordExecute: function(bot, username, usernameraw, sender, prefix, args, channeldc) {
changelogs = '';
changelog.forEach((message, number) => {
number += 1;
changelogs += `\`${number}\` - \`${message}\`` + '\n';
});
const Embed = new MessageEmbed()
.setColor('#FFFF00')
.setTitle('Changelogs')
.setDescription(changelogs);
channeldc.send({embeds: [Embed]});
},
};

16
commands/clearchat.js Normal file
View file

@ -0,0 +1,16 @@
/* eslint-disable max-len */
module.exports = {
name: 'clearchat',
alias: ['cc'],
description: 'Clears the chat',
usage: '[specific] <player>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]==='specific') {
bot.core.run(`minecraft:tellraw ${args[1]} ` + JSON.stringify([{text: `${'\n'.repeat(100)}`, color: 'white'}, {text: `Your chat has been cleared by ${username}.`, color: 'dark_green'}]));
return;
} else {
bot.core.run(`minecraft:tellraw @a ` + JSON.stringify([{text: `${'\n'.repeat(100)}`, color: 'white'}, {text: 'The chat has been cleared.', color: 'dark_green'}]));
}
},
};

View file

@ -0,0 +1,12 @@
module.exports = {
name: 'clearchatqueue',
description: 'Clears the bot\'s chat queue',
alias: ['ccq'],
usage: '',
trusted: 0,
execute: function(bot) {
if (bot.queue[0]) {
bot.queue = [];
}
},
};

101
commands/cloop.js Normal file
View file

@ -0,0 +1,101 @@
/* eslint-disable max-len */
bot.cloops = [];
function add(command, interval, bot) {
const id = setInterval(() => bot.core.run(command), interval);
bot.cloops.push({id, interval, command});
}
function remove(item) {
clearInterval(bot.cloops[item].id);
bot.cloops.splice(item, 1);
}
function clear() {
for (const interval of bot.cloops) clearInterval(interval.id);
bot.cloops = [];
}
function list(bot) {
const message = [];
message.push({text: 'Cloops:', color: 'green'});
message.push('\n')
for (const [id, cloop] of Object.entries(bot.cloops)) {
message.push({text: id, color: 'aqua'});
message.push({text: ' > ', color: 'gold'});
message.push({text: cloop.command, color: 'green'});
message.push({text: ' - ', color: 'gold'});
message.push({text: cloop.interval, color: 'green'});
message.push('\n');
}
message.pop();
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(message));
}
module.exports = {
name: 'cloop',
alias: [],
description: 'Loop commands',
usage: '<hash> <add|remove|removeall|list> <interval|index> <command>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[1]==='add') {
if (args[0]===bot.hash) {
if (typeof args[3]!=='undefined') {
// bot.cloopnumbers++;
// bot.clooparr.push(args.slice(3).join(' '));
// eval(`bot.command${bot.cloopnumbers} = args.slice(3).join(' ')`);
// eval(`bot.interval${bot.cloopnumbers} = args[2]`);
// eval(`bot.cloop${bot.cloopnumbers} = setInterval(() => { bot.core.run(bot.command${bot.cloopnumbers}) }, bot.interval${bot.cloopnumbers})`);
// eval(`bot.core.run('minecraft:tellraw @a ["",{"text":"Added command ","color":"white"},{"text":"' + bot.command${bot.cloopnumbers} + '","color":"aqua"},{"text":" with interval ","color":"white"},{"text":"' + bot.interval${bot.cloopnumbers} + '","color":"green"},{"text":" to the cloops","color":"white"}]')`);
add(args.slice(3).join(' '), args[2], bot);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Added command ', color: 'white'}, {text: `${args.slice(3).join(' ')}`, color: 'aqua'}, {text: ' with interval ', color: 'white'}, {text: `${args[2]}`, color: 'green'}, {text: ' to the cloops', color: 'white'}]));
}
} else {
throw new Error('Invalid hash');
}
return;
}
if (args[1]==='list') {
if (args[0]===bot.hash) {
// bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'Cloops:'}]));
// bot.clooparr.forEach((item, index) => {
// bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: `${index}`, color: 'aqua'}, {text: ' > ', color: 'gold'}, {text: `${item}`, color: 'green'}]));
// });
list(bot);
} else {
throw new Error('Invalid hash');
}
return;
}
if (args[1]==='remove') {
if (args[0]===bot.hash) {
// eval(`if (typeof bot.cloop${Number(args[2])}==='undefined'){ throw new Error('Invalid index') }`);
// bot.clooparr.shift(Number(args[2]));
// eval(`clearInterval(bot.cloop${Number(args[2])})`);
// bot.cloopnumbers - 1;
remove(args[2]);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'Removed cloop '}, {text: args[2], color: 'aqua'}]));
} else {
throw new Error('Invalid hash');
}
return;
}
if (args[1]==='removeall') {
if (args[0]===bot.hash) {
// for (let i = 0; i <= bot.cloopnumbers; i++) {
// bot.clooparr.shift(i);
// eval(`clearInterval(bot.cloop${i})`);
// }
// bot.cloopnumbers = -1;
clear();
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'Removed all looped commands', color: 'white'}]));
} else {
throw new Error('Invalid hash');
}
return;
}
},
};

18
commands/cow.js Normal file
View file

@ -0,0 +1,18 @@
/* eslint-disable max-len */
module.exports = {
name: 'cow',
alias: [],
description: 'Summon cows at everyone',
usage: '[specific] <player>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]==='specific') {
const specific = args[1];
bot.core.run(`minecraft:execute unless entity @s[name= run ] run execute as @a at ${specific} run summon cow`);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {'text': 'Cows ', 'color': '#FCA6A6'}, {'text': 'spawning at ' + `${specific}`, 'color': 'white'}]));
} else {
bot.core.run('minecraft:execute unless entity @s[name= run ] run execute as @a at @r[\'limit\'=10] run summon cow');
bot.core.run('minecraft:tellraw @a ["",{"text":"Cows ","color":"white"},{"text":"spawned at everyone","color":"white"}]');
}
},
};

12
commands/cowsay.js Normal file
View file

@ -0,0 +1,12 @@
/* eslint-disable max-len */
const cowsay = require('cowsay');
module.exports = {
name: 'cowsay',
alias: [],
description: 'Moo',
usage: '<message>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${cowsay.say({text: args.join(' ')})}`}));
},
};

11
commands/creator.js Normal file
View file

@ -0,0 +1,11 @@
/* eslint-disable max-len */
module.exports = {
name: 'creator',
alias: [],
description: 'Shows the bot\'s creator',
usage: '',
trusted: 0,
execute: function(bot) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: 'ChomeNS Bot was created by chayapak', color: 'yellow'}));
},
};

10
commands/discord.js Normal file
View file

@ -0,0 +1,10 @@
module.exports = {
name: 'discord',
alias: [],
description: 'Shows the discord invite',
usage: '',
trusted: 0,
execute: function(bot) {
bot.core.run('minecraft:tellraw @a ["",{"text":"The Discord invite is ","color":"white"},{"text":"https://discord.gg/xdgCkUyaA4","color":"blue","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"}}]');
},
};

30
commands/eaglercrash.js Normal file
View file

@ -0,0 +1,30 @@
/* eslint-disable max-len */
module.exports = {
name: 'eaglercrash',
alias: [],
description: 'Lags Eaglercraft and crashes it',
usage: '<on|off> <hash>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[1]==='on') {
if (args[0]===bot.hash) {
bot.eaglercrashstarted = true;
bot.eaglercrash = setInterval(async function() {
if (bot.eaglercrashstarted===true) return bot.core.run('minecraft:playsound block.note_block.harp record @a ~ ~ ~ 100000000000000000000000000000000000000 1 0');
}, 0);
bot.core.run('minecraft:tellraw @a ["",{"text":"Eaglercrash started","color":"white"}]');
} else {
throw new Error('Invalid hash');
}
}
if (args[1]==='off') {
if (args[0]===bot.hash) {
clearInterval(bot.eaglercrash);
bot.eaglercrashstarted = false;
bot.core.run('minecraft:tellraw @a ["",{"text":"Eaglercrash stopped","color":"white"}]');
} else {
throw new Error('Invalid hash');
}
}
},
};

14
commands/echo.js Normal file
View file

@ -0,0 +1,14 @@
/* eslint-disable max-len */
module.exports = {
name: 'echo',
alias: [],
description: 'Says a message',
usage: '<message>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
bot.chat(args.join(' '));
},
discordExecute: function(bot, username, usernameraw, sender, prefix, args, channeldc) {
bot.chat(args.join(' '));
},
};

14
commands/end.js Normal file
View file

@ -0,0 +1,14 @@
module.exports = {
name: 'end',
alias: [],
description: 'Ends the bot\'s client',
usage: '<hash>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
bot.emit('end', 'end command');
} else {
throw new Error('Invalid hash');
}
},
};

19
commands/entity.js Normal file
View file

@ -0,0 +1,19 @@
/* eslint-disable max-len */
module.exports = {
name: 'entity',
alias: [],
description: 'Summon any entity!',
usage: '[specific] <player>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (typeof args[0]==='undefined') return;
const entity = args[0];
if (typeof args[1]==='undefined') {
bot.core.run('minecraft:execute unless entity @s[name= run ] run execute as @a at @r[\'limit\'=10] run summon ' + entity);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'Entity ', color: 'white'}, {text: `"${entity}" `, color: 'green'}, {text: 'spawning at everyone...', color: 'white'}]));
} else if (args[1]==='specific' && typeof args[2]!=='undefined') {
bot.core.run('minecraft:execute unless entity @s[name= run ] run execute as @a at ' + args[2] + ' run summon ' + entity);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: `Entity `, color: 'white'}, {text: `"${entity}" `, color: 'green'}, {text: 'spawning at ', color: 'white'}, {text: `${args[2]}`, color: 'aqua'}]));
}
},
};

51
commands/eval.js Normal file
View file

@ -0,0 +1,51 @@
/* eslint-disable max-len */
const {VM} = require('vm2');
const axios = require('axios');
const util = require('util');
const querystring = require('querystring');
const {stylize} = require('../util/colors/minecraft');
module.exports = {
name: 'eval',
alias: [],
description: 'Safe eval 100% secure!!!',
trusted: 0,
usage: '<run|reset|server|dineval> <code>',
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]==='run') {
try {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${util.inspect(bot.vm.run(args.slice(1).join(' ')), {stylize: stylize})}`.substring(0, 1900)}));
} catch (err) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${util.inspect(err).replaceAll('runner', 'chayapak1')}`, color: 'red'}));
}
}
if (args[0]==='reset') {
bot.vm = new VM(bot.vmoptions);
}
if (args[0]==='server') {
axios
.post('http://192.168.1.105:4445/', querystring.stringify({
html: false,
showErrorMsg: false,
colors: 'minecraft',
code: args[1],
})).then((res) => {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${res.data}`}));
}).catch((e) => {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${e}`, color: 'red'}));
});
}
if (args[0]==='dineval') {
axios
.get('https://eval.dinhero21.repl.co', {
headers: {
data: args[1],
colors: 'minecraft',
},
}).then((res) => {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${res.data}`}));
}).catch((e) => {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${e}`, color: 'red'}));
});
}
},
};

15
commands/executebypass.js Normal file
View file

@ -0,0 +1,15 @@
/* eslint-disable max-len */
module.exports = {
name: 'executebypass',
alias: [],
description: 'Execute command bypassed',
usage: '<hash> <command>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
bot.core.run('minecraft:execute unless entity @s[name= run ] run ' + args.slice(1).join(' '));
} else {
throw new Error('Invalid hash');
}
},
};

15
commands/gamemodeall.js Normal file
View file

@ -0,0 +1,15 @@
/* eslint-disable max-len */
module.exports = {
name: 'gamemodeall',
alias: [],
description: 'Gamemode everyone',
usage: '<hash> <gamemode>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
bot.core.run(`minecraft:execute unless entity @s[name= run ] run gamemode ${args[1]} @a[name=!${bot.username}]`);
} else {
throw new Error('Invalid hash');
}
},
};

100
commands/help.js Normal file
View file

@ -0,0 +1,100 @@
/* eslint-disable no-var */
/* eslint-disable max-len */
const {MessageEmbed} = require('discord.js');
module.exports = {
name: 'help',
alias: ['heko', 'cmds', 'commands'],
description: 'Shows the help',
usage: '[command]',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
let generalCommands = '';
let trustedCommands = '';
let ownerCommands = '';
for (const command of bot.command_handler.commands) {
if (command.trusted!==0) continue;
generalCommands += ' ' + command.name;
}
for (const command of bot.command_handler.commands) {
if (command.trusted!==1) continue;
trustedCommands += ' ' + command.name;
}
for (const command of bot.command_handler.commands) {
if (command.trusted!==2) continue;
ownerCommands += ' ' + command.name;
}
if (typeof args[0]!=='undefined') {
for (const command of bot.command_handler.commands) {
function m() {
let discordSupported;
let alias = command.name;
if (typeof command.discordExecute==='undefined') {
discordSupported = 'false';
} else {
discordSupported = 'true';
}
if (command.alias.toString()!=='') {
alias = command.alias.join(', ');
}
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: prefix + command.name, color: 'gold'}, {text: ` (${alias})`, color: 'white'}, {text: ' - ', color: 'gray'}, {text: command.description, color: 'gray'}]));
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Trust level: ', color: 'green'}, {text: command.trusted, color: 'yellow'}]));
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Supported on Discord: ', color: 'green'}, {text: discordSupported, color: 'gold'}]));
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: prefix + command.name, color: 'gold'}, {text: ' ' + command.usage, color: 'aqua'}]));
}
if (command.name===args[0]) m();
for (const alias of command.alias) {
if (alias===args[0]) m();
}
};
} else {
const pre = [{'text': 'Commands ', 'color': 'gray'}, {'text': '(', 'color': 'gray'}, {'text': '⬤ Public', 'color': 'green'}, {'text': ' ⬤ Trusted', 'color': 'red'}, {'text': ' ⬤ Owner', 'color': 'dark_red'}, {'text': ') -', 'color': 'gray'}];
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([pre, {text: generalCommands, color: 'green'}, {text: trustedCommands, color: 'red'}, {text: ownerCommands, color: 'dark_red'}]));
}
},
discordExecute: function(bot, username, usernameraw, sender, prefix, args, channeldc) {
let commands = '';
for (const command of bot.command_handler.commands) {
commands += command.name + ' ';
}
if (typeof args[0]!=='undefined') {
for (const command of bot.command_handler.commands) {
if (command.name===args[0]) {
let discordSupported;
let alias = command.name;
if (typeof command.discordExecute==='undefined') {
discordSupported = 'false';
} else {
discordSupported = 'true';
}
if (command.alias.toString()!=='') {
alias = command.alias.join(', ');
}
const Embed = new MessageEmbed()
.setColor('#FFFF00')
.setTitle(`${prefix + command.name} (${alias}) - ${command.description}`)
.setDescription(`Trust level: ${commands.trusted}` + '\n' + `${prefix + command.name} ${command.usage}` + '\n' + `Supported: ${discordSupported}`);
channeldc.send({embeds: [Embed]});
} else {
throw new SyntaxError('Invalid command');
}
};
} else {
let supportedCommands = '';
let unsupportedCommands = '';
for (const command of bot.command_handler.commands) {
if (typeof command.discordExecute==='undefined') continue;
supportedCommands += command.name + ' ';
}
for (const command of bot.command_handler.commands) {
if (typeof command.discordExecute!=='undefined') continue;
unsupportedCommands += command.name + ' ';
}
const Embed = new MessageEmbed()
.setColor('#FFFF00')
.setTitle('Commands')
.setDescription('**Supported Commands**\n' + supportedCommands + '\n**Unsupported Commands**\n' + unsupportedCommands);
channeldc.send({embeds: [Embed]});
}
},
};

30
commands/list.js Normal file
View file

@ -0,0 +1,30 @@
/* eslint-disable max-len */
const sleep = (t) => new Promise((a) => setTimeout(a, t));
const {MessageEmbed} = require('discord.js');
module.exports = {
name: 'list',
alias: [],
description: 'List players',
usage: '',
trusted: 0,
execute: async function(bot) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'Players:', color: 'green'}]));
await sleep(60);
for (const property of bot.tabcompleteplayers) {
if (property.match.startsWith('@')) continue;
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: `${property.match}`, color: 'yellow'}, {text: ' ', color: 'aqua'}, {text: `${bot.players.getPlayer(property.match).UUID}`, color: 'aqua'}]));
}
},
discordExecute: async function(bot, username, usernameraw, sender, prefix, args, channeldc) {
let players = '';
for (const property of bot.tabcompleteplayers) {
if (property.match.startsWith('@')) continue;
players += `\`${property.match}\` \`${bot.players.getPlayer(property.match).UUID}\`` + '\n';
}
const Embed = new MessageEmbed()
.setColor('#FFFF00')
.setTitle('Players')
.setDescription(players);
channeldc.send({embeds: [Embed]});
},
};

88
commands/music.js Normal file
View file

@ -0,0 +1,88 @@
/* eslint-disable max-len */
const fs = require('fs/promises');
const path = require('path');
const fileExists = require('../util/file-exists');
const list = require('../util/file-list');
const axios = require('axios');
const os = require('os');
let SONGS_PATH;
if (os.hostname()==='chomens-kubuntu') {
SONGS_PATH = path.join(__dirname, '..', '..', 'nginx-html', 'midis');
} else {
SONGS_PATH = path.join(__dirname, '..', 'midis');
}
module.exports = {
name: 'music',
description: 'Plays music',
alias: [],
trusted: 0,
usage: '<play|playurl|stop|loop|list|nowplaying> <song>',
execute: function(bot, username, usernameraw, sender, prefix, args) {
async function play(bot, values) {
try {
const filepath = values.join(' ');
const absolutePath = await resolve(filepath);
const song = bot.music.load(await fs.readFile(absolutePath), path.basename(absolutePath));
bot.music.play(song);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Now playing '}, {text: song.name, color: 'gold'}]));
} catch (e) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: 'SyntaxError: Invalid file', color: 'red'}));
}
}
async function playUrl(bot, values) {
try {
const url = values.join(' ');
const response = await axios.get('https://http-proxy.nongsonchome.repl.co', {
params: {
uri: url,
},
responseType: 'arraybuffer',
});
const song = bot.music.load(response.data, url);
bot.music.play(song);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Now playing '}, {text: song.name, color: 'gold'}]));
} catch (e) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: 'SyntaxError: Invalid URL', color: 'red'}));
}
}
async function resolve(filepath) {
if (!path.isAbsolute(filepath) && await fileExists(SONGS_PATH)) {
return path.join(SONGS_PATH, filepath);
}
return filepath;
}
bot.music.list = async function(bot) {
const absolutePath = await resolve(SONGS_PATH);
const listed = await list(absolutePath);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: listed.join(''), color: 'green'}));
};
if (args[0]==='play') {
play(bot, args.slice(1));
}
if (args[0]==='playurl') {
playUrl(bot, args.slice(1));
}
if (args[0]==='stop') {
bot.music.stop();
}
if (args[0]==='loop') {
bot.music.loop = !bot.music.loop;
const loop = bot.music.loop ? {text: 'enabled', color: 'green'} : {text: 'disabled', color: 'red'};
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Looping is now '}, loop]));
}
if (args[0]==='list') {
bot.music.list(bot);
}
if (args[0]==='nowplaying') {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Now playing '}, {text: bot.music.song.name, color: 'gold'}]));
}
},
};

11
commands/myuser.js Normal file
View file

@ -0,0 +1,11 @@
/* eslint-disable max-len */
module.exports = {
name: 'myuser',
alias: [],
description: 'Shows your username (not nickname)',
usage: '',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'Your username is: ', color: 'white'}, {text: `${bot.getplayerusername[sender]}`, color: 'gold', clickEvent: {action: 'copy_to_clipboard', value: `${bot.getplayerusername[sender]}`}, hoverEvent: {action: 'show_text', contents: [{text: 'Click here to copy the username to your clipboard', color: 'green'}]}}] ));
},
};

18
commands/pig.js Normal file
View file

@ -0,0 +1,18 @@
/* eslint-disable max-len */
module.exports = {
name: 'pig',
alias: [],
description: 'Summon pigs at everyone',
usage: '[specific] <player>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]==='specific') {
const specific = args[1];
bot.core.run(`minecraft:execute unless entity @s[name= run ] run execute as @a at ${specific} run summon pig`);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {'text': 'Pigs ', 'color': 'white'}, {'text': 'spawning at ' + `${specific}`, 'color': 'white'}]));
} else {
bot.core.run('minecraft:execute unless entity @s[name= run ] run execute as @a at @r[\'limit\'=10] run summon pig');
bot.core.run('minecraft:tellraw @a ["",{"text":"Pigs ","color":"#FCA6A6"},{"text":"spawned at everyone","color":"white"}]');
}
},
};

10
commands/refillcore.js Normal file
View file

@ -0,0 +1,10 @@
module.exports = {
name: 'refillcore',
alias: ['rc'],
description: 'Resets the bot\'s command core',
usage: '',
trusted: 0,
execute: function(bot) {
bot.core.fillCore();
},
};

14
commands/rtp.js Normal file
View file

@ -0,0 +1,14 @@
/* eslint-disable max-len */
const {between} = require('../util/between');
module.exports = {
name: 'rtp',
alias: [],
description: 'Randomly teleports the player',
usage: '',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
const rtppos = `${between(20000000, 500000)} 100 ${between(20000000, 500000)}`;
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Teleporting ', color: 'white'}, {text: username, color: 'aqua'}, {text: ' to ', color: 'white'}, {text: rtppos, color: 'green'}, {text: '...', color: 'white'}]));
bot.core.run(`minecraft:execute unless entity @s[name= run ] run tp ${username} ${rtppos}`);
},
};

21
commands/servereval.js Normal file
View file

@ -0,0 +1,21 @@
/* eslint-disable max-len */
const util = require('util');
const {stylize} = require('../util/colors/minecraft');
module.exports = {
name: 'servereval',
alias: [],
description: 'Eval command without vm2',
trusted: 2,
usage: '<ownerhash> <code>',
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.ownerHash) {
try {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${util.inspect(eval(args.slice(1).join(' ')), {stylize: stylize})}`.substring(0, 1900)}));
} catch (err) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${util.inspect(err).replaceAll('runner', 'chayapak1')}`, color: 'red'}));
}
} else {
throw new Error('Invalid OwnerHash');
}
},
};

14
commands/stopserver.js Normal file
View file

@ -0,0 +1,14 @@
module.exports = {
name: 'stopserver',
alias: [],
description: 'Stops the stopserver',
usage: '<hash>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
bot.core.run('minecraft:execute unless entity @s[name= run ] run stop');
} else {
throw new Error('Invalid hash');
}
},
};

19
commands/test.js Normal file
View file

@ -0,0 +1,19 @@
/* eslint-disable max-len */
const {MessageEmbed} = require('discord.js');
module.exports = {
name: 'test',
alias: [],
description: 'Tests if the bot is working',
usage: '',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {'text': `Username: ${username},`, 'color': 'green'}, {'text': ` Raw username: ${usernameraw},`, 'color': 'green'}, {'text': ` Sender UUID: ${sender},`, 'color': 'green'}, {'text': ` Prefix: ${prefix},`, 'color': 'green'}, {'text': ` Args: ${args.join(', ').toString()}`, 'color': 'green'}]));
},
discordExecute: function(bot, username, usernameraw, sender, prefix, args, channeldc) {
const Embed = new MessageEmbed()
.setColor('#FFFF00')
.setTitle('Hello!')
.setDescription('This is the first ever command to be discordified!' + '\n' + `More info: Username: ${username}, Prefix: ${prefix}, Args: ${args.join(' ')}`);
channeldc.send({embeds: [Embed]});
},
};

25
commands/time.js Normal file
View file

@ -0,0 +1,25 @@
/* eslint-disable max-len */
const moment = require('moment-timezone');
module.exports = {
name: 'time',
alias: [],
description: 'Shows the time',
usage: '<timezone>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
const timezone = args.join(' ');
const momented = moment().tz(`${timezone}`).format('dddd, MMMM Do, YYYY, h:mm:ss A');
const command = 'minecraft:tellraw @a ' + JSON.stringify(['', {text: 'The current date and time for the timezone ', color: 'white'}, {text: timezone, color: 'aqua'}, {text: ' is: ', color: 'white'}, {text: `${momented}`, color: 'green'}]);
if (timezone.toLowerCase()==='asia/bangkok') {
bot.core.run(command);
return;
} else if (timezone.toLowerCase()==='utc') {
bot.core.run(command);
return;
} else if (momented===moment().format('dddd, MMMM Do, YYYY, h:mm:ss A')) {
throw new SyntaxError('Invalid timezone');
} else {
bot.core.run(command);
}
},
};

15
commands/tpall.js Normal file
View file

@ -0,0 +1,15 @@
/* eslint-disable max-len */
module.exports = {
name: 'tpall',
alias: [],
description: 'Teleport everyone',
usage: '<hash> <player>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
bot.core.run(`minecraft:execute unless entity @s[name= run ] run tp @a ${args.slice(1).join(' ')}`);
} else {
throw new Error('Invalid hash');
}
},
};

17
commands/translate.js Normal file
View file

@ -0,0 +1,17 @@
/* eslint-disable max-len */
const translate = require('@vitalets/google-translate-api');
module.exports = {
name: 'translate',
alias: [],
description: 'Translate a message from any language to any language using Google Translate',
usage: '<language 1> <language 2> <message>',
trusted: 0,
execute: async function(bot, username, usernameraw, sender, prefix, args) {
try {
const res = await translate(args.slice(2).join(' '), {from: args[0], to: args[1]});
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'Result: ', color: 'gold'}, {text: res.text, color: 'green'}]));
} catch (e) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: String(e), color: 'red'}));
}
},
};

12
commands/uptime.js Normal file
View file

@ -0,0 +1,12 @@
/* eslint-disable max-len */
const {secondsToHms} = require('../util/secondToHms');
module.exports = {
name: 'uptime',
alias: [],
description: 'Shows the bot\'s uptime',
usage: '',
trusted: 0,
execute: function(bot) {
bot.core.run(`minecraft:tellraw @a ["",{"text":"The bot's uptime is ","color":"white"},{"text":"${secondsToHms(Math.floor(performance.now() / 1000))}","color":"green"}]`); return;
},
};

20
commands/urban.js Normal file
View file

@ -0,0 +1,20 @@
/* eslint-disable max-len */
const urban = require('urban-dictionary');
module.exports = {
name: 'urban',
alias: [],
description: 'Working Urban Dictionary',
usage: '<word>',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
urban.autocompleteExtra(args[0], (error, results) => {
if (error) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: '[', color: 'dark_red'}, {text: 'Urban', color: 'red'}, {text: '] ', color: 'dark_red'}, {text: error.message, color: 'red'}]));
return;
}
results.forEach(({preview, term}) => {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: '[', color: 'dark_red'}, {text: 'Urban', color: 'red'}, {text: '] ', color: 'dark_red'}, {text: term, color: 'white'}, {text: ' - ', color: 'white'}, {text: preview, color: 'white'}]));
});
});
},
};

18
commands/uuid.js Normal file
View file

@ -0,0 +1,18 @@
/* eslint-disable max-len */
module.exports = {
name: 'uuid',
alias: [],
description: 'Gets the UUID of a player. If no player specified it will show your UUID instead',
usage: '',
trusted: 0,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]!=undefined) {
const playername = args.join(' ');
const player = bot.playersAddedPlayers[playername];
if (player===undefined) throw new SyntaxError('Invalid UUID');
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: `${playername}'s uuid: `, color: 'green'}, {text: `${player}`, color: 'aqua', clickEvent: {action: 'copy_to_clipboard', value: `${player}`}, hoverEvent: {action: 'show_text', contents: [{text: 'Click here to copy the uuid to your clipboard', color: 'green'}]}}]));
} else {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: `Your uuid: `, color: 'green'}, {text: `${sender}`, color: 'aqua', clickEvent: {action: 'copy_to_clipboard', value: `${sender}`}, hoverEvent: {action: 'show_text', contents: [{text: 'Click here to copy the uuid to your clipboard', color: 'green'}]}}]));
}
},
};

17
commands/validate.js Normal file
View file

@ -0,0 +1,17 @@
/* eslint-disable max-len */
module.exports = {
name: 'validate',
description: 'Validates hash',
alias: [],
usage: '<hash>',
trusted: 1,
execute: function(bot, username, usernameraw, sender, prefix, args) {
if (args[0]===bot.hash) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: 'Valid hash', color: 'green'}));
} else if (args[0]===bot.ownerHash) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: 'Valid OwnerHash', color: 'green'}));
} else {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: 'Invalid hash', color: 'red'}));
}
},
};

36
commands/wikipedia.js Normal file
View file

@ -0,0 +1,36 @@
/* eslint-disable max-len */
const wiki = require('wikipedia');
const util = require('util');
const {MessageEmbed} = require('discord.js');
module.exports = {
name: 'wikipedia',
alias: ['wiki'],
usage: '<anything>',
trusted: 0,
execute: async function(bot, username, usernameraw, sender, prefix, args) {
try {
const page = await wiki.page(args.join(' '));
const summary = await page.summary();
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: summary.extract, color: 'green'}));
} catch (e) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: e.toString(), color: 'red'}));
}
},
discordExecute: async function(bot, username, usernameraw, sender, prefix, args, channeldc) {
try {
const page = await wiki.page(args.join(' '));
const summary = await page.summary();
const Embed = new MessageEmbed()
.setColor('#FFFF00')
.setTitle('Output')
.setDescription(summary.extract);
channeldc.send({embeds: [Embed]});
} catch (e) {
const Embed = new MessageEmbed()
.setColor('#FF0000')
.setTitle('Error')
.setDescription(`\`\`\`${util.inspect(e)}\`\`\``);
channeldc.send({embeds: [Embed]});
}
},
};

31
config.json Normal file
View file

@ -0,0 +1,31 @@
{
"prefixes": [
"*",
"cbot ",
"/cbot "
],
"core": {
"layers": 1
},
"discord": {
"token": "OTcxNjUwNDU2NzA5Mzk4NTY5.GfUrmw.45neSqFN4O9NmkwmqzjsC2avdY3FVvV_kQZ8AE",
"servers": {
"sus.shhnowisnottheti.me:25565": "990140129245020221",
"play.kaboom.pw:25565": "1000355361196355674",
"129.159.58.114:25565": "998945155316973650",
"192.168.1.103:25565": "1002806756885413978",
"kitsune.icu:25565": "1004006678460637315"
},
"prefix": "!"
},
"servers": [
{
"host": "sus.shhnowisnottheti.me",
"port": 25565
},
{
"host": "kitsune.icu",
"port": 25565
}
]
}

663
index.js Normal file
View file

@ -0,0 +1,663 @@
/* eslint-disable no-unused-vars */
/* eslint-disable no-var */
/* eslint-disable prefer-rest-params */
/* eslint-disable no-tabs */
/* eslint-disable max-len */
/* eslint-disable no-undef */
const mc = require('minecraft-protocol');
const crypto = require('crypto');
const colorConvert = require('color-convert');
const chatMessage = require('prismarine-chat')('1.18.2');
const {EventEmitter} = require('events');
const fs = require('fs');
const path = require('path');
const config = require('./config.json');
const uuid = require('uuid-by-string');
const readline = require('node:readline');
const {stdin: input, stdout: output} = require('node:process');
const rl = readline.createInterface({input, output});
const querystring = require('querystring');
const moment = require('moment-timezone');
const urban = require('urban-dictionary');
const cowsay = require('cowsay');
const {stylize} = require('./util/colors/minecraft');
const translate = require('@vitalets/google-translate-api');
const axios = require('axios');
const util = require('node:util');
const {between} = require('./util/between');
const {escapeMarkdown} = require('./util/escapeMarkdown');
const {VM} = require('vm2');
const randomstring = require('randomstring');
const mineflayer = require('mineflayer');
// readline > fix on console.log
const log = console.log;
console.log = function() {
rl.output.write('\x1b[2K\r');
log.apply(console, Array.prototype.slice.call(arguments));
rl._refreshLine();
};
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Load discord.js
const {
Client,
Intents,
MessageEmbed,
} = require('discord.js');
// Create Discord intentions, required in v13
const intents = new Intents(['GUILDS', 'GUILD_MESSAGES']);
// Create Discord client
const dcclient = new Client({
intents,
});
const ayunboomchannel = config.discord.servers['sus.shhnowisnottheti.me:25565'];
const dinboomchannel = config.discord.servers['129.159.58.114:25565'];
const kaboomchannel = config.discord.servers['play.kaboom.pw:25565'];
const localclonechannel = config.discord.servers['192.168.1.103:25565'];
const kitsunechannel = config.discord.servers['kitsune.icu:25565'];
let chomenschannel = '969773424387981356';
const hashchannel = '980438368422871151';
const ownerhashchannel = '980786390247833620';
/**
* Error
* @param {*} err
*/
// async function onerror(err) {
// try {
// console.log(`INFO: Disconnected: ${err}`);
// fs.appendFileSync('./logs.txt', `INFO: Disconnected: ${err}\r\n`);
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle(`${err.message ?? 'Disconnected'}`)
// .setDescription(`\`\`\`text\n${err}\`\`\``);
// channel.send({embeds: [Embed]});
// if (err.includes('issued "end" command')) {
// bot.chat('Restarting...');
// }
// await sleep(1000);
// bot.end();
// bot._client = mc.createClient(bot.options);
// } catch (e) {
// return;
// }
// }
/**
* empty function for discord message
* @return {String}
*/
function dcmsg() {
return 'this does nothing...';
}
function botThings() {
bot = new EventEmitter();
bot.options = {
username: `${randomstring.generate(16)}`,
host: process.argv[2],
// host: '129.159.58.114',
// host: 'mathialogsscode.tk',
// host: 'sus.shhnowisnottheti.me',
// host: 'play.kaboom.pw',
// host: '35.157.111.131',
port: process.argv[3] ? Number(process.argv[3]) : 25565,
version: '1.18.2',
physicsEnabled: false,
checkTimeoutInterval: '30000',
keepAlive: false,
hideErrors: true,
};
bot._client = mc.createClient(bot.options);
bot.queue = [];
bot.write = (name, data) => bot._client.write(name, data);
bot.end = (reason = 'end') => {
bot.emit('end', reason);
bot.removeAllListeners();
bot._client.end();
bot._client.removeAllListeners();
};
bot.visibility = false;
bot.command_handler = function() {
return;
};
bot.command_handler.commands = {};
bot.getplayerusername = {};
// allink's plugin loader
const plugins = []; // NOTE: DO NOT CHANGE, PLUGINS ARE LOADED AUTOMATICALLY
fs.readdirSync(
path.join(__dirname, 'plugins'),
).forEach(function(file) { // populate plugins array
if (file.endsWith('.js')) {
plugins.push(path.join(__dirname, 'plugins', file));
}
});
plugins.forEach(function(plugin) { // load plugins
let name = plugin.split('/');
name = name[name.length - 1];
try {
const plug = require(plugin);
plug.inject(bot, dcclient);
} catch (e) {
console.log(`Plugin loader: Plugin ${name} is having exception loading the plugin:`);
console.log(util.inspect(e));
}
});
}
/**
* Main bot function
*/
function main() {
// allink's chat queue
chatQueue = setInterval(function() {
try {
if (bot.queue[0]) {
try {
bot.write('chat', {message: bot.queue[0]});
bot.queue.shift();
} catch (e) {
return;
}
}
} catch (e) {
return;
}
}, 500);
module.exports = function() {
return bot;
};
dcmsg.queue = '';
bot.playersAddedPlayers = {};
bot.getplayerusername = {};
bot.hash = '';
bot.setHash = function(hash) {
bot.hash = hash;
};
bot.setOwnerHash = function(hash) {
bot.ownerhash = hash;
};
sleep = (time) => new Promise((a)=>setTimeout(a, time)),
bot.chat = (message) => {
bot.queue.push(String(message));
};
// fixCmdBlocksOnlyCore=(core)=>{
// const cmd = `/minecraft:fill ${Math.floor(bot.position.x)} 0 ${Math.floor(bot.position.z)} ${Math.floor(bot.position.x + 15)} 63 ${Math.floor(bot.position.z + 15)} command_block{CustomName: '{"text":"ChomeNS Bot Core","color":"yellow"}'} replace`;
// if (core===true) {
// bot.core.run(cmd);
// } else {
// bot.chat(cmd);
// }
// };
// fixCmdBlocks=()=>{
// bot.chat('/essentials:world world');
// fixCmdBlocksOnlyCore();
// };
discordQueue = setInterval(function() {
if (dcmsg.queue!='') {
channel.send(dcmsg.queue.substring(0, 2000));
dcmsg.queue = '';
}
}, 1000);
console.log(`Connecting to: ${bot.options.host}:${bot.options.port}...`);
// fs.appendFileSync('./logs.txt', `\r\Connecting to: ${bot.options.host}:${bot.options.port}...\r\n`);
channel.send(`Connecting to: \`${bot.options.host}:${bot.options.port}\`...`);
bot._client.on('login', async function(data) {
console.log(`Successfully logged in to: ${bot.options.host}:${bot.options.port}`);
// fs.appendFileSync('./logs.txt', `\r\nSuccessfully logged in to: ${bot.options.host}:${bot.options.port}\r\n`);
channel.send(`Successfully logged in to: \`${bot.options.host}:${bot.options.port}\``);
bot.uuid = bot._client.uuid;
bot.username = bot._client.username;
bot.entityId = data.entityId;
previusMessage = undefined;
loginfinish = false;
started = false;
bot.eaglercrashstarted = false;
await sleep(1500);
bot.createCore();
bot.vmoptions = {
timeout: 2000,
sandbox: {
run: bot.core.run,
mc: mc,
mineflayer: mineflayer,
chat: bot.chat,
moment: moment,
randomstring: randomstring,
uuid: uuid,
chatMessage: chatMessage,
crypto: crypto,
colorConvert: colorConvert,
bruhifyText: function(message) {
if (typeof message!=='string') throw new SyntaxError('message must be a string');
bot.bruhifyText = message.substring(0, 1000);
},
},
// require: {
// mock: {
// run: run,
// randomchar: randomchar,
// chat: bot.chat,
// mineflayer: mineflayer
// }
// }
};
bot.vm = new VM(bot.vmoptions);
loginfinish = true;
await sleep(1400);
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'ChomeNS Bot', color: 'yellow'}, {text: ' - a bot made by ', color: 'gray'}, {text: 'chayapak', color: 'gold'}]));
corefill = setInterval(async function() {
try {
bot.core.fillCore(true);
} catch (e) {
return;
}
}, 2000);
// NotOnline mode enabled
notonline = setInterval(async function() {
fs.readFile('./notonline.txt', 'utf8', (_err, data) => {
if (data === 'true') {
bot.core.run('execute run deop chayapak');
}
});
}, 250);
});
bot.on('parsed_chat', async function(message, data) {
try {
// prevents command set message and hi % exploit (it uses prismarine-chat)
const parsedMessage = JSON.parse(data.message);
if (parsedMessage.translate==='translation.test.invalid') return;
if (parsedMessage.translate==='advMode.setCommand.success') return;
const cleanMessage = escapeMarkdown(message.toString());
discordMsg = /* '_ _ ' + */cleanMessage.replaceAll('@', '@\u200B').replaceAll('http', '[http]');// .replace(/[\r\n]/gm, '\n')
if (previusMessage===message.toString()) return;
previusMessage = message.toString();
console.log(bot.options.host + ': ' + message.toAnsi()/* + '\u001b[0m'*/);
// fs.appendFileSync('./logs.txt', `${bot.options.host}: ${message.toMotd()}\r\n`);
// if (discordMsg)return channel.send(`${discordMsg.substring(0, 2000)}`)
if (message.toMotd().startsWith('§8[§r§eChomeNS §r§9Discord§r§8] §r§c')) return;
if (message.toString()==='') return;
if (message.toString().startsWith(' ')) return;
dcmsg.queue += '\n' + discordMsg.substring(0, 2000);
} catch (e) {
return;
}
});
// bot.on('message', async function(username, message, sender) {
// try {
// const usernameraw = username;
// // let username = usernameraw.replace(/§[a-f0-9rlonmk]/g, "").replace(/§/g, "");
// const messageraw = message;
// var username = getplayerusername[sender];
// var message = messageraw.replace(/§[a-f0-9rlonmk]/g, '').replace(/§/g, '');
// // if (username===bot.username)return
// // console.log(username + ': ' + message);
// allCommands(username, message, usernameraw, sender);
// } catch (e) {
// console.log(e);
// }
// });
// bot.on('cspy', async function(username, message) {
// // eslint-disable-next-line no-redeclare
// var username = username.replace(/§[a-f0-9rlonmk]/g, '').replace(/§/g, '');
// // eslint-disable-next-line no-redeclare
// var message = message.replace(/§[a-f0-9rlonmk]/g, '').replace(/§/g, '');
// const args = message.substring(5).trim().split(' ');
// args[0] = args[0].toLowerCase();
// try {
// allCommands(username, message, username, '00000000-0000-0000-0000-000000000000');
// } catch (e) {
// bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: String(e), color: 'red'}));
// }
// });
bot.on('player_added', (player) => {
bot.playersAddedPlayers[player.name] = player.UUID;
bot.getplayerusername[player.UUID] = player.name;
});
bot.on('player_removed', (player) => {
delete players[player.name];
});
bot._client.on('end', function(reason) {
bot.emit('end', reason, 'end');
// onerror('end event: ' + util.inspect(reason).replaceAll('runner', 'chayapak1'));
});
bot._client.on('tab_complete', (packet) => {
bot.tabcompleteplayers = packet.matches;
});
bot._client.on('kick_disconnect', function(data) {
const parsed = JSON.parse(data.reason);
bot.emit('end', parsed, 'kick_disconnect');
// onerror('kick_disconnect event: ' + util.inspect(reason));
});
bot._client.on('disconnect', function(data) {
const parsed = JSON.parse(data.reason);
bot.emit('end', parsed, 'disconnect');
});
bot._client.on('error', function(error) {
console.log('Error: ' + util.inspect(error));
channel.send('Error: ' + util.inspect(error));
// onerror('error event: ' + util.inspect(err).replaceAll('runner', 'chayapak1'));
});
process.on('uncaughtException', (error) => {
console.log('uncaught ' + util.inspect(error));
channel.send('uncaught ' + util.inspect(error));
bot.emit('end', 'uncaughtException');
});
process.on('SIGINT', async function() {
bot.chat('Interrupted by console');
process.exit();
});
bot.once('end', (reason, event) => {
console.log(`Disconnected (${event} event): ${util.inspect(reason)}`);
channel.send(`Disconnected (${event} event): ${util.inspect(reason)}`);
let timeout = 1000;
if (reason.text) {
if (reason.text.find((data) => data.text === 'Wait 5 seconds before connecting, thanks! :)')) timeout = 1000 * 6;
if (reason.text.find((data) => data.text === 'You are logging in too fast, try again later.')) timeout = 1000 * 6;
}
try {
clearInterval(corefill);
clearInterval(notonline);
clearInterval(discordQueue);
clearInterval(chatQueue);
} catch (e) {
return;
}
setTimeout(() => {
bot.end();
botThings();
main();
}, timeout);
});
}
dcclient.on('ready', async () => {
botThings();
// Find the Discord channel messages will be sent to
if (process.argv[2]==='sus.shhnowisnottheti.me') {
channel = dcclient.channels.cache.get(ayunboomchannel);
bot.channel = dcclient.channels.cache.get(ayunboomchannel);
}
if (process.argv[2]==='129.159.58.114') {
channel = dcclient.channels.cache.get(dinboomchannel);
bot.channel = dcclient.channels.cache.get(dinboomchannel);
}
if (process.argv[2]==='play.kaboom.pw') {
channel = dcclient.channels.cache.get(kaboomchannel);
bot.channel = dcclient.channels.cache.get(kaboomchannel);
}
if (process.argv[2]==='192.168.1.103') {
channel = dcclient.channels.cache.get(localclonechannel);
bot.channel = dcclient.channels.cache.get(localclonechannel);
}
if (process.argv[2]==='kitsune.icu') {
channel = dcclient.channels.cache.get(kitsunechannel);
bot.channel = dcclient.channels.cache.get(kitsunechannel);
}
await sleep(200);
main();
chomenschannel = dcclient.channels.cache.get(chomenschannel);
bot.hashchannel = dcclient.channels.cache.get(hashchannel);
bot.ownerhashchannel = dcclient.channels.cache.get(ownerhashchannel);
bot.channelId = channel.id;
attachmentlink = '';
// Console COMMANDS
rl.on('line', function(line) {
try {
const {MessageBuilder} = require('prismarine-chat')('1.18.2');
if (line.toLowerCase()==='' || line.toLowerCase().startsWith(' ')) return;
if (line.toLowerCase()==='.exit' || line.toLowerCase()==='.end') {
bot.emit('end', 'end command');
// onerror('Console issued "end" command, rebooting bot...');
return;
}
if (line.toLowerCase().startsWith('.servereval ')) {
try {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${util.inspect(eval(`${line.substring(12)}`))}`, color: 'green'}));
return;
} catch (err) {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify({text: `${util.inspect(err)}`, color: 'red'}));
return;
}
}
if (line==='.notonline on') {
fs.writeFileSync('./notonline.txt', 'true');
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'NotOnline mode enabled', color: 'white'}]));
return;
}
if (line==='.notonline off') {
fs.writeFileSync('./notonline.txt', 'false');
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {text: 'NotOnline mode disabled', color: 'white'}]));
return;
}
if (line.toLowerCase()==='.resethash') {
bot.hash = randomstring.generate(16);
console.log('new hash: ' + bot.hash);
return;
}
// if (line.startsWith("."))return console.log('command not found')
if (line.startsWith('.')) return bot.command_handler.run('Console', '§e§lConsole§r', '*' + line.substring(1), 'c0ns0le_uuid');
bot.core.run('minecraft:tellraw @a ' + JSON.stringify(['', {'text': '[', 'color': 'dark_gray'}, {'text': `${bot.username} Console`, 'color': 'gray'}, {'text': '] ', 'color': 'dark_gray'}, {'text': 'chayapak ', 'color': 'green'}, {'text': ' ', 'color': 'dark_gray'}, MessageBuilder.fromString('&7' + line)]));
} catch (e) {
console.log(e);
}
});
});
// Redirect Discord messages to in-game chat
dcclient.on('messageCreate', async (message) => {
// Ignore messages from the bot itself
if (message.author.id === dcclient.user.id) return;
const {MessageBuilder} = require('prismarine-chat')('1.18.2');
const channelid = message.channel.id;
const channeldc = dcclient.channels.cache.get(channelid);
// if (message.content.toLowerCase().startsWith('!chomensmsg ')) {
// bot.core.run(`minecraft:tellraw @a ["",{"text":"[","color":"dark_gray"},{"text":"ChomeNS ","color":"yellow","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":"Discord","color":"blue","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":" (ChomeNS Channel)","color":"gray"},{"text":"] ","color":"dark_gray"},{"text":"${message.member.displayName}","color":"red","clickEvent":{"action":"copy_to_clipboard","value":"${message.author.username}#${message.author.discriminator}"},"hoverEvent":{"action":"show_text","value":{"text":"${message.author.username}§7#${message.author.discriminator}"} }},{"text":" ","color":"white"},` + MessageBuilder.fromString('&7' + message.content.substring(12)) + ']');
// return;
// }
// Only handle messages in specified channel
if (message.channel.id != channel.id) return;
if (message.content.startsWith(config.discord.prefix)) return;
// try {
// if (message.content.toLowerCase()==='!test') {
// const Embed = new MessageEmbed()
// .setColor('#FFFF00')
// .setTitle('Hello!')
// .setDescription('This is the first command to be discordified!');
// channeldc.send({embeds: [Embed]});
// return;
// }
// if (message.content.toLowerCase()==='!help') {
// const Embed = new MessageEmbed()
// .setColor('#FFFF00')
// .setTitle('Commands')
// .setDescription('help echo cb eval stopserver end ayunsudo playerlist');
// channeldc.send({embeds: [Embed]});
// return;
// }
// if (message.content.toLowerCase().startsWith('!echo ')) {
// channeldc.send(`${message.author.username}, sending "${message.content.toLowerCase().substring(6)}"`);
// bot.chat(message.content.substring(6));
// return;
// }
// if (message.content.toLowerCase().startsWith('!cb ')) {
// channeldc.send(`${message.author.username}, executing "${message.content.toLowerCase().substring(4)}"`);
// bot.core.run(message.content.substring(4));
// return;
// }
// if (message.content.toLowerCase().startsWith('!eval run ')) {
// try {
// const Embed = new MessageEmbed()
// .setColor('#FFFF00')
// .setTitle('Output')
// .setDescription(`\`\`\`js\n${escapeMarkdown(util.inspect(vm.run(message.content.substring(10))))}\`\`\``.substring(0, 1900));
// channeldc.send({embeds: [Embed]});
// } catch (err) {
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle('Error')
// .setDescription(`\`\`\`text\n${escapeMarkdown(util.inspect(err).replaceAll('runner', 'chayapak1'))}\`\`\``.substring(0, 1900));
// channeldc.send({embeds: [Embed]});
// }
// return;
// }
// if (message.content.toLowerCase()==='!eval reset') {
// vm = new VM(vmoptions);
// return;
// }
// if (message.content.toLowerCase().startsWith('!eval server ')) {
// axios
// .post('http://192.168.1.105:4445/', querystring.stringify({
// html: false,
// showErrorMsg: true,
// code: message.content.substring(13),
// })).then((res) => {
// const Embed = new MessageEmbed()
// .setColor('#FFFF00')
// .setTitle('Output')
// .setDescription(`\`\`\`js\n${res.data}\`\`\``.substring(0, 1900));
// channeldc.send({embeds: [Embed]});
// }).catch((e) => {
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle('Error')
// .setDescription(`\`\`\`text\n${e}\`\`\``.substring(0, 1900));
// channeldc.send({embeds: [Embed]});
// });
// return;
// }
// if (message.content.toLowerCase().startsWith('!eval dineval ')) {
// axios
// .get('https://eval.dinhero21.repl.co', {
// headers: {
// data: message.content.substring(14),
// },
// }).then((res) => {
// const Embed = new MessageEmbed()
// .setColor('#FFFF00')
// .setTitle('Output')
// .setDescription(`\`\`\`js\n${res.data}\`\`\``.substring(0, 1900));
// channeldc.send({embeds: [Embed]});
// }).catch((e) => {
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle('Error')
// .setDescription(`\`\`\`text\n${e}\`\`\``.substring(0, 1900));
// channeldc.send({embeds: [Embed]});
// });
// return;
// }
// if (message.content.toLowerCase()==='!stopserver') {
// if (message.member._roles.at(0)==='981159334299983953' || message.member._roles.at(0)==='974590495563075594') {
// bot.core.run('minecraft:execute unless entity @s[name= run ] run stop');
// } else {
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle('Error')
// .setDescription('You\'re not in the trusted role!');
// channeldc.send({embeds: [Embed]});
// }
// return;
// }
// if (message.content.toLowerCase()==='!end') {
// if (message.member._roles.at(0)==='981159334299983953' || message.member._roles.at(0)==='974590495563075594') {
// bot.emit('end', 'end command');
// // onerror(`${message.member.displayName} issued "end" command, rebooting bot...`);
// } else {
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle('Error')
// .setDescription('You\'re not in the trusted role!');
// channeldc.send({embeds: [Embed]});
// }
// return;
// }
// if (message.content.toLowerCase().startsWith('!ayunsudo ')) {
// if (message.member._roles.at(0)==='981159334299983953' || message.member._roles.at(0)==='974590495563075594') {
// for (const property of bot.players.list) {
// bot.core.run('sudo ' + property.UUID + ' ' + message.content.toLowerCase().substring(10));
// }
// } else {
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle('Error')
// .setDescription('You\'re not in the trusted role!');
// channeldc.send({embeds: [Embed]});
// }
// return;
// }
// if (message.content.toLowerCase()==='!playerlist' || message.content.toLowerCase()==='!list') {
// var allplayers = '';
// for (const property of bot.tabcompleteplayers) {
// if (property.match.startsWith('@')) continue;
// // eslint-disable-next-line no-redeclare
// var allplayers = allplayers + '\n`' + property.match + '` > `' + bot.players.getPlayer(property.match).UUID + '`';
// }
// const Embed = new MessageEmbed()
// .setColor('#FFFF00')
// .setTitle('Players')
// .setDescription(allplayers);
// channeldc.send({embeds: [Embed]});
// return;
// }
//
// if (message.content.toLowerCase().startsWith('!')) {
// const args = message.content.toLowerCase().substring(1).trim().split(' ');
// const Embed = new MessageEmbed()
// .setColor('#FF0000')
// .setTitle('Error')
// .setDescription(`Unknown command or incomplete command: "${args.at(0)}"`);
// channeldc.send({embeds: [Embed]});
// return;
// }
// } catch (e) {
// console.log(e);
// }
const attachment = message.attachments.at(0);
if (attachment!=undefined) {
if (message.content.toLowerCase()==='') {
bot.core.run(`minecraft:tellraw @a ["",{"text":"[","color":"dark_gray"},{"text":"ChomeNS ","color":"yellow","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":"Discord","color":"blue","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":"] ","color":"dark_gray"},{"text":"${message.member.displayName}","color":"red","clickEvent":{"action":"copy_to_clipboard","value":"${message.author.username}#${message.author.discriminator}"},"hoverEvent":{"action":"show_text","value":{"text":"${message.author.username}§7#${message.author.discriminator}"} }},{"text":" ","color":"dark_gray"},` + `{"text":"[Attachment]","clickEvent":{"action":"open_url","value":"${attachment.proxyURL}"},"color":"green"}` + ']');
} else {
bot.core.run(`minecraft:tellraw @a ["",{"text":"[","color":"dark_gray"},{"text":"ChomeNS ","color":"yellow","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":"Discord","color":"blue","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":"] ","color":"dark_gray"},{"text":"${message.member.displayName}","color":"red","clickEvent":{"action":"copy_to_clipboard","value":"${message.author.username}#${message.author.discriminator}"},"hoverEvent":{"action":"show_text","value":{"text":"${message.author.username}§7#${message.author.discriminator}"} }},{"text":" ","color":"dark_gray"},` + MessageBuilder.fromString('&7' + message.content) + `,{"text":" [Attachment]","clickEvent":{"action":"open_url","value":"${attachment.proxyURL}"},"color":"green"}` + ']');
}
} else {
bot.core.run(`minecraft:tellraw @a ["",{"text":"[","color":"dark_gray"},{"text":"ChomeNS ","color":"yellow","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":"Discord","color":"blue","clickEvent":{"action":"open_url","value":"https://discord.gg/xdgCkUyaA4"},"hoverEvent":{"action":"show_text","contents":[{"text":"https://discord.gg/xdgCkUyaA4 ","color":"blue"},{"text":"<-- join now","color":"red"}]}},{"text":"] ","color":"dark_gray"},{"text":"${message.member.displayName}","color":"red","clickEvent":{"action":"copy_to_clipboard","value":"${message.author.username}#${message.author.discriminator}"},"hoverEvent":{"action":"show_text","value":{"text":"${message.author.username}§7#${message.author.discriminator}"} }},{"text":" ","color":"dark_gray"},` + MessageBuilder.fromString('&7' + message.content) + ']');
}
});
dcclient.login(config.discord.token);

42
package.json Normal file
View file

@ -0,0 +1,42 @@
{
"name": "bot",
"version": "1.0.0",
"description": "",
"main": "run.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ."
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@tonejs/midi": "^2.0.28",
"@vitalets/google-translate-api": "^8.0.0",
"axios": "^0.27.2",
"color-convert": "^2.0.1",
"cowsay": "^1.5.0",
"discord-webhook-node": "^1.1.8",
"discord.js": "^13.7.0",
"mineflayer": "^4.3.0",
"moment": "^2.29.3",
"moment-timezone": "^0.5.34",
"node-persist": "^3.1.0",
"node-ssh": "^12.0.4",
"prismarine-viewer": "^1.23.0",
"rainbowvis.js": "^1.0.1",
"randomstring": "^1.2.2",
"readline": "^1.3.0",
"safe-eval": "^0.4.1",
"sleep-promise": "^9.1.0",
"translate-api": "^0.3.18",
"urban-dictionary": "^3.0.2",
"uuid-by-string": "^3.0.7",
"vm2": "^3.9.9",
"wikipedia": "^1.1.9"
},
"devDependencies": {
"eslint": "^8.20.0",
"eslint-config-google": "^0.14.0"
}
}

22
plugins/bruhify.js Normal file
View file

@ -0,0 +1,22 @@
const convert = require('color-convert');
module.exports = {
inject: function(bot) {
bot.bruhifyText = '';
let startHue = 0;
timer = setInterval(() => {
if (bot.bruhifyText==='') return;
let hue = startHue;
const displayName = bot.bruhifyText;
const increment = (360 / Math.max(displayName.length, 20));
const component = [];
for (const character of displayName) {
const color = convert.hsv.hex(hue, 100, 100);
component.push({text: character, color: `#${color}`});
hue = (hue + increment) % 360;
}
bot.core.run(`minecraft:title @a actionbar ${JSON.stringify(component)}`);
startHue = (startHue + increment) % 360;
}, 100);
},
};

61
plugins/chat.js Normal file
View file

@ -0,0 +1,61 @@
/* eslint-disable max-len */
/* eslint-disable require-jsdoc */
// eslint-disable-next-line no-undef
// const parse = require('../util/text_parser');
const ChatMessage = require('prismarine-chat')('1.18.2');
function inject(bot) {
bot._client.on('chat', (packet) => {
try {
// const message = parse(packet.message);
const message = ChatMessage.fromNotch(packet.message);
bot.emit('parsed_chat', message, packet);
} catch (e) {
return;
}
});
bot.on('parsed_chat', (message, packet) => {
try {
const raw = message.toMotd().substring(0, 32767);
if (raw.match(/<.*§r> .*/g)) {
if (packet.sender === '00000000-0000-0000-0000-000000000000') return;
const username = raw.substr(3).split('§r>')[0];
const message = raw.split('§r> §r')[1];
bot.emit('message', username, message, packet.sender);
} else if (raw.match(/<.*> .*/g)) {
if (packet.sender === '00000000-0000-0000-0000-000000000000') return;
const username = raw.substr(3).split('>')[0];
const message = raw.split('> ')[1];
bot.emit('message', username, message, packet.sender);
} else if (raw.match(/.* .*§r: §.*/g)) {
// if (packet.sender === '00000000-0000-0000-0000-000000000000') return;
const username = raw.replace(/.*?\[.*?\] /, '').replace(/:.*/g, '').replace(/§#....../gm, '');
const message = raw.split('§r: ')[1].substr(2);
bot.emit('message', username, message, packet.sender);
} else if (raw.match(/.* .*: .*/g)) {
// if (packet.sender === '00000000-0000-0000-0000-000000000000') return;
const username = raw.replace(/.*?\[.*?\] /, '').replace(/:.*/g, '').replace(/§#....../gm, '');
const message = raw.split(': ')[1];
bot.emit('message', username, message, packet.sender);
} else if (raw.match(/§.*§b: \/.*/g)) {
const username = raw.split('§b: ')[0];
const command = raw.split('§b: ')[1];
bot.emit('cspy', username, command);
} else if (raw.match(/§.*§e: \/.*/g)) {
const username = raw.split('§e: ')[0];
const command = raw.split('§e: ')[1];
bot.emit('cspy', username, command);
}
} catch (e) {
return;
}
});
}
module.exports = {inject};

77
plugins/commands.js Normal file
View file

@ -0,0 +1,77 @@
/* eslint-disable no-var */
/* eslint-disable max-len */
const config = require('../config.json');
const loadFiles = require('../util/load_files');
const path = require('path');
const {MessageEmbed} = require('discord.js');
function inject(bot, dcclient) {
bot.command_handler.commands = loadFiles(path.join(__dirname, '../commands'));
bot.command_handler.main = function(prefix, username, usernameraw, message, sender, channeldc) {
const raw = message.substr(prefix.length);
const [commandName, ...args] = raw.split(' ');
var command = bot.command_handler.commands.find((command) => command.name === commandName.toLowerCase());
try {
var alias = bot.command_handler.commands.find((command) => command.alias.includes(commandName.toLowerCase()));
if (alias !== undefined) {
var command = bot.command_handler.commands.find((command) => command.alias.includes(commandName.toLowerCase()));
}
if (command === undefined) {
throw new Error(`Unknown command: "${commandName}"`);
}
if (prefix==='!') {
if (typeof command.discordExecute==='undefined') throw new Error('This command is not yet supported on discord!');
command.discordExecute(bot, username, usernameraw, sender, prefix, args, channeldc);
} else {
command.execute(bot, username, usernameraw, sender, prefix, args);
}
} catch (e) {
if (prefix==='!') {
const Embed = new MessageEmbed()
.setColor('#FF0000')
.setTitle('Error')
.setDescription(`\`\`\`${e}\`\`\``);
channeldc.send({embeds: [Embed]});
} else {
bot.core.run('minecraft:tellraw chayapak ' + JSON.stringify({text: String(e), color: 'red'}));
}
}
};
bot.command_handler.run = function(username, usernameraw, message, sender, channeldc) {
for (const prefix of config.prefixes) {
if (!message.startsWith(prefix)) continue;
bot.command_handler.main(prefix, username, usernameraw, message, sender, channeldc);
}
};
bot.on('message', async (username, message, sender) => {
// try catch cuz TypeError: Cannot read properties of undefined (reading 'replace')
try {
const usernameraw = username.replace(/§[a-f0-9rlonmk]/g, '').replace(/§/g, '');
var username = bot.getplayerusername[bot.playersAddedPlayers[usernameraw]/* sender */];
var message = message.replace(/§[a-f0-9rlonmk]/g, '').replace(/§/g, '');
bot.command_handler.run(username, usernameraw, message, sender);
} catch (e) {
return;
}
});
bot.on('cspy', async function(username, message) {
var username = username.replace(/§[a-f0-9rlonmk]/g, '').replace(/§/g, '');
var message = message.replace(/§[a-f0-9rlonmk]/g, '').replace(/§/g, '');
bot.command_handler.run(username, username, message, 'no uuid1!1!1!');
});
dcclient.on('messageCreate', async (message) => {
try {
// ignores the message that comes from the bot itself
if (message.author.id === dcclient.user.id) return;
const channelid = message.channel.id;
const channeldc = dcclient.channels.cache.get(channelid);
// only receive messages in SPECIFIC channel
if (message.channel.id != bot.channelId) return;
if (!message.content.startsWith(config.discord.prefix)) return;
bot.command_handler.main(config.discord.prefix, message.member.displayName, message.member.displayName, message.content, 'no sender for discord', channeldc);
} catch (e) {
return;
};
});
};
module.exports = {inject};

81
plugins/core.js Normal file
View file

@ -0,0 +1,81 @@
/* eslint-disable max-len */
/* eslint-disable require-jsdoc */
const config = require('../config.json');
const Vec3 = require('vec3');
const relativePosition = new Vec3(0, 0, 0);
function inject(bot) {
bot.createCore = (layers = config.core.layers) => {
const core = {
isCore(position) {
return position.x >= core.start.x && position.x <= core.end.x && position.y >= core.start.y && position.y <= core.end.y && position.z >= core.start.z && position.z <= core.end.z;
},
run(command) {
relativePosition.x++;
if (relativePosition.x >= 16) {
relativePosition.x = 0;
relativePosition.y++;
}
if (relativePosition.y >= layers) {
relativePosition.y = 0;
relativePosition.z++;
}
if (relativePosition.z >= 16) {
relativePosition.z = 0;
}
bot.write('update_command_block', {
location: {
x: core.start.x + relativePosition.x,
y: core.start.y + relativePosition.y,
z: core.start.z + relativePosition.z,
},
command: command.substring(0, 32767),
mode: 1,
flags: 0b100,
});
},
fillCore(useCore) {
const fillCommand = `/minecraft:fill ${core.start.x} ${core.start.y} ${core.start.z} ${core.end.x} ${core.end.y} ${core.end.z} command_block{CustomName:'{"text":"ChomeNS Bot Core","color":"yellow"}'}`;
if (useCore==true) {
bot.core.run(fillCommand);
} else {
bot.chat(fillCommand);
}
bot.emit('core_filled');
},
};
bot._client.on('position', (position) => {
bot.position = position;
bot.emit('position', position);
});
bot.on('position', fillCore);
fillCore();
bot.core = core;
return core;
function fillCore() {
core.start = new Vec3(
Math.floor(bot.position.x / 16) * 16,
0 /* bot.position.y */,
Math.floor(bot.position.z / 16) * 16,
).floor();
core.end = core.start.clone().translate(16, layers, 16).subtract(new Vec3(1, 1, 1));
core.fillCore();
}
};
}
module.exports = {inject};

12
plugins/hash.js Normal file
View file

@ -0,0 +1,12 @@
/* eslint-disable max-len */
const crypto = require('crypto');
module.exports = {
inject: function(bot) {
setInterval(() => {
bot.hash = crypto.createHash('md5').update(Math.floor(Date.now() / 1000).toString() + 'chomens1!1!').digest('hex').toString().substring(0, 16);
}, 1000);
setInterval(() => {
bot.ownerHash = crypto.createHash('md5').update(Math.floor(Date.now() / 1000).toString() + 'ownermogus').digest('hex').toString().substring(0, 16);
}, 1000);
},
};

113
plugins/music.js Normal file
View file

@ -0,0 +1,113 @@
/* eslint-disable max-len */
const {Midi} = require('@tonejs/midi');
const {convertMidi} = require('../util/midi_converter');
const soundNames = {
harp: 'minecraft:block.note_block.harp',
basedrum: 'minecraft:block.note_block.basedrum',
snare: 'minecraft:block.note_block.snare',
hat: 'minecraft:block.note_block.hat',
bass: 'minecraft:block.note_block.bass',
flute: 'minecraft:block.note_block.flute',
bell: 'minecraft:block.note_block.bell',
guitar: 'minecraft:block.note_block.guitar',
chime: 'minecraft:block.note_block.chime',
xylophone: 'minecraft:block.note_block.xylophone',
iron_xylophone: 'minecraft:block.note_block.iron_xylophone',
cow_bell: 'minecraft:block.note_block.cow_bell',
didgeridoo: 'minecraft:block.note_block.didgeridoo',
bit: 'minecraft:block.note_block.bit',
banjo: 'minecraft:block.note_block.banjo',
pling: 'minecraft:block.note_block.pling',
};
function inject(bot) {
bot.music = function() {};
bot.music.song = null;
bot.music.loop = false;
time = 0;
startTime = 0;
noteIndex = 0;
setInterval(() => {
try {
if (!bot.music.song) return;
time = Date.now() - startTime;
while (bot.music.song.notes[noteIndex]?.time <= time) {
const note = bot.music.song.notes[noteIndex];
const floatingPitch = 2 ** ((note.pitch - 12) / 12.0);
bot.core.run(`minecraft:execute as @a[tag=!nomusic] at @s run playsound ${soundNames[note.instrument]} record @s ~ ~ ~ ${note.volume} ${floatingPitch}`);
noteIndex++;
bot.core.run('minecraft:title @a[tag=!nomusic] actionbar ' + JSON.stringify(toComponent()));
if (noteIndex >= bot.music.song.notes.length) {
if (bot.music.loop) {
resetTime();
return;
}
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Finished playing '}, {text: bot.music.song.name, color: 'gold'}]));
bot.music.stop();
}
}
} catch (e) {
return;
}
}, 20);
bot.music.load = function(buffer, fallbackName = '[unknown]') {
// TODO: NBS Support
const midi = new Midi(buffer);
const song = convertMidi(midi);
if (song.name === '') song.name = fallbackName;
return song;
};
bot.music.play = function(song) {
bot.music.song = song;
loop = song.loop;
resetTime();
};
bot.music.stop = function() {
bot.core.run('minecraft:tellraw @a ' + JSON.stringify([{text: 'Stopped playing '}, {text: bot.music.song.name, color: 'gold'}]));
bot.music.song = null;
bot.music.loop = false;
resetTime();
};
function resetTime() {
time = 0;
startTime = Date.now();
noteIndex = 0;
}
function formatTime(time) {
const seconds = Math.floor(time / 1000);
return `${Math.floor(seconds / 60)}:${(seconds % 60).toString().padStart(2, '0')}`;
}
function toComponent() {
const component = [
'§8[§eChomeNS Bot§8] ',
{text: 'Now Playing', color: 'gold'},
' §8| ',
{text: bot.music.song.name, color: 'green'},
' §8| ',
{text: formatTime(time), color: 'gray'},
' §8/ ',
{text: formatTime(bot.music.song.length), color: 'gray'},
' §8| ',
{text: noteIndex, color: 'gray'},
'§8 / ',
{text: bot.music.song.notes.length, color: 'gray'},
];
if (bot.music.loop) {
component.push(' §8| ');
component.push('§aLooping');
}
return component;
}
}
module.exports = {inject};

163
plugins/players.js Normal file
View file

@ -0,0 +1,163 @@
/* eslint-disable max-len */
/* eslint-disable require-jsdoc */
class PlayerList {
list = [];
addPlayer(player) {
this.removePlayer(player);
this.list.push(player);
}
hasPlayer(player) {
return this.getPlayer(player) !== undefined;
}
getPlayer(player) {
let identifier;
switch (typeof player) {
case 'object':
identifier = player.UUID;
break;
case 'string':
identifier = player;
break;
default:
throw new Error(`Get player called with ${player}`);
}
return this.list.find((player) => [player.UUID, player.name].some((item) => item === identifier));
}
getPlayers() {
return Array.from(this.list);
}
removePlayer(player) {
this.list = this.list.filter(({UUID}) => UUID !== player.UUID);
}
}
class TabCompletePlayerRequester {
id = 0;
queue = {};
bot;
constructor(bot) {
this.bot = bot;
bot.on('target_packet', (name, data) => {
if (name !== 'tab_complete') return;
const players = data.matches
.filter((match) => !match.tooltip)
.map((match) => match.match);
this.returnPlayerList(data.transactionId, players);
});
}
getPlayerList() {
return new Promise((resolve) => {
this.id++;
this.id %= 256;
this.queue[this.id] = resolve;
setTimeout(() => this.returnPlayerList(this.id, this.getPlayerList()), 1000 * 5);
this.bot.write('tab_complete', {transactionId: this.id, text: '/scoreboard players add '});
});
}
returnPlayerList(id, players) {
if (!this.queue[id]) return;
this.queue[id](players);
delete this.queue[id];
}
}
function inject(bot) {
bot.players = new PlayerList();
bot.requester = new TabCompletePlayerRequester(bot);
bot._client.on('player_info', (packet) => {
for (const player of packet.data) {
switch (packet.action) {
case 0:
addPlayer(player, packet);
break;
case 1:
updateGamemode(player, packet);
break;
case 2:
updatePing(player, packet);
break;
case 3:
updateDisplayName(player, packet);
break;
case 4:
removePlayer(player, packet);
break;
}
}
});
function addPlayer(player, packet) {
if (bot.players.getPlayer(player)) bot.emit('player_unvanished', player, packet);
else bot.emit('player_added', player, packet);
bot.players.addPlayer(player);
}
function updateGamemode(player, packet) {
const fullPlayer = bot.players.getPlayer(player);
bot.emit('onPlayerGamemodeUpdate', player, packet);
if (fullPlayer === undefined) return;
fullPlayer.gamemode = player.gamemode;
}
function updatePing(player, packet) {
const fullPlayer = bot.players.getPlayer(player);
bot.emit('player_ping_updated', player, packet);
if (fullPlayer === undefined) return;
fullPlayer.ping = player.ping;
}
function updateDisplayName(player, packet) {
const fullPlayer = bot.players.getPlayer(player);
bot.emit('player_display_name_updated', player, packet);
if (fullPlayer === undefined) return;
fullPlayer.displayName = player.displayName;
}
async function removePlayer(player, packet) {
const fullPlayer = bot.players.getPlayer(player);
const players = await bot.requester.getPlayerList();
if (fullPlayer && players.some((name) => name === fullPlayer.name)) {
bot.emit('player_vanished', player);
return;
}
bot.emit('player_removed', player, packet);
bot.players.removePlayer(player);
}
}
module.exports = {inject};

13
plugins/position.js Normal file
View file

@ -0,0 +1,13 @@
/* eslint-disable require-jsdoc */
const Vec3 = require('vec3');
function inject(bot) {
bot.position = new Vec3(null, null, null);
bot._client.on('position', (position) => {
bot.position = new Vec3(position.x, position.y, position.z);
bot.write('teleport_confirm', {teleportId: position.teleportId});
});
}
module.exports = {inject};

75
plugins/self_care.js Normal file
View file

@ -0,0 +1,75 @@
/* eslint-disable max-len */
/* eslint-disable require-jsdoc */
function inject(bot) {
let vanish = false;
let cspy = false;
let op = true;
let gameMode = 1;
let prefix = false;
let muted = false;
bot.on('parsed_chat', (data) => {
if (data.toString()=='You are now completely invisible to normal users, and hidden from in-game commands.') vanish = true;
if (!bot.visibility) {
if (data.toString().startsWith('Vanish for ') && data.toString().endsWith('disabled')) vanish = false;
}
if (data.toString()=='Successfully enabled CommandSpy') cspy = true;
if (data.toString()=='Successfully disabled CommandSpy') cspy = false;
if (data.toString()=='You now have the tag: [ChomeNS Bot]') {
prefix = true;
return;
}
if (data.toString().startsWith('You no longer have a tag')) prefix = false;
if (data.toString().startsWith('You now have the tag: ')) prefix = false;
if (data.toString().startsWith('You have been muted')) muted = true;
if (data.toString()=='You have been unmuted.') muted = false;
});
bot._client.on('entity_status', (data) => {
if (data.entityId !== bot.entityId) return;
switch (data.entityStatus) {
case 24:
op = false;
bot.emit('deop');
break;
case 28:
op = true;
bot.emit('op');
break;
}
bot.emit('entity_status', data);
});
bot._client.on('game_state_change', (data) => {
if (data.reason !== 3) return;
gameMode = data.gameMode;
});
bot._client.once('login', (data) => {
gameMode = data.gameMode;
});
const interval = setInterval(() => {
if (!op) {
bot.chat('/minecraft:op @s[type=player]');
return;
}
if (!vanish) bot.chat('/essentials:vanish enable');
if (!cspy) bot.chat('/commandspy:commandspy on');
if (gameMode !== 1) bot.chat('/minecraft:gamemode creative @s[type=player]');
if (!prefix) bot.chat('/extras:prefix &8[&eChomeNS Bot&8]');
if (muted) bot.chat('/essentials:mute ' + bot.uuid);
}, 1000 * 5);
bot.once('end', () => {
clearInterval(interval);
});
}
module.exports = {inject};

73
run.js Normal file
View file

@ -0,0 +1,73 @@
/* eslint-disable max-len */
/* eslint-disable no-var */
const readline = require('node:readline');
const {stdin: input, stdout: output} = require('node:process');
const rl = readline.createInterface({input, output});
const process = require('child_process');
const config = require('./config.json');
require('./uptime');
const bots = {};
/**
* the start function
* @param {String} host
* @param {Number} port
*/
function start(host, port) {
const server = host;
let theServer;
bots[server] = process.exec('node index.js ' + host);
if (host=='sus.shhnowisnottheti.me') {
theServer = 'ayunboom';
}
if (host=='129.159.58.114') {
theServer = 'dinboom';
}
if (host=='play.kaboom.pw') {
theServer = 'kaboom';
}
if (host=='192.168.1.103') {
theServer = 'local';
}
if (host=='kitsune.icu') {
theServer = 'kitsune';
}
eval(`${theServer} = []`);
eval(`${theServer}loop = setInterval(() => {
if (${theServer}[0]) {
bots[server].stdin.write(${theServer}.at(0) + '\\n');
${theServer} = [];
}
}, 0)`);
bots[server].on('close', function() {
bots[server].kill();
eval(`clearInterval(${theServer}loop)`);
start(server);
});
bots[server].stdout.on('data', function(chunk) {
rl.output.write('\x1b[2K\r');
require('process').stdout.write(`${chunk}`);
rl._refreshLine();
});
rl.on('line', (line) => {
if (line.startsWith('/send ')) {
try {
const args = line.substring(1).trim().split(' ');
eval(`${args.at(1)}.push(args.slice(2).join(' ').toString())`);
} catch (e) {
console.log('Invalid.');
}
return;
}
bots[server].stdin.write(line + '\n');
require('process').on('SIGINT', () => {
bots[server].kill();
require('process').exit();
});
});
}
for (const server of config.servers) {
start(server.host, server.port);
}

1
uptime.js Normal file
View file

@ -0,0 +1 @@
// nothing interesting here....

13
util/between.js Normal file
View file

@ -0,0 +1,13 @@
module.exports = {
/**
* this code is from somewhere i can't remember...
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
between: function(min, max) {
return Math.floor(
Math.random() * (max - min) + min,
);
},
};

23
util/colors/minecraft.js Normal file
View file

@ -0,0 +1,23 @@
/* eslint-disable require-jsdoc */
const styles = {
bigint: '\xa76',
boolean: '\xa76',
date: '\xa75',
module: '\xa7n',
name: undefined,
null: '\xa7l',
number: '\xa76',
regexp: '\xa74',
special: '\xa73',
string: '\xa72',
symbol: '\xa72',
undefined: '\xa78',
};
function stylize(str, styleType) {
const style = styles[styleType];
if (style !== undefined) return `${style}${str}\xa7r`;
return str;
}
module.exports = {stylize, styles};

18
util/escapeMarkdown.js Normal file
View file

@ -0,0 +1,18 @@
/* eslint-disable no-var */
/* eslint-disable max-len */
/**
* escape markdown so on discord it will be \_ChipMC\_ instead of ChipMC in italic
* @param {String} text
* @return {String}
*/
function escapeMarkdown(text) {
try {
var unescaped = text.replace(/\\(\*|@|_|`|~|\\)/g, '$1');
var escaped = unescaped.replace(/(\*|@|_|`|~|\\)/g, '\\$1');
} catch (e) {
return unescaped;
}
return escaped;
}
module.exports = {escapeMarkdown};

14
util/file-exists.js Normal file
View file

@ -0,0 +1,14 @@
const fs = require('fs/promises')
async function fileExists (filepath) {
try {
await fs.access(filepath)
return true
} catch (error) {
if (error.code !== 'ENOENT') throw error
return false
}
}
module.exports = fileExists

14
util/file-list.js Normal file
View file

@ -0,0 +1,14 @@
const fs = require('fs/promises')
async function list (filepath = '.') {
const files = await fs.readdir(filepath)
const component = []
files.forEach((filename, index) => {
component.push(filename)
if (index !== files.length - 1) component.push(' ')
})
return component
}
module.exports = list

20
util/load_files.js Normal file
View file

@ -0,0 +1,20 @@
const fs = require('fs')
const path = require('path')
function loadPlugins (directory) {
const plugins = []
for (const filename of fs.readdirSync(directory)) {
if (!filename.endsWith('.js')) continue
const filepath = path.join(directory, filename)
const plugin = require(filepath)
plugins.push(plugin)
}
return plugins
}
module.exports = loadPlugins

View file

@ -0,0 +1,39 @@
const instrumentMap = require('./instrument_map.js')
const percussionMap = require('./percussion_map.js')
function convertNote (track, note) {
let instrument = null
const instrumentList = instrumentMap[track.instrument.number]
if (instrumentList != null) {
for (const candidateInstrument of instrumentList) {
if (note.midi >= candidateInstrument.offset && note.midi <= candidateInstrument.offset + 24) {
instrument = candidateInstrument
break
}
}
}
if (instrument == null) return null
const pitch = note.midi - instrument.offset
const time = Math.floor(note.time * 1000)
return { time, instrument: instrument.name, pitch, volume: note.velocity }
}
function convertPercussionNote (track, note) {
if (note.midi < percussionMap.length) {
const mapEntry = percussionMap[note.midi]
if (mapEntry == null) return
const { pitch, instrument } = mapEntry
const time = Math.floor(note.time * 1000)
return { time, instrument: instrument.name, pitch, volume: note.velocity }
}
return null
}
module.exports = { convertNote, convertPercussionNote }

View file

@ -0,0 +1,153 @@
const instruments = require('./instruments.json')
module.exports = [
// Piano (harp bass bell)
[instruments.harp, instruments.bass, instruments.bell], // Acoustic Grand Piano
[instruments.harp, instruments.bass, instruments.bell], // Bright Acoustic Piano
[instruments.bit, instruments.didgeridoo, instruments.bell], // Electric Grand Piano
[instruments.harp, instruments.bass, instruments.bell], // Honky-tonk Piano
[instruments.bit, instruments.didgeridoo, instruments.bell], // Electric Piano 1
[instruments.bit, instruments.didgeridoo, instruments.bell], // Electric Piano 2
[instruments.harp, instruments.bass, instruments.bell], // Harpsichord
[instruments.harp, instruments.bass, instruments.bell], // Clavinet
// Chromatic Percussion (iron_xylophone xylophone bass)
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Celesta
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Glockenspiel
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Music Box
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Vibraphone
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Marimba
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Xylophone
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Tubular Bells
[instruments.iron_xylophone, instruments.bass, instruments.xylophone], // Dulcimer
// Organ (bit didgeridoo bell)
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Drawbar Organ
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Percussive Organ
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Rock Organ
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Church Organ
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Reed Organ
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Accordian
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Harmonica
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Tango Accordian
// Guitar (bit didgeridoo bell)
[instruments.guitar, instruments.harp, instruments.bass, instruments.bell], // Acoustic Guitar (nylon)
[instruments.guitar, instruments.harp, instruments.bass, instruments.bell], // Acoustic Guitar (steel)
[instruments.guitar, instruments.harp, instruments.bass, instruments.bell], // Electric Guitar (jazz)
[instruments.guitar, instruments.harp, instruments.bass, instruments.bell], // Electric Guitar (clean)
[instruments.guitar, instruments.harp, instruments.bass, instruments.bell], // Electric Guitar (muted)
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Overdriven Guitar
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Distortion Guitar
[instruments.guitar, instruments.harp, instruments.bass, instruments.bell], // Guitar Harmonics
// Bass
[instruments.bass, instruments.harp, instruments.bell], // Acoustic Bass
[instruments.bass, instruments.harp, instruments.bell], // Electric Bass (finger)
[instruments.bass, instruments.harp, instruments.bell], // Electric Bass (pick)
[instruments.bass, instruments.harp, instruments.bell], // Fretless Bass
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Slap Bass 1
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Slap Bass 2
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Synth Bass 1
[instruments.didgeridoo, instruments.bit, instruments.xylophone], // Synth Bass 2
// Strings
[instruments.flute, instruments.guitar, instruments.bass, instruments.bell], // Violin
[instruments.flute, instruments.guitar, instruments.bass, instruments.bell], // Viola
[instruments.flute, instruments.guitar, instruments.bass, instruments.bell], // Cello
[instruments.flute, instruments.guitar, instruments.bass, instruments.bell], // Contrabass
[instruments.bit, instruments.didgeridoo, instruments.bell], // Tremolo Strings
[instruments.harp, instruments.bass, instruments.bell], // Pizzicato Strings
[instruments.harp, instruments.bass, instruments.chime], // Orchestral Harp
[instruments.harp, instruments.bass, instruments.bell], // Timpani
// Ensenble
[instruments.harp, instruments.bass, instruments.bell], // String Ensemble 1
[instruments.harp, instruments.bass, instruments.bell], // String Ensemble 2
[instruments.harp, instruments.bass, instruments.bell], // Synth Strings 1
[instruments.harp, instruments.bass, instruments.bell], // Synth Strings 2
[instruments.harp, instruments.bass, instruments.bell], // Choir Aahs
[instruments.harp, instruments.bass, instruments.bell], // Voice Oohs
[instruments.harp, instruments.bass, instruments.bell], // Synth Choir
[instruments.harp, instruments.bass, instruments.bell], // Orchestra Hit
// Brass
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.bit, instruments.didgeridoo, instruments.bell],
// Reed
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
// Pipe
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
[instruments.flute, instruments.didgeridoo, instruments.iron_xylophone, instruments.bell],
// Synth Lead
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
// Synth Pad
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
// Synth Effects
null,
null,
[instruments.bit, instruments.didgeridoo, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
[instruments.harp, instruments.bass, instruments.bell],
// Ethnic
[instruments.banjo, instruments.bass, instruments.bell],
[instruments.banjo, instruments.bass, instruments.bell],
[instruments.banjo, instruments.bass, instruments.bell],
[instruments.banjo, instruments.bass, instruments.bell],
[instruments.banjo, instruments.bass, instruments.bell],
[instruments.harp, instruments.didgeridoo, instruments.bell],
[instruments.harp, instruments.didgeridoo, instruments.bell],
[instruments.harp, instruments.didgeridoo, instruments.bell],
// Percussive
[instruments.iron_xylophone, instruments.bass, instruments.xylophone],
[instruments.iron_xylophone, instruments.bass, instruments.xylophone],
[instruments.iron_xylophone, instruments.bass, instruments.xylophone],
[instruments.iron_xylophone, instruments.bass, instruments.xylophone],
[instruments.iron_xylophone, instruments.bass, instruments.xylophone],
[instruments.iron_xylophone, instruments.bass, instruments.xylophone],
[instruments.iron_xylophone, instruments.bass, instruments.xylophone],
[instruments.iron_xylophone, instruments.bass, instruments.xylophone]
]

View file

@ -0,0 +1,82 @@
{
"harp": {
"id": 0,
"name": "harp",
"offset": 54
},
"basedrum": {
"id": 1,
"name": "basedrum",
"offset": 0
},
"snare": {
"id": 2,
"name": "snare",
"offset": 0
},
"hat": {
"id": 3,
"name": "hat",
"offset": 0
},
"bass": {
"id": 4,
"name": "bass",
"offset": 30
},
"flute": {
"id": 5,
"name": "flute",
"offset": 66
},
"bell": {
"id": 6,
"name": "bell",
"offset": 78
},
"guitar": {
"id": 7,
"name": "guitar",
"offset": 42
},
"chime": {
"id": 8,
"name": "chime",
"offset": 78
},
"xylophone": {
"id": 9,
"name": "xylophone",
"offset": 78
},
"iron_xylophone": {
"id": 10,
"name": "iron_xylophone",
"offset": 54
},
"cow_bell": {
"id": 11,
"name": "cow_bell",
"offset": 66
},
"didgeridoo": {
"id": 12,
"name": "didgeridoo",
"offset": 30
},
"bit": {
"id": 13,
"name": "bit",
"offset": 54
},
"banjo": {
"id": 14,
"name": "banjo",
"offset": 54
},
"pling": {
"id": 15,
"name": "pling",
"offset": 54
}
}

View file

@ -0,0 +1,36 @@
const { Midi } = require('@tonejs/midi')
const { convertNote, convertPercussionNote } = require('./convert_note.js')
function convertMidi (midi) {
if (!(midi instanceof Midi)) throw new TypeError("midi must be an instance of require('@tonejs/midi').Midi")
let noteList = []
for (const track of midi.tracks) {
for (const note of track.notes) {
const mcNote = (track.instrument.percussion ? convertPercussionNote : convertNote)(track, note)
if (mcNote != null) {
noteList.push(mcNote)
}
}
}
noteList = noteList.sort((a, b) => a.time - b.time)
// It might be better to move some of this code to the converting loop (for performance reasons)
let maxVolume = 0.001
for (const note of noteList) {
if (note.volume > maxVolume) maxVolume = note.volume
}
for (const note of noteList) {
note.volume /= maxVolume
}
let songLength = 0
for (const note of noteList) {
if (note.time > songLength) songLength = note.time
}
return { name: midi.header.name, notes: noteList, loop: false, loopPosition: 0, length: songLength }
}
module.exports = { convertMidi, convertNote, convertPercussionNote }

View file

@ -0,0 +1,3 @@
{
"main": "main.js"
}

View file

@ -0,0 +1,58 @@
const instruments = require('./instruments.json')
module.exports = [
...new Array(35).fill(null), // offset
{ pitch: 10, instrument: instruments.basedrum },
{ pitch: 6, instrument: instruments.basedrum },
{ pitch: 6, instrument: instruments.hat },
{ pitch: 8, instrument: instruments.snare },
{ pitch: 6, instrument: instruments.hat },
{ pitch: 4, instrument: instruments.snare },
{ pitch: 6, instrument: instruments.basedrum },
{ pitch: 22, instrument: instruments.snare },
{ pitch: 13, instrument: instruments.basedrum },
{ pitch: 22, instrument: instruments.snare },
{ pitch: 15, instrument: instruments.basedrum },
{ pitch: 18, instrument: instruments.snare },
{ pitch: 20, instrument: instruments.basedrum },
{ pitch: 23, instrument: instruments.basedrum },
{ pitch: 17, instrument: instruments.snare },
{ pitch: 23, instrument: instruments.basedrum },
{ pitch: 24, instrument: instruments.snare },
{ pitch: 8, instrument: instruments.snare },
{ pitch: 13, instrument: instruments.snare },
{ pitch: 18, instrument: instruments.hat },
{ pitch: 18, instrument: instruments.snare },
{ pitch: 1, instrument: instruments.hat },
{ pitch: 13, instrument: instruments.snare },
{ pitch: 2, instrument: instruments.hat },
{ pitch: 13, instrument: instruments.snare },
{ pitch: 9, instrument: instruments.hat },
{ pitch: 2, instrument: instruments.hat },
{ pitch: 8, instrument: instruments.hat },
{ pitch: 22, instrument: instruments.basedrum },
{ pitch: 15, instrument: instruments.basedrum },
{ pitch: 13, instrument: instruments.snare },
{ pitch: 8, instrument: instruments.snare },
{ pitch: 8, instrument: instruments.hat },
{ pitch: 3, instrument: instruments.hat },
{ pitch: 20, instrument: instruments.hat },
{ pitch: 23, instrument: instruments.hat },
{ pitch: 24, instrument: instruments.hat },
{ pitch: 24, instrument: instruments.hat },
{ pitch: 17, instrument: instruments.hat },
{ pitch: 11, instrument: instruments.hat },
{ pitch: 18, instrument: instruments.hat },
{ pitch: 9, instrument: instruments.hat },
{ pitch: 5, instrument: instruments.hat },
{ pitch: 22, instrument: instruments.hat },
{ pitch: 19, instrument: instruments.snare },
{ pitch: 17, instrument: instruments.hat },
{ pitch: 22, instrument: instruments.hat },
{ pitch: 22, instrument: instruments.snare },
{ pitch: 24, instrument: instruments.chime },
{ pitch: 24, instrument: instruments.chime },
{ pitch: 21, instrument: instruments.hat },
{ pitch: 14, instrument: instruments.basedrum },
{ pitch: 7, instrument: instruments.basedrum }
]

17
util/secondToHms.js Normal file
View file

@ -0,0 +1,17 @@
/**
* from codegrepper
* @param {Number} d
* @return {String}
*/
function secondsToHms(d) {
d = Number(d);
const h = Math.floor(d / 3600);
const m = Math.floor(d % 3600 / 60);
const s = Math.floor(d % 3600 % 60);
const hDisplay = h > 0 ? h + (h == 1 ? ' hour, ' : ' hours, ') : '';
const mDisplay = m > 0 ? m + (m == 1 ? ' minute, ' : ' minutes, ') : '';
const sDisplay = s > 0 ? s + (s == 1 ? ' second' : ' seconds') : '';
return hDisplay + mDisplay + sDisplay;
}
module.exports = {secondsToHms};

147
util/text_parser.js Normal file
View file

@ -0,0 +1,147 @@
/* eslint-disable max-len */
const {language} = require('minecraft-data')('1.16.1');
const colormap = {
black: '§0',
dark_blue: '§1',
dark_green: '§2',
dark_aqua: '§3',
dark_red: '§4',
dark_purple: '§5',
gold: '§6',
gray: '§7',
dark_gray: '§8',
blue: '§9',
green: '§a',
aqua: '§b',
red: '§c',
light_purple: '§d',
yellow: '§e',
white: '§f',
reset: '§r',
};
const ansimap = {
'§0': '\x1b[0m\x1b[30m',
'§1': '\x1b[0m\x1b[34m',
'§2': '\x1b[0m\x1b[32m',
'§3': '\x1b[0m\x1b[36m',
'§4': '\x1b[0m\x1b[31m',
'§5': '\x1b[0m\x1b[35m',
'§6': '\x1b[0m\x1b[33m',
'§7': '\x1b[0m\x1b[37m',
'§8': '\x1b[0m\x1b[90m',
'§9': '\x1b[0m\x1b[94m',
'§a': '\x1b[0m\x1b[92m',
'§b': '\x1b[0m\x1b[96m',
'§c': '\x1b[0m\x1b[91m',
'§d': '\x1b[0m\x1b[95m',
'§e': '\x1b[0m\x1b[93m',
'§f': '\x1b[0m\x1b[97m',
'§r': '\x1b[0m',
'§l': '\x1b[1m',
'§o': '\x1b[3m',
'§n': '\x1b[4m',
'§m': '\x1b[9m',
'§k': '\x1b[6m',
};
/**
* Parses a native minecraft text component in string form.
* @param {string} string - A text component string, such as the chat packet's "message" property.
* @return {object} Parsed message in { raw, clean, ansi } form.
*/
function parseText(string) {
const json = JSON.parse(string);
let raw = parseJson(json, {color: 'reset'});
if (raw.startsWith('§r')) {
raw = raw.substring(2);
}
const clean = raw.replace(/§.?/g, '');
const ansi = raw.replace(/§.?/g, (m) => ansimap[m] || '');
return {raw, clean, ansi};
}
/**
* Parses a native minecraft text component in JSON form.
* @param {object} json - The json message.
* @param {object} parent - The parent json.
* @return {string} The parsed raw string.
*/
function parseJson(json, parent) {
if (typeof json === 'string') json = {text: json};
json.color ??= parent.color;
json.bold ??= parent.bold;
json.italic ??= parent.italic;
json.underlined ??= parent.underlined;
json.strikethrough ??= parent.strikethrough;
json.obfuscated ??= parent.obfuscated;
let raw = '';
let formatting = '';
raw += colormap[json.color] ?? '';
if (json.bold) {
formatting += '§l';
}
if (json.italic) {
formatting += '§o';
}
if (json.underlined) {
formatting += '§n';
}
if (json.strikethrough) {
formatting += '§m';
}
if (json.obfuscated) {
formatting += '§k';
}
raw += formatting;
if (json.text) {
raw += json.text;
} else if (json.translate) { // I checked with the native minecraft code. This is how Minecraft does the matching and group indexing. -hhhzzzsss
if (language[json.translate]) {
const _with = json.with ?? [];
let i = 0;
raw += language[json.translate].replace(/%(?:(\d+)\$)?(s|%)/g, (g0, g1) => {
if (g0 === '%%') {
return '%';
} else {
const idx = g1 ? parseInt(g1) : i++;
if (_with[idx]) {
return parseJson(_with[idx], json) + formatting;
} else {
return '';
}
}
});
} else {
raw += json.translate;
}
} else if (json.selector) {
raw += json.selector;
} else if (json.keybind) {
raw += json.keybind;
}
// Remove trailing section signs
let end = raw.length;
while (raw[end - 1] === '§') end--;
raw = raw.substring(0, end);
if (json.extra) {
json.extra.forEach((extra) => {
raw += parseJson(extra, json);
});
}
return raw;
}
module.exports = parseText;