const mineflayer = require('mineflayer') // importing mineflayer
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const bot = mineflayer.createBot({
  host: 'localhost',             // minecraft server ip, use localhost for testing on your own machine (you have to have a minecraft server running)
  username: 'niceusername', // minecraft email or username (for non premium)
  // password: '12345678',       // minecraft password, leave commented out for testing or offline servers (use offline mode for testing because you might will quickly get ratelimited by mojang if you don't)
  // port: 25565,                // default port is 25565 and this will work for most servers. If you have to use a different port change it here
  // version: false,             // set a specific minecraft version that the bot should join from (default is on autodetect)
  // auth: 'mojang'              // set to 'microsoft' if you're using microsoft accounts
})

bot.on('spawn', () => { // triggers when the bot successfully logs in and spawns
  bot.chat("I spawned") // send a chat message
})


bot.on('chat:sayHello', async () => { // triggers when the event happens
    bot.chat("hi")
    for (let i = 0; i < 5; i++) { // repeat 5 times aka dig 5 blocks
        var target = bot.blockAt(bot.entity.position.offset(0, -1, 0)); // tell it where the block below is
        if (target && bot.canDigBlock(target)) {
          await bot.dig(target);
          await bot.chat("mining" + target);
          await sleep(500)
        }
        else {
          bot.chat("cant dig block"); // when the bot is standing in the middle of two blocks it might not be able to dig down causing this to trigger
          await sleep(5000);
        }
}})

bot.on('login', () => {
    bot.addChatPattern( // adding a chat pattern
        "sayHello", // event listener name
        /(hello)/ // regular expression of what the message should match for it to trigger
        );
    })



// If the bot gets kicked from the server it will tell you the reason in the console
bot.on('error', console.log)
bot.on('kicked', console.log)

const { mineflayer: mineflayerViewer } = require('prismarine-viewer') // add at the top of the js file

bot.once('spawn', () => { // on spawn event
  mineflayerViewer(bot, { port: 3007, firstPerson: true }) // the port specified is the webserver port, you should be fine leaving it at 3007
})