plugin refactor and stuff

This commit is contained in:
Chipmunk 2024-02-29 20:39:21 -05:00
parent f139c0b417
commit 989b3fa1f3
26 changed files with 88 additions and 100 deletions

34
bot.js
View file

@ -3,6 +3,12 @@ const { EventEmitter } = require('events')
const fs = require('fs') const fs = require('fs')
const path = require('path') const path = require('path')
const plugins = []
for (const filename of fs.readdirSync('plugins')) {
if (!filename.endsWith('.js')) return
plugins.push(require(path.resolve('plugins', filename)))
}
function createBot (options = {}) { function createBot (options = {}) {
// defaults // defaults
options.username ??= 'Bot' options.username ??= 'Bot'
@ -10,20 +16,6 @@ function createBot (options = {}) {
options.prefix ??= '!' options.prefix ??= '!'
options.brand ??= 'vanilla' // found that mineflayer has this so i added it here lol options.brand ??= 'vanilla' // found that mineflayer has this so i added it here lol
options.plugins ??= {}
fs.readdirSync(
'plugins'
).forEach((file) => { // populate plugins array
if (file.endsWith('.js') && options.plugins[file] == null) {
options.plugins[file] = require(path.resolve('plugins', file))
}
})
const plugins = []
Object.keys(options.plugins).forEach((key) => {
const plugin = options.plugins[key]
if (plugin) plugins.push(plugin)
})
options.colors ??= {} options.colors ??= {}
options.colors.primary ??= 'white' options.colors.primary ??= 'white'
options.colors.secondary ??= 'green' options.colors.secondary ??= 'green'
@ -99,23 +91,19 @@ function createBot (options = {}) {
bot._client.write('teleport_confirm', { teleportId: packet.teleportId }) bot._client.write('teleport_confirm', { teleportId: packet.teleportId })
}) })
// plugin injection bot._client.on('packet', (data, meta) => {
bot.plugins.forEach((plugin) => { bot.emit('packet', data, meta);
if (typeof plugin.client === 'function') plugin.client(bot, bot._client) bot.emit('packet.' + meta.name, data);
}) })
}) })
bot._client = options.client ?? mc.createClient(options) bot._client = options.client ?? mc.createClient(options)
bot.emit('set_client', bot._client) bot.emit('set_client', bot._client)
bot.plugins.forEach((plugin) => { for (const plugin of plugins) plugin(bot)
if (typeof plugin.bot === 'function') plugin.bot(bot)
})
function loadPlugin (plugin) { function loadPlugin (plugin) {
try { try {
if (typeof plugin.bot === 'function') plugin.bot(bot) plugin(bot)
if (typeof plugin.client === 'function') plugin.client(bot, bot._client)
bot.plugins.push(plugin)
} catch (e) { } catch (e) {
console.log(`Error loading ${plugin}:`) console.log(`Error loading ${plugin}:`)
console.log(require('util').inspect(e)) console.log(require('util').inspect(e))

View file

@ -4,7 +4,7 @@ const usages = ['destroy']
const aliases = ['destroy'] const aliases = ['destroy']
const enabled = true const enabled = true
const permLevel = 0 const permLevel = 1
function execute (bot, cmd, entity, args, handler) { function execute (bot, cmd, entity, args, handler) {
let i = 0 let i = 0

View file

@ -29,7 +29,7 @@ function execute (bot, cmd, player, args, handler) {
msg.push({ text: a[i] }) msg.push({ text: a[i] })
if (a[i + 1] != null) { if (a[i + 1] != null) {
msg.push( msg.push(
{ text: a[i + 1], underlined: true, clickEvent: { action: 'run_command', value: `${bot.prefix}${name} ${a[i + 1]}` } } { text: a[i + 1], underlined: true, clickEvent: { action: 'suggest_command', value: `${bot.prefix}${name} ${a[i + 1]}` } }
) )
} }
} }

View file

@ -1,14 +1,6 @@
[ [
[
"test00001",
""
],
[ [
"MCSTORM_IO_.*", "MCSTORM_IO_.*",
"" ""
],
[
"okay",
"g"
] ]
] ]

File diff suppressed because one or more lines are too long

View file

@ -1,4 +1,4 @@
function bot (bot) { function inject (bot) {
bot.on('login', () => { bot.on('login', () => {
bot.chat.queue.push('/commandspy:commandspy on') bot.chat.queue.push('/commandspy:commandspy on')
// bot.chat.queue.push('/essentials:vanish enable') // bot.chat.queue.push('/essentials:vanish enable')
@ -18,19 +18,22 @@ function bot (bot) {
}) })
bot.on('chat', (message) => { bot.on('chat', (message) => {
// if (/\u00a76Vanish for .*\u00a76: disabled/.test(message.raw)) { bot.core.run(`sudo ${bot._client.uuid} essentials:vanish enable`) } else if (/§6God mode§c disabled§6./.test(message.raw)) { bot.core.run(`sudo ${bot._client.uuid} essentials:god enable`) } else if (/§rSuccessfully disabled CommandSpy/.test(message.raw)) { bot.core.run(`sudo ${bot._client.uuid} commandspy:commandspy on`) } else if (/§6Your nickname is now .*§6./.test(message.raw)) { bot.core.run(`essentials:nick ${bot._client.uuid} off`) } if (/\u00a76Vanish for .*\u00a76: disabled/.test(message.raw)) {
}) bot.core.run(`sudo ${bot._client.uuid} essentials:vanish enable`)
} else if (/§6God mode§c disabled§6./.test(message.raw)) {
bot._client.on('player_info', (packet) => { bot.core.run(`sudo ${bot._client.uuid} essentials:god enable`)
if (packet.action === 0) { } else if (/§rSuccessfully disabled CommandSpy/.test(message.raw)) {
packet.data.forEach((player) => { bot.core.run(`sudo ${bot._client.uuid} commandspy:commandspy on`)
if (player.UUID === bot._client.uuid && player.name !== bot._client.username) { bot.core.run(`essentials:sudo ${bot._client.uuid} username ${bot._client.username}`) } } else if (/§6Your nickname is now .*§6./.test(message.raw)) {
}) bot.core.run(`essentials:nick ${bot._client.uuid} off`)
} }
}) })
}
function client (bot, client) { bot.on('player_added', (player) => {
client.on('game_state_change', (packet) => { if (player.uuid === bot._client.uuid && player.username !== bot._client.username) bot.core.run(`essentials:sudo ${bot._client.uuid} username ${bot._client.username}`)
})
bot.on('packet.game_state_change', (packet) => {
switch (packet.reason) { switch (packet.reason) {
case 3: case 3:
if (packet.gameMode !== 1) { bot.chat.queue.push('/minecraft:gamemode creative @s[type=player]') } if (packet.gameMode !== 1) { bot.chat.queue.push('/minecraft:gamemode creative @s[type=player]') }
@ -40,11 +43,11 @@ function client (bot, client) {
} }
}) })
client.on('update_health', (packet) => { bot.on('packet.update_health', (packet) => {
if (packet.health <= 0) { bot._client.write('client_command', { payload: 0 }) } if (packet.health <= 0) { bot._client.write('client_command', { payload: 0 }) }
}) })
// bot._client.on('declare_commands', () => bot.chat.queue.push(bot.brand === 'kaboom' ? '/op @s[type=player]' : '/trigger opme')) // assumes that the vanilla server has an 'opme' trigger bot.on('packet.declare_commands', () => bot.chat.queue.push(bot.brand === 'kaboom' ? '/op @s[type=player]' : '/trigger opme')) // assumes that the vanilla server has an 'opme' trigger
} }
module.exports = { bot, client } module.exports = inject

View file

@ -17,18 +17,15 @@ setInterval(() => {
}, 5 * 6000) }, 5 * 6000)
// expose the blacklist and make the bot uuid ban blacklisted players // expose the blacklist and make the bot uuid ban blacklisted players
function bot (bot) { bot.blacklist = blacklist } function inject (bot) {
bot.blacklist = blacklist
function client (bot, client) { bot.on('player_added', player => {
client.on('player_info', (packet) => { for (const [pattern, flags] of blacklist) {
if (packet.action === 0) { const regex = new RegExp(pattern, flags)
packet.data.forEach((player) => { if (regex.test(player.username)) bot.exploits.uuidBan(player.uuid)
blacklist.forEach(([pattern, flags]) => {
if (new RegExp(pattern, flags).test(player.name)) { bot.exploits.uuidBan(player.UUID) }
})
})
} }
}) })
} }
module.exports = { bot, client } module.exports = inject

View file

@ -13,4 +13,4 @@ function inject (bot) {
}) })
} }
module.exports.bot = inject module.exports = inject

View file

@ -61,4 +61,4 @@ function censor (match) {
return c return c
} }
module.exports.bot = inject module.exports = inject

View file

@ -1,7 +1,7 @@
const parseText = require('./../util/text_parser.js') const parseText = require('./../util/text_parser.js')
const nbt = require('prismarine-nbt') const nbt = require('prismarine-nbt')
function bot (bot) { function inject (bot) {
bot.chat = { bot.chat = {
queue: [], queue: [],
patterns: [], patterns: [],
@ -75,20 +75,18 @@ function bot (bot) {
bot.emit('cspy', player, command) bot.emit('cspy', player, command)
} }
}) })
}
function client (bot, client) { bot.on('packet.profileless_chat', (packet) => {
client.on('profileless_chat', (packet) => {
const message = parseText(nbt.simplify(packet.message)) const message = parseText(nbt.simplify(packet.message))
bot.emit('chat', message, packet) bot.emit('chat', message, packet)
}) })
client.on('player_chat', (packet) => { bot.on('packet.player_chat', (packet) => {
const message = packet.unsignedChatContent ? parseText(nbt.simplify(packet.unsignedChatContent)) : packet.plainMessage const message = packet.unsignedChatContent ? parseText(nbt.simplify(packet.unsignedChatContent)) : packet.plainMessage
bot.emit('chat', message, { sender: packet.senderUuid }) bot.emit('chat', message, { sender: packet.senderUuid })
}) })
client.on('system_chat', (packet) => { bot.on('packet.system_chat', (packet) => {
const json = nbt.simplify(packet.content) const json = nbt.simplify(packet.content)
if (json?.translate === 'advMode.setCommand.success') return if (json?.translate === 'advMode.setCommand.success') return
@ -97,4 +95,4 @@ function client (bot, client) {
}) })
} }
module.exports = { bot, client } module.exports = inject

View file

@ -14,4 +14,4 @@ function inject (bot) {
} }
} }
module.exports.bot = inject module.exports = inject

View file

@ -43,9 +43,12 @@ function inject (bot) {
} }
} }
const requirement = source => source.permissionLevel >= command.permLevel
const node = bot.commands.dispatcher.register( const node = bot.commands.dispatcher.register(
literal(command.aliases[0]) literal(command.aliases[0])
.executes(c => { _execute(c, []); return 0 }) .executes(c => { _execute(c, []); return 0 })
.requires(requirement)
.then( .then(
argument('args', greedyString()) argument('args', greedyString())
.executes(c => { _execute(c, c.getArgument('args').split(' ')); return 0 }) .executes(c => { _execute(c, c.getArgument('args').split(' ')); return 0 })
@ -55,6 +58,7 @@ function inject (bot) {
bot.commands.dispatcher.register( bot.commands.dispatcher.register(
literal(command.aliases[i]) literal(command.aliases[i])
.executes(context => { _execute([]); return 0 }) .executes(context => { _execute([]); return 0 })
.requires(requirement)
.redirect(node) .redirect(node)
) )
} }
@ -143,4 +147,4 @@ function isValid (command) {
typeof command.permLevel === 'number' typeof command.permLevel === 'number'
} }
module.exports.bot = inject module.exports = inject

View file

@ -74,7 +74,7 @@ function inject (bot) {
function handleLine (line) { function handleLine (line) {
if (bot.host !== bot.console.host && bot.console.host !== 'all') return if (bot.host !== bot.console.host && bot.console.host !== 'all') return
if (line.startsWith('.')) { if (line.startsWith('.')) {
const source = new CommandSource({ bot, sendFeedback }) const source = new CommandSource({ bot, permissionLevel: Infinity, sendFeedback })
bot.commands.execute(line.substring(1), source) bot.commands.execute(line.substring(1), source)
} else { } else {
bot.fancyMsg('test', '_ChipMC_', line) bot.fancyMsg('test', '_ChipMC_', line)
@ -89,4 +89,4 @@ function inject (bot) {
} }
} }
module.exports.bot = inject module.exports = inject

View file

@ -1,7 +1,7 @@
const nbt = require('prismarine-nbt') const nbt = require('prismarine-nbt')
const mcNamespace = 'minecraft:' const mcNamespace = 'minecraft:'
function bot (bot) { function inject (bot) {
let mcData = require('minecraft-data')('1.17.1') let mcData = require('minecraft-data')('1.17.1')
bot.on('login', () => (mcData = require('minecraft-data')(bot._client.version))) bot.on('login', () => (mcData = require('minecraft-data')(bot._client.version)))
@ -85,4 +85,4 @@ function bot (bot) {
setInterval(() => bot.core.refill(), 60 * 1000) setInterval(() => bot.core.refill(), 60 * 1000)
} }
module.exports = { bot } module.exports = inject

View file

@ -128,4 +128,4 @@ function inject (bot) {
return result return result
}*/ }*/
module.exports.bot = inject module.exports = inject

View file

@ -9,13 +9,13 @@ while (lootTable.length <= 256) { lootTable += 'i' }
function inject (bot) { function inject (bot) {
bot.exploits = { bot.exploits = {
titleKick: function (selector) { titleKick (selector) {
return new Promise((resolve) => { return new Promise((resolve) => {
bot.core.run(`minecraft:title ${selector} title ${JSON.stringify(kick)}`) bot.core.run(`minecraft:title ${selector} title ${JSON.stringify(kick)}`)
bot.once('player_info', resolve) bot.once('player_info', resolve)
}) })
}, },
uuidBan: function (UUID) { uuidBan (UUID) {
return new Promise((resolve) => { return new Promise((resolve) => {
const nbtUUID = toNBTUUID(UUID) const nbtUUID = toNBTUUID(UUID)
bot.exploits.titleKick(`@p[nbt=${SNBT.stringify(nbt.comp({ UUID: nbtUUID }))}]`).then((packet) => { bot.exploits.titleKick(`@p[nbt=${SNBT.stringify(nbt.comp({ UUID: nbtUUID }))}]`).then((packet) => {
@ -24,17 +24,17 @@ function inject (bot) {
}) })
}) })
}, },
bossbarBan: function (selector) { bossbarBan (selector) {
bot.core.run(`/bossbar add ban title ${JSON.stringify(kick)}`) bot.core.run(`/bossbar add ban title ${JSON.stringify(kick)}`)
setTimeout(() => bot.core.run(`/minecraft:bossbar set ban players ${selector}`), 50) setTimeout(() => bot.core.run(`/minecraft:bossbar set ban players ${selector}`), 50)
}, },
chunkBan: function () { chunkBan () {
// i will add code later // i will add code later
}, },
execute: function (args) { execute (args) {
bot.core.run(`minecraft:execute unless data entity @p run ${args}`) bot.core.run(`minecraft:execute unless data entity @p run ${args}`)
} }
} }
} }
module.exports.bot = inject module.exports = inject

View file

@ -12,4 +12,4 @@ function inject (bot) {
} }
} }
module.exports.bot = inject module.exports = inject

View file

@ -13,4 +13,4 @@ function inject (bot) {
} }
} }
module.exports.bot = inject module.exports = inject

View file

@ -82,4 +82,4 @@ function kahootErrMsg (message) {
]) ])
} }
module.exports.bot = inject module.exports = inject

View file

@ -12,4 +12,4 @@ function inject (bot) {
}) })
} }
module.exports.bot = inject module.exports = inject

View file

@ -25,4 +25,4 @@ function inject (bot) {
} }
} }
module.exports.bot = inject module.exports = inject

View file

@ -128,4 +128,4 @@ function format (ms) {
return seconds + ':' + (minutes.length <= 1 ? '0' : '') + minutes return seconds + ':' + (minutes.length <= 1 ? '0' : '') + minutes
} }
module.exports.bot = inject module.exports = inject

View file

@ -2,10 +2,10 @@ const nbt = require('prismarine-nbt')
const gamemodes = ['survival', 'creative', 'adventure', 'spectator'] const gamemodes = ['survival', 'creative', 'adventure', 'spectator']
function inject (bot, client) { function inject (bot) {
bot.players = [] bot.players = []
client.on('player_info', packet => { bot.on('packet.player_info', packet => {
for (const player of packet.data) { for (const player of packet.data) {
if (packet.action & 1) addPlayer(player) if (packet.action & 1) addPlayer(player)
if (packet.action & 2) initializeChat(player) if (packet.action & 2) initializeChat(player)
@ -16,6 +16,12 @@ function inject (bot, client) {
} }
}) })
bot.on('packet.player_remove', packet => {
for (const uuid of packet.players) {
removePlayer(uuid)
}
})
function addPlayer (player) { function addPlayer (player) {
bot.players.filter(_player => _player.uuid !== player.uuid) // Remove duplicates bot.players.filter(_player => _player.uuid !== player.uuid) // Remove duplicates
@ -65,13 +71,13 @@ function inject (bot, client) {
} }
async function removePlayer (uuid) { async function removePlayer (uuid) {
const target = bot.players.find(_player => _player.uuid === player.uuid) const target = bot.players.find(_player => _player.uuid === uuid)
if (target == null) return if (target == null) return
// Check that the player actually left // Check that the player actually left
const completions = await bot.tabComplete('scoreboard players add ') const completions = await bot.tabComplete('scoreboard players add ')
for (const match of completions.matches) { for (const match of completions.matches) {
if (match.tooltip) return if (match.tooltip) continue
if (match.match === target.username) { if (match.match === target.username) {
target.listed = false target.listed = false
@ -83,7 +89,7 @@ function inject (bot, client) {
bot.emit('player_removed', target) bot.emit('player_removed', target)
} }
client.on('end', () => (bot.players = [])) bot.on('end', () => (bot.players = []))
} }
module.exports.client = inject module.exports = inject

View file

@ -17,7 +17,7 @@ setInterval(() => {
}, 5 * 6000) }, 5 * 6000)
// expose the data to the bot // expose the data to the bot
function bot (bot) { function inject (bot) {
bot.seen = seen bot.seen = seen
bot.on('player_added', player => { bot.on('player_added', player => {
@ -40,4 +40,4 @@ function bot (bot) {
}) })
} }
module.exports = { bot } module.exports = inject

View file

@ -1,17 +1,17 @@
function inject (bot, client) { function inject (bot) {
const transactions = {} const transactions = {}
let transactionId = 0 let transactionId = 0
function tabComplete (text) { function tabComplete (text) {
return new Promise(resolve => { return new Promise(resolve => {
transactions[transactionId] = resolve transactions[transactionId] = resolve
client.write('tab_complete', { transactionId, text }) bot._client.write('tab_complete', { transactionId, text })
transactionId = (transactionId + 1) % 256 transactionId = (transactionId + 1) % 256
}) })
} }
client.on('tab_complete', packet => { bot.on('packet.tab_complete', packet => {
if (!transactions[packet.transactionId]) return if (!transactions[packet.transactionId]) return
transactions[packet.transactionId](packet) transactions[packet.transactionId](packet)
@ -21,4 +21,4 @@ function inject (bot, client) {
bot.tabComplete = tabComplete bot.tabComplete = tabComplete
} }
module.exports.client = inject module.exports = inject

View file

@ -95,4 +95,4 @@ function inject (bot) {
} }
} }
module.exports.bot = inject module.exports = inject