#Script API General

1 messages · Page 77 of 1

loud frigate
#

my guess its something to do with how the client entity is rendered and interpolated

dim tusk
#

1.21.80 which is preview.

prisma shard
#

Or could be your script is laggy

prisma shard
# loud frigate my guess its something to do with how the client entity is rendered and interpol...
/**
 * Shoots a projectile entity from a player's view direction.
 * @param {string} projectile The projectile typeId to shoot (example, "minecraft:arrow")
 * @param {number} power The speed of the projectile
 * @param {Player} source The player or entity to shoot the projectile from
 * @returns {Entity} The projectile
 */
export const shootProjectile = (projectile, power, source) => {
    const headLoc = source.getHeadLocation();
    const viewVector = source.getViewDirection();
    const direction = {
        x: headLoc.x + viewVector.x,
        y: headLoc.y + viewVector.y + viewVector.y * 0.4,
        z: headLoc.z + viewVector.z,
    };
    const vel = { x: viewVector.x * power, y: viewVector.y * power, z: viewVector.z * power };
    const entity = source.dimension.spawnEntity(projectile, direction);
    entity.getComponent("projectile").shoot(vel);

    return entity;
};```
How about  you could use this function to shoot the projectile from entity
#

try adjusting the power

dim tusk
#

Client problem or you're script is running heavy before spawning it.

prisma shard
prisma shard
loud frigate
dim tusk
#

and btw, what's the purpose of adding vectorY twice and multiplying by 0.4?

chrome flint
#

i just changed my script version manifest to 2.0.0-beta, how do i fix this?

loud frigate
prisma shard
#

the same

little hull
#
import { world } from "@minecraft/server";

world.afterEvents.entitySpawn.subscribe((event) => {
    const entity = event.entity;

    if (entity && entity.typeId === "zombie:explosion_cast") {
        const projectileComponent = entity.getComponent("minecraft:projectile");

        if (projectileComponent && projectileComponent.owner) {
            const owner = projectileComponent.owner;
            world.sendMessage(`Projectile was shot by: ${owner.typeId}`);
        } else {
            world.sendMessage("Projectile has no owner.");
        }
    }
});```
native patio
#

Hi

loud frigate
prisma shard
#

huh

patent bane
#

oof, thanks tho

warped blaze
#

you can't read the property if the world hasn't loaded yet

warped blaze
chrome flint
buoyant canopy
#

wait, can we not allow for more than 1 stack of items in a custom bundle

#

well, this puts the nail in the coffin for my custom equipment slots project

#

why is it not mentioned in the docs?

wary edge
wary edge
#

lol they removed iut.

dusky flicker
#

man, im making a way to addons send requests to a server(another addon) and receive a response from them

#

the thing is that if the client and the server dont block the thread, they do 10 requests per second due to runJob

#

the client executes runJob, the server as well so 2 runjobs, 2ticks lost

#

if both block, it can send up to 100 requests per second

#

but im planning to do something like merging a lot of requests in once

#

and send this single one

#
const client = new EnchantedClient({
  target: "enchanted",
  piece_len: 2048,
  uuid: "seupai"
});


world.afterEvents.playerBreakBlock.subscribe(async e => {
  let i = 0;
  const now = Date.now();
  while (Date.now() - now < 1000) {
    await client.send_object({ "route": "/" });
    i++;
  }
  console.log("Sent a total of", i, "requests");
});```
the code im running on minecraft
#

no i cannot use system.currentTick, both block thread, so the tick does not run

#

for some reason

#

anyways, i pretended doing something to merge them all

#

but actually im tired as hell of implementing this and having 1001 problems with some random request index

#

and now my brain is a bit slower so i cannot think in something

#

could someone help me?

#

i thought in using some kind of queue, for the sent content before actually sending, but it gets compressed

#

and i dont pretend compress each request made and put them together and then send, that would be heavy

#

just some way to predict the compressed size of the current sent request would be good

hollow sail
#

is there some other place to set scripting api version

#

i have the package version 1.18.0 but when i play the pack in preview i get errors because i guess its trying to load as 2.0

#

none of my components are registering

hollow sail
round bone
#

what errors are you getting?

hollow sail
#

And in game subscribe is undefined

#

And so is registerCustomComponent

round bone
#

NPM versions

round bone
#

Use worldLoad

hollow sail
#

Oh

hollow sail
round bone
#

What are your NPM package versions

hollow sail
#

i also can't find worldLoad anywherew

round bone
#

hmm, weird

thorn flicker
hollow sail
#

For some reason

#

Well I don’t even see worldload so I dunno

sweet seal
#

How to make banner red?


          const banner = new ItemStack("minecraft:banner", 1)
          banner.lockMode = 'slot'
          inventory.setItem(player.selectedSlotIndex, banner)
sharp elbow
#

Heh, I guess you can't. Color must be stored in NBT somewhere.

#

Unless you can give data values with scripting?

little hull
#
world.afterEvents.entityHitEntity.subscribe((event) => {
    const damager = event.damagingEntity;
    const damaged = event.hitEntity;
    if (damager && damager.typeId === 'zombie:megumin') {
        if (damager.hasComponent('minecraft:behavior.melee_attack') === true) {
            damaged.runCommand("summon zombie:explosion_majic ~ ~ ~");
        }
    }
});

world.afterEvents.entityHitEntity.subscribe((event) => {
    const damager = event.damagingEntity;
    if (damager && damager.typeId === 'zombie:megumin') {
        if (damager.hasComponent('minecraft:behavior.delayed_attack') === true) {
            damager.triggerEvent('zombie:tired');
        }
    }
});```
little hull
warped blaze
#

how does the arguments part of using a custom command work?

customCommandRegistry.registerCommand({...}, ({ origin, args }) => { //the "args" part in this line
  //???
});```
#

nvm i just figured it out

#

so obvious, but my brain wasn't braining

echo tinsel
#

Is it possible to set up a script that when an attachable is on an armor stand that when using an item on the armor stand it changes the attachables geometry(and the attachable keeps the geometry when taking it off the armor stand) based on the item used

patent bane
#

do commands actually run significantly slower than scripts?

shy leaf
#

its kinda indistinguishable with our bare eyes but

#

in mass quantity, scripts are significantly faster

patent bane
shy leaf
#

runCommand is a Plan B

deep quiver
#

something like /clear is probably faster as with script you gotta iterate through all slots and make an api call each time, instead of running just one command and letting the c++ handle it

#

But yeah you should usually do the script api methods

hexed fox
#

world.beforeEvents.chatSend.subscribe((data) => {
const player = data.sender;
const msg = data.message.toLowerCase();
const command = CustomCommands[msg];
if (!command) return;
system.run(() => command(player));
data.cancel = true;
});

Manifest part:
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.3.0"
},
{
"module_name": "@minecraft/server-ui",
"version": "2.0.0-beta"
}
]
}

How to fix the bug?

patent bane
patent bane
#

it should be like dis:

#
    "dependencies": [
        {
            "module_name": "@minecraft/server",
            "version": "2.0.0-beta"
        },
        {
            "module_name": "@minecraft/server-ui",
            "version": "1.3.0"
        }
    ]

sterile epoch
#

I think both server and server UI have to be beta

leaden elbow
#

checking player if is op is a property or a method?

nova flame
#

is there a way to make blocks in a certain area explosion-proof?

patent bane
#

yeah its a method

honest wave
#

how to write values using js? Example: if player moves script writes value "moving": true in json file, when not then fald?

wheat condor
#

Only bds

leaden elbow
#

modalform body is not a thing anymore?

round bone
leaden elbow
marsh pebble
#

@cobalt onyx

#

start here

cobalt onyx
#

Alright

nova flame
#

whats the problem here???

#
const deleted_items = [
    'minecraft:grass_block',
    'minecraft:dirt']

world.afterEvents.entitySpawn.subscribe(ev => {
    const entity = ev.entity;


    if (entity.typeId != 'minecraft:item') return;
    const item = entity.getComponent('item').itemStack;
    if (isInBoundingBox(entity.location, {x:-80, y:162, z:-81}, {x:92, y:63, z:91}) && deleted_items.includes(item.typeId)) {
        entity.remove();
    } 
})
#

its just not deleting the items

slender aurora
#

Hello 👋
I am just starting with scripting and wanted to ask: What is the differenz between scripting in javascript and typescript?

#

An are there some tutorials to easyli get started? I mean I have seen the Microsoft learn things, but even with them I don't really know how to dive into the topic of scripting 😅

remote oyster
# slender aurora Hello 👋 I am just starting with scripting and wanted to ask: What is the diffe...

TypeScript is a superset of JavaScript. It adds features to JavaScript, mainly static typing. Due to its design for static typing it helps to catch a lot of runtime bugs without necessarily having to load up a Minecraft World and test in-game. Cuts down debugging immensely.

The engine expects it to be JS. Developers will write the code using TS but then later transpile their scripts to JS for distribution/additional testing.

wheat condor
prisma shard
#

actually

#

since You guys are talking about typescript, Can anyone clear my doubt?
I have a confusion about TS

slender aurora
#

So if I sript, I will just always make it a .ts file?

wheat condor
remote oyster
# slender aurora So if I sript, I will just always make it a .ts file?

It's not required but if you want static typing to help ensure proper coding style while using the API's then it's recommended, but you can most certainly just use .js. JavaScript has JS-Docs as well which can be used to define and enforce typings in your script, but that is not necessarily required either. Though recommended in either case.

wheat condor
slender aurora
#

Okay, then I will write my script in a .ts file and if I want to test it in Minecraft, i will just change the extenion to .js?

copper egret
#

is there a technique for damage and knockback cancelation?

copper egret
wheat condor
#

Ask in entities thread

remote oyster
prisma shard
#

So, A doubt I have about TypeScript.
I know minecraft Script API itself doesn't support TS, And so You have to do tsc --watch, which automatically compiles the TS to JS , so you can load it in world. But.. TypeScript has some speical features, which JS don't have, such as Interface, If you put a code of interface inside a online Compiler, it will turn out.. Nothing as JS. SO how does minecraft itself reads it

slender aurora
prisma shard
wheat condor
prisma shard
#

i see

#

and what do you put inside manifest.json for the script path? does tsc --watch makes a compiled JS in background? Or a JS file next to the TS? But i seen developers have no JS file, in thier addon path.. Do you put the TS path in manifest.json? Or the JS

remote oyster
# prisma shard So, A doubt I have about TypeScript. I know minecraft Script API itself doesn't ...

In TypeScript, an interface defines the structure of an object, what properties it should have and their types. This helps the development environment provide real-time feedback, like autocompletion and error checking. JavaScript doesn’t need interfaces because it’s dynamically typed, it figures out object shapes at runtime. But TypeScript relies on static typing, so it needs a way to understand an object’s shape ahead of time, and that's what interfaces are for.

prisma shard
remote oyster
# prisma shard and what do you put inside `manifest.json` for the script path? does `tsc --wat...

You typically manage everything TypeScript-related using tsconfig.json. This file tells TypeScript how to behave, like where your .ts files are, how strict type-checking should be, and where the compiled .js files should go. For example, you might say: “Take everything from the src folder and compile it into a scripts folder,” and it’ll handle that automatically.

When you run tsc --watch, it listens for changes in your .ts files and continuously compiles them in the background based on those tsconfig rules. So even if you don’t see .js files in your source folders, they’re being generated elsewhere, usually in a dedicated output directory.

This process is often paired with package.json scripts where you define commands like "build" or "watch" to trigger the compiler or prep everything for distribution. So instead of touching files manually, you automate the pipeline and keep your TypeScript clean and separate from the final output.

prisma shard
#

Oh

#

I understand

#

Thanks!

remote oyster
#

I'll use my files as an example.

manifest.json

{
    "format_version": 2,
    "header": {
        "name": "Paradox AntiCheat",
        "description": "A utility to fight against malicious hackers on Bedrock Edition ~ v5.5.2",
        "uuid": "54edfea5-ab51-47ca-b992-724e255b5560",
        "version": [5, 5, 2],
        "min_engine_version": [1, 21, 70]
    },
    "metadata": {
        "authors": ["Visual1mpact"],
        "license": "GPLv3",
        "url": "https://github.com/Visual1mpact/Paradox_AntiCheat"
    },
    "modules": [
        {
            "type": "data",
            "uuid": "d8395127-6923-4fb7-93d2-977cecd463e0",
            "version": [1, 0, 0]
        },
        {
            "description": "Paradox AntiCheat API Features",
            "language": "javascript",
            "type": "script",
            "uuid": "1326c87b-37f3-4543-9f0f-0d03893134e1",
            "version": [0, 0, 1],
            "entry": "scripts/paradox.js"
        }
    ],
    "dependencies": [
        {
            "module_name": "@minecraft/server",
            "version": "2.0.0-beta"
        },
        {
            "module_name": "@minecraft/server-ui",
            "version": "2.0.0-beta"
        },
        {
            "module_name": "@minecraft/server-net",
            "version": "1.0.0-beta"
        }
    ],
    "capabilities": ["script_eval"]
}
prisma shard
#

yeahhh i see

#

Thanks for clearing my complete doubt

#

wait if the JS folder is outside the addon directory, how does manifest get it

#

becuase inside scripts folder you have TS

remote oyster
#

Nope, inside scripts folder I have .js when compiled and built. This is where your package.json comes into play, paired with your rules and instructions in tsconfig.json.

#

tsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "typeRoots": ["node_modules/@minecraft", "node_modules/@types"],
        "types": ["node", "server", "server-ui"],
        "lib": ["esnext"],
        "target": "esnext",
        "module": "esnext",
        "moduleResolution": "node10",
        "outDir": "build/scripts",
        "allowJs": false,
        "checkJs": false,
        "useDefineForClassFields": true,
        "noImplicitReturns": true,
        "noUnusedLocals": true,
        "noImplicitAny": true,
        "alwaysStrict": true,
        "noFallthroughCasesInSwitch": true,
        "noImplicitThis": true,
        "noUnusedParameters": true
    },
    "include": ["penrose"],
    "exclude": ["node_modules"]
}
prisma shard
#

Ahhhhh

remote oyster
prisma shard
#

Kinda janky to me, so TS is normally not used in addons scripts folder ? Then why i seen sharing repostitry addons inside it has TS...

#

so TS is not a thing to put in addon file

#

It is only for typings

#

I see

remote oyster
#

Keep in mind that your skeletal environment does not have to fall in line with a skeletal behavior pack. What matters is that when you compile and build it that your finished product is.

Yes, you won't put TS scripts in a behavior pack as the engine only supports JS. TS is purely for static typing to help write robust code, quickly and more effectively, while minimizing bugs and errors before even debugging in a world.

prisma shard
#

thank you very much

remote oyster
#

It also can prove to be extremely useful by establishing rules and guidelines in the tsconfig file to ensure consistency within your practices and with others who wish to contribute. Good for preventing what I call spaghetti code lol.

remote oyster
# slender aurora Do you know where I can finde a tutorial on how to set it up?😅

Yes, Mojang has a repo with one set up as an example. You will just need to familiarize yourself with it. There are also many other open source projects on GitHub with similar setups that you can review as inspiration to begin and start your journey.

The following link will walk you through the process of learning how it all works using the basic fundamental knowledge to get started.

https://learn.microsoft.com/en-us/samples/microsoft/minecraft-scripting-samples/minecraft-typescript-starter-project/

A basic Hello World example of developing Minecraft scripts using TypeScript and a build process.

slender aurora
# remote oyster Yes, Mojang has a repo with one set up as an example. You will just need to fami...

Thanks so much for your help, everything I did was working perfektly and I can see myself getting into scripting. But I got one last question: I followed the tutorial till the end, where I set the npm via windows terminal to the watch mode with:
npm run local deploy -- --watch

Now I want to know, how I can get npm to "unwatch"
Or is it doing nothing, if I close the windows terminal or what will happen? 😅

slender aurora
#

Well to anyone wondering: I just closed the terminal and npm stoped to watch my script. So as far as I can see it does also not operate in the background anymore. If I am wrong pls let me know 😂

nocturne berry
#

How to detect if a monster died from a specific item?

frozen vine
#

What is the website to check script component fields based on API version?

distant tulip
#

Jaylys as example

frozen vine
lyric kestrel
#

Is it possible to get the owner of the world? Or everyone that is OP on a world?

distant tulip
lyric kestrel
#

ah I see

#

I might put my function as beta needed then

lyric kestrel
remote oyster
#

It will work on BDS (after making a small change in server.properties), but Realms, not so much.

frozen vine
remote oyster
#

Yes, its been around for a while.

dusky flicker
remote oyster
#

Never heard of bun. I believe tsconfig is pretty simple and straightforward.

distant tulip
patent tapir
#

This script seems to work (the chat messages to get changed) but even if I have a rank and it goes through it shows up as undefined next to my name

#
world.beforeEvents.chatSend.subscribe((data) => {
    const sender = data.sender
    const message = data.message
    const ranks = sender.getTags().filter(predicate => predicate.startsWith("rank:") === true)/*?.forEach(function (item, index, array) {
        array[index] = item.substring(4)
    })*/
    const trimmedRanks = ranks === undefined ? undefined : ranks.forEach(function (item, index, array) {
        array[index] = item.substring(5)
    })
    system.run(() => {
        world.sendMessage(`§r${sender.name}§r${/*trimmedRanks === undefined ? "" :*/ ` - ${trimmedRanks?.join(" - ")}`}§r: ${message.trim()}`)
        world.sendMessage(`${ranks}`)
    })
    data.cancel = true
})```
#

the commented out parts are things I've already tried

sterile epoch
#

bcuz for each doesn't return anything it just modifies the original array

#

so the trimmedRanks will be undefined regardless of what u do

#

it's better to use .map

patent tapir
#

well ok

#

why doesnt this work then

#
world.beforeEvents.chatSend.subscribe((data) => {
    const sender = data.sender
    const message = data.message
    var ranks = sender.getTags().filter(predicate => predicate.startsWith("rank:") === true)/*?.forEach(function (item, index, array) {
        array[index] = item.substring(5)
    })*/
    ranks = ranks?.forEach(function (value, index, array) {
        array[index] = value.substring(5)
    })
    system.run(() => {
        world.sendMessage(`§r${sender.name}§r${/*trimmedRanks === undefined ? "" :*/ ` - ${ranks?.join(" - ")}`}§r: ${message.trim()}`)
        world.sendMessage(`${ranks}`)
    })
    data.cancel = true
})```
gaunt salmonBOT
patent tapir
#

HOW do I NOT make it void??

#

OH

#

I FIGURED IT OUT

#

you don't assign the variable using forEach :l

#

you use forEach literally as a function that assigns itself

#

ok

#

that makes sense

leaden elbow
#

how to get a players inventory like return an array of the items in their inventory? it is used with getComponent right? but how

edgy elm
#

Hi here. How can i have a translation for my addons? like a different language for my scripts

rapid sail
#

so i got npm how do i get minecraft math into my project?

cold grove
rapid sail
#

op

cold grove
frozen vine
#

has the onPlayerDestroy "component" been renamed? it is used in custom components, but I am using api 2.0.0 and it does not work

cold grove
#

theres no method that returns an array

viral wigeon
#

wha

#

can someone help me with a math problem in my post pls 🙏

#

#1365849295345025025

rapid sail
cold grove
rapid sail
#

it says dist? does that mean i have to put in the dist of the pack?

rapid sail
#

do i need to add it to the manifest too?

thorn flicker
#

just download the minified version and put the file in your scripts folder.

#

and then import it into the file you'll be using it in.

rapid sail
#

k

leaden elbow
#

i have vanilla items in my inv btw

leaden elbow
#

so if i rename the item, the nametag will work?

#

how about on custom items if typeid doesnt match its name

cold grove
#

world.sendMessage({ translate: item.localizationKey })

leaden elbow
#

okay thanks

leaden elbow
#

and also one last thing is <ItemStack>.durability and <ItemStack>.isEnchanted a thing?

chrome gyro
#

Is there a way to unpack a Lore into it's numbers... doesn't seem to be working in my code, it keeps thinking it's a string.

valid ice
#

wdym by that?

#

Can you use parseInt()?

chrome gyro
dusky flicker
#

do you guys know what's a good data structure implementing caching? im in need to implement cache and i dont know what can be best. Yes i thought in hashmap but i want to know if there is another option than hashmaps

frozen vine
# thorn flicker not to my knowledge.

that's weird, i'm getting this log error.


[Scripting][warning]-Block custom component 'mc:on_player_destroy' was registered without any event listeners, should the component be removed?
#

This error only occurred in the components where I use on_player_destroy, the others worked normally.

frozen vine
thorn flicker
#

the event seems setup correctly, but the readability here...

sweet seal
#

How to update a pack without changing manifest? So when I update a pack on my realm all dynamic properties wont reset.

frozen vine
thorn flicker
#

but that's not your issue right now

frozen vine
thorn flicker
#

it could be.

remote oyster
viral wigeon
#

does someone know about vector math? i need some help with this
#1365849295345025025

viral wigeon
#

🙏

random flint
#

Incorrect naming ig

round bone
broken dagger
#
import { world, system, DynamicPropertiesDefinition } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

// Registra as Dynamic Properties
world.afterEvents.worldInitialize.subscribe((eventData) => {
    const def = new DynamicPropertiesDefinition();
    def.defineNumber("max_health");
    def.defineNumber("ki_max_real");

    eventData.propertyRegistry.registerEntityTypeDynamicProperties(def, "minecraft:player");
});
fickle dagger
#

is there a reason why a scriptevent suddenly stops working?

#

I didn't change the script much but that caused the scriptevent to not run

thorn flicker
#

use entity.setDynamicProperty('whatever', 20)

thorn flicker
distant tulip
#

you have any for 3d placement?

prisma shard
#
export function QueryCardinal3(player) {
    const viewDirection = player.getViewDirection();
    const { x, y, z } = viewDirection;

    if (y >= 0.5 || y <= -0.5) {
        return 0; // up/down
    } else if (z >= 0.5 || z <= -0.5) {
        return 1; // north/south
    } else if (x >= 0.5 || x <= -0.5) {
        return 2; // east/west
    }
}```
#

@distant tulip

valid ice
# distant tulip you have any for 3d placement?

function cardinal_direction({ x: pitch, y: yaw }) {
    if (pitch > 60) return 0.0; //Down
    if (pitch < -60) return 1.0; //Up
    if (Math.abs(yaw) > 112.5) return 2.0; //North
    if (Math.abs(yaw) < 67.5) return 3.0; //South
    if (yaw < 157.5 && yaw > 22.5) return 4.0; //West
    if (yaw > -157.5 && yaw < -22.5) return 5.0; //East
    return 6.0; //Undefined
};```
plucky light
#

I am using the Mob Heads addon by 2-Tail Productions on a server I maintain and am constantly getting the below error.

[Scripting] TypeError: cannot read property 'hasTypeFamily' of undefined at <anonymous> (index.js:166)

The code it is getting generated from is below. Is this due to a conflicting pack or a change in required language?

    let damagingEntity = data.damagingEntity;
    let entity = data.hitEntity;
    if (entity != undefined && damagingEntity != undefined) {
        console.warn(entity.typeId + " output " + damagingEntity.typeId)
        let familyComponent = entity.getComponent("minecraft:type_family");```
wintry bane
#

Hold on, if add-on #1 has const add = 1; and add-on #2 has const add = 0;, which value will the variable have?

#

The add-on higher in the stack?

distant tulip
#

each file have it own environment, there is no conflict

#

you can even have const add = 0 in on file and const add = 1 in a diffrent file in the same addon

distant tulip
#

or the code is not complete

#

also, not sure you are allowed to share codes from mp addons

plucky light
# distant tulip also, not sure you are allowed to share codes from mp addons

Sorry was missing the last line which is the hasTypeFamily request.

    let damagingEntity = data.damagingEntity;
    let entity = data.hitEntity;
    if (entity != undefined && damagingEntity != undefined) {
        console.warn(entity.typeId + " output " + damagingEntity.typeId)
        let familyComponent = entity.getComponent("minecraft:type_family");
        if (familyComponent.hasTypeFamily(`${nameSpace}_head`)) {```

Also understood on MP addons but this developer offers the same version from on their website.
distant tulip
#

the error shouldn't appear anyway

#

i assume his entity don't have a family component, if so you should report the problem to foxy

prisma shard
#

very useless

#

lol

#

why the entityHitEntity event would fire if the entity doesn't even exists, xD

distant tulip
#

what happen if the entity died?

warm mason
thorn flicker
#

so the if statement here is for the some.

warm mason
#

You will always get an entity object. If you want to protect yourself from errors, you can check isValid

distant tulip
#

yeah, i guess bedrock do delay the removal

#

even the xp is delayed

thorn flicker
#

you could just use optional chaining

plucky light
random flint
#

It'll still technically give Entity class, but not valid for modification 😔

distant tulip
#

well, that is still not undefined

warm mason
#

At the same time, other functions of your addon or another one can remove the entity. So the isValid check is very justified, but not != undefined

lyric kestrel
#

How do I send a chat message to a select few people?

warm mason
lyric kestrel
#

Not like that, that sends it to all

#

But I figured out a way anyways

remote oyster
lyric kestrel
remote oyster
#

No worries. Just wanted to make sure 😀

lyric kestrel
#
let allPlayers = world.getAllPlayers()
allPlayers.forEach(player => {})```
I did that instead xD
#

Basically the same thing

remote oyster
#

Yea basically haha. An array of player objects.

lyric kestrel
#

ye

#

I was doing a function for the Script-API-Utilities that Finnafinest started

remote oyster
#

Be careful with using isOp(). It's effective in a BDS environment if server.properties includes the proper attribute, but when it comes to Realms, it is not reliable until they do something about the different layers of permissions and how they are handled internally.

remote oyster
#

Ok, as long as you know. 😅

full idol
#

Uhhhh how do I prevent this? The script is very laggy, just mapping the world for some data, not a public addon

prisma shard
prisma shard
full idol
#

Is there a workaround for these errors?

unique dragon
remote oyster
#

This will offset their execution so that the read permission is elevated to read/write.

somber cedar
marsh pebble
#

how do i make a item open a scriptevent

gilded shadow
#

"open"

distant tulip
#

your comment didn't help, lol

distant tulip
marsh pebble
#
console.warn('main.js loaded')

import { world, system } from "@minecraft/server"

world.beforeEvents.itemUse.subscribe(data => {
    let player = data.source
    if (data.itemStack.typeId == "minecraft:compass") {
        system.run()("scriptevent skygen:player_quest_menu")
    }
})```
#

@distant tulip

#

what did i do wrong

distant tulip
#

just trigger the code the script event is triggering directly

random flint
marsh pebble
#

so

#

is this right?

distant tulip
#

system.sendScriptEvent
if you really need to send it

marsh pebble
#

i dont understand

#

@random flint

#

i kinda need this fixed

#

like rn

#

AND ITS NOT WORKING

#
console.warn('main.js loaded')

import { world, system } from "@minecraft/server"

world.beforeEvents.itemUse.subscribe(data => {
    let player = data.source
    if (data.itemStack.typeId == "minecraft:compass") {
        system.run()("scriptevent skygen:player_quest_menu")
    }
})```
distant tulip
warm mason
gaunt salmonBOT
twilit tartan
#

I have a structure loading system, it divides the build into 4 sections (alligator1, alligator2, alligator3, alligator4) because the total size exceeds the 64x64 blocks allowed per structure. However, this causes problems when trying to rotate them, since each part rotates independently and becomes misaligned, and if a chunk is not previously loaded, some pieces are not placed correctly or bug and do not generate, there is no efficient way to save structures larger than 64x64 and make their rotation work. This causes the final structure to be incomplete, poorly synchronized or with visual errors, especially in large worlds or servers with latency.

full idol
#

Is there a way to get blocks out of player simulation distance? Say I want to know what is currently at 1,000,000 1,000,000

granite cape
ruby haven
#

When spawning particles using script api will it render even if I'm not seeing it in my screen?

Cause in my animation in rp it only renders when I'm seeing the entity in my screen playing it

remote oyster
# granite cape bruh

Are you counting the broken blocks because that math ain't mathing if you are lol.

sterile epoch
#

lol

granite cape
#

want code?

warped blaze
full idol
#

Is there an easy way to get a ton of JSON data out of a script that processed a ton of data when in single player?

lyric tiger
#

Yo how can I add tags like "Minecraft:is_axe" to an item via scripting?

thorn flicker
lyric kestrel
thorn flicker
random flint
#

Item Component? No.
Custom API Component? Still No.
Item Events? Bruh

copper egret
#

I can't wait for it to be implemented

#

it's been 2 years since it's suggested

warm mason
#

I asked about this at Creator Camp

copper egret
#

yet dev ignored it since it's probably not very specific or probably they couldn't do it for a certain purpose.

warm mason
little hull
#

is it possible to make a particle being rendered at all times or the sound through scripts?

little hull
full idol
#

How can I copy some JSON data out of the game?

warm mason
full idol
#

What about putting it in a pre-filled command block or book?

random flint
# full idol What about putting it in a pre-filled command block or book?
  1. Both Command Block and Book & Quill text content currently can't be read or modified by Script-API.
  2. Item name, entity name, Item Lore, and text sign, Server Forms are some of the things you can assign text to with Script-API.
  • If it's specifically for copying a text, you can go with Signs (The player can edit it) or better... modalForm.textField(), which is basically a text box.
    • (However, by default, they do have a character limit.)
  1. Is simply using the console. You log the stringified JSON to the console and let the user copy it through the content log GUI. Which doesn't have a character limit.
  • This would be limited to the server console or the world's host.
full idol
nova flame
#

anyone have any examples of chat commands? like "!spawn"

sterile epoch
# nova flame anyone have any examples of chat commands? like "!spawn"
const PREFIX = "!";

world.beforeEvents.chatSend.subscribe((e) => {
  const { sender: player, message } = e;
  if (!message.startsWith(PREFIX)) return;
  const msg = message.toLowerCase();
  const args = msg.split(" ");
  const cmd = args[0].substring(1);
  system.run(() => runCommand(player, cmd, args));
})

function runCommand(player, command, args) {
  if (command == "spawn") {
    player.teleport({ x: 0, y: 0, z: 0 });
    player.sendMessage("Warped to spawn!");
  }
}
random flint
#

I often forgot that Entity.kill() is a thing.
I always use .remove() to instantly delete an entity out of existence.

sterile epoch
#

I am just curious

random flint
#

Item Entity? yea.
ItemStack? Error: Not a function.

sterile epoch
#

interesting

#

does it do the death particles/sfx?

random flint
#

I think it plays. It's just like /kill but native method

#

But for some entities, it might not... like end crystal instantaneously just explode (I'm not sure lol)

sterile epoch
#

lmao

#

that gives me an idea to summon tons of them on a player and kill them for a tactical nuke

#

and they also launch you into the stratosphere so that'll be funny af

random flint
#

<Player> exploded by 200x End Crystal

sterile epoch
#

lmfao I beg it works

#

im gonna test it

sterile epoch
#

it didn't work... sad

full idol
#

I saw the chunk loader script in scripting resources, but I'm having trouble getting it to work. I need to scan every 8 blocks of the overworld to make a 200x200 map at 1:8 scale. My first attempt teleported the player to various points with 12 sim distance, but that was slow. I wanted to switch to armor stands, teleport them to each point that needs scanning, find the top block, then move on, but all the blocks are returning undefined 1 tick after the teleport

lyric kestrel
#

Is it possible to use the Container class to make a new Container

distant tulip
#

no

lyric kestrel
#

So it's still only possible with JSON UI?

digital trout
#

Is there a way to use translated messages in scripts?

ex: player.sendMessage("Rocket boosting is disabled!");

And have it auto translate to spanish, etc.

Or use the lang files

granite cape
#

wanna make mine area use this

shy leaf
#

@wary edge hey uh do you have the docs that shows diff in scripting API

#

i cant find it

shy leaf
#

thanks

dim tusk
prisma shard
#

hi

prisma shard
#

Giving 128 jump boost makes the player unable to jump?

#

what the fuk is this i've never seen this

#

Does this work

#

Giving 128 jump boost makes the player unable to jump?

deep quiver
warm mason
#

It doesn't work

prisma shard
#

who made this 😂

warm mason
#

Definitely AI

#

Although it seems to me that AI ​​doesn't even know how to use classes

prisma shard
#

ngl this is getting funnier looking at it

warm mason
# prisma shard

Let me guess, the class is called something like PlayerUtils

prisma shard
#

you guessed it

prisma shard
#

💀

#

like giving that much jump boost, so the player would not want to jump

#

unless they woud go to sky lmao

warm mason
abstract girder
#

how to make simulated player use items

random flint
#

Same goes with levitation. It makes you fall faster
-# (Java too)

prisma shard
#

i see

plucky light
#

What is wrong with this code?


WorldAPI.afterEvents.scriptEventReceive.subscribe((event) => {```

I get the error

```[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined    at <anonymous> (XXXX/events/XXXX.js:4)


[Scripting][error]-Plugin [XXX - 1.0.0] - [main.js] ran with error: [TypeError: cannot read property 
'subscribe' of undefined    at <anonymous> (XXXX/events/XXXX.js:4)
]```
prisma shard
#

what is your script api version

plucky light
#

I have tried both 1.18.0 and 2.0.0-beta and get the same error

#

sorry that is the "@minecraft/server" version

prisma shard
#

check if your running the exact script

#

Do a console.warn("hi")

#

does it show?

plucky light
#

yep

prisma shard
prisma shard
#

hm oh yes

plucky light
#

system worked. Thanks alot!

prisma shard
#

yeah i forget everything lol i shoul've checked it first

nova flame
#

anyone have any idea on how to make a actionform ui appear when u close chat

#

like i have a chat command set up that opens it

#

but if u just dont close chat within 3 seconds it just dont open

abstract cave
#

Did anything change regarding itemUseOn?

distant tulip
#

use playerInteractWithBlock

#

there is event.itemStack in it now

abstract cave
#

i havent been here for a month+

prisma shard
#

it has itemStack property as minato said

sage sparrow
#

hi there, is it possible to change a entity target using API?

distant tulip
#

nope

lyric kestrel
nova flame
#

can someone help me fix somethign quick

#

it looks simple but ive just started coding and i have no idea what ive done wrong

solar dagger
#

I'm trying to make an item that needs to be charged in order to increase the damage of the projectile (btw it spawns 3 projectiles). Would it be good practice to pass the charge duration over to the spawned projectile and scale the damage from there? Also I want to give it a visual representation of its increased damage so maybe slowly increase the size of the projectile? I kinda need help brainstorming this one

nova flame
prisma shard
austere flax
#

why do mobs with health boost (e.g. i have a mob with 400 health) reset back to its base health when spawned using a structure block or world reload?

#

its at 400/400hp but on reload or when i spawn it usin a structure block it resets to 20/400

#

never had this issue before

prisma shard
#

uhhhhhhhhh

#

wait what

#

i have two functions to applyEnchantment

#

but

#

one uses .getComponent('minecraft:enchantments');

#

and another uses .getComponent("enchantable");

#

what

#

does both component have addEnchantment() method

prisma shard
wheat condor
#

Is it only my thought or this thread is dying?

wary edge
#

What?

wheat condor
#

I mean I’ve always seen like 20 messages per second

wary edge
#

People have such a weird obsession with things "dying". 💀 also doesnt help that the 20 messages per second are usually off topic.

remote oyster
#

Out of the many different servers I'm in that speaks about the Script API, this one is by far the most active. I would say it's doing well.

#

👀

wheat condor
#

Is there also the inventory change event?

wary edge
#

Yes.

remote oyster
wheat condor
#

😭

#

Before event would be cool.. but like I image what cancelling the pickup of an item how would look like

prisma shard
#
    /**
     * 
     * @param {ItemStack} itemStack 
     * @param {Object} enchantments
     */
    static addEnchantments(itemStack, enchantments) {
        const enchantableComp = itemStack.getComponent("minecraft:enchantable");

        if (!enchantableComp.canAddEnchantment) {
            throw new Error("The item is not enchantable!");
        }
        if (!enchantableComp) return;

        Object.entries(enchantments).forEach(([id, level]) => {
            enchantableComp.addEnchantment({ type: new EnchantmentType(id), level: level });

        });
        //return itemStack
    }```
Umm guys what do i do here?
Do i remove the `return itemStack` or remove it? or `setEquipment/setItem` to set the item again? (i dont have equipment / container component here )
wheat condor
#

Depend on how you want it to work

remote oyster
#

That's a tough one to answer but let's follow up that question and ask if you have other functions which modify a ItemStack such as Lore? If yes, then I would say return the ItemStack so you can get all the changes at once, then set the item.

wheat condor
#

But i think that returning the ItemStack is enough becouse you let the user to do what he want

prisma shard
#

What i dooo

wheat condor
#

Bro

#

You re doing that script api function pack?

#

The ItemStack class has the enchantable component that has the SetEnchantment method that just edits the ItemStack (remember that ItemStack is an instance and not a simple object)

wheat condor
# prisma shard What i dooo

As I said to you 2 days ago use
ItemStack.prototype.addEnchantments
So you just run the function at the ItemStack instance without having to get a new ItemStack from the function

barren eagle
#

We need 2 more messages here to reach 99999 messages

#

I m gonna make it reach 99 999

Done

cyan basin
#

It's hit 99999 mutliple times now

#

It just resets a certain amount back since discord can't seem to display over said number

cinder shadow
#

that moment when you spend a long time making localization strings and forget that lore doesn't support it

cinder shadow
#

I mean I still needed it I guess

#

Just sucks that there's no way to just turn the localization key into a string

cinder shadow
#

welp that was easy, just chucked the localization keys into chatGPT and had it transfer all the data into the correct spots in my objects

safe stream
#

dude we need a distance() method, i am so tired of calculating the distance manually

safe stream
cinder shadow
#

I don't think so

safe stream
#

no

#

I don't want to make a function for every project, a distance method is just too convenient

cinder shadow
#

you can't just make a file for functions you commonly use

#

and import that into each project?

thorn flicker
#

you are really complaining about making a function

safe stream
sharp elbow
#

It could be a nice thing to have in vector-utilities

thorn flicker
thorn flicker
lyric kestrel
abstract cave
#

was runCommandAsync removed

sterile epoch
#

in 2.0.0-beta yes

#

quick question: if you had a player object and checked .isValid would it be false of the player is no longer online

shy leaf
sterile epoch
#

as in, the player object is stored

shy leaf
#

where is it stored?

sterile epoch
#

in a class

shy leaf
#

hmmmmm

sterile epoch
#

is that sarcasm

shy leaf
#

no i genuinely dont really know

sterile epoch
#

oh ok sorr

#

y

abstract cave
#

'world.beforeEvents.worldInitialize'
was this removed or replaced

shy leaf
#

ive never had an instance where .isValid returns false since the object wouldnt just exist before i can get the boolean

#

so i just use it as a failsafe

player?.isValid
sterile epoch
#

i just don't have an alt to test it tbh

sterile epoch
shy leaf
#

cant give a clear answer, sorry

sterile epoch
#

It's all good

#

question, would you mind joining my world for a second so i can test it?

shy leaf
#

im on a lecture rn so i cant, sorry

sterile epoch
#

all good

remote oyster
sterile epoch
#

isValid becomes false once the player leaves

#

let's goooo

#

easy

remote oyster
#

It's false because it doesn't exist.

sterile epoch
#

it does exist

#

the player object is stored

remote oyster
#

How are you storing it.

#

If you are copying the object then the copied object doesn't reference the original object.

sterile epoch
#

the Boolean being isValid

sterile epoch
#

but anyways, it works and I'm happy

remote oyster
#

I don't think you understand what it's doing though.

sterile epoch
#

???

remote oyster
#

But if it's getting you the results you seek then so be it

sterile epoch
#

from my understanding the player leaves so the player object is no longer valid and is false

#

lmao bro gave up

remote oyster
# sterile epoch explain what I'm misunderstanding please

When you copy the object into a new variable, you're creating an entirely new object. It's no longer linked to the original. This means that any changes made to the original object by the Scripting Engine won’t affect the new object, because the new object is now independent.

Think of it like this: imagine you have a bedroom, and you make a copy of it, so now you have two bedrooms. If you dismantle the bed in the original bedroom, the bed in the copied bedroom stays intact. This is because the two bedrooms aren’t connected, they are completely separate, with no reference to one another.

remote oyster
sterile epoch
#

damn the typing stopped so i thought you gave up

remote oyster
#

That was your ego speaking out loud.

sterile epoch
#

no? i just thought you gave up typing

sterile epoch
remote oyster
sterile epoch
#

if the object didn't exist wouldn't it throw an error

remote oyster
#

Go break the object down. It may help you get a visual on what I am talking about. Do a comparison of the objects.

#

@sterile epoch , test and see if it's shallow copying or deep copying the object.

sterile epoch
#

idk

#

I'm just confused on what you mean, isn't it storing a reference to the players object?

#

i don't see how what you're saying makes sense if isValid changes after the player leaves

little hull
#

how do i check the owner of a tamed entity?

prisma shard
#

Oh i didnt read the full messege history

#

You were already replied lol

prisma shard
#

how can i detect if a ItemStack has no enchantment

#

the hasEnchantment() requires an string
such as hasEnchantment("unbreaking")

#

but I want to detect if it has any enchantment or not

shy leaf
#

make it to check if .getEnchantments() returns an empty array

prisma shard
#

how

#

okay a bit

#

hmmmmmmm

#
const enchants = enchantableComponent.getEnchantments();
if (enchants.length === 0) {
  // no encchantment
}```
#

like that?

#

@shy leaf

#

legnth right

shy leaf
#

maybe

prisma shard
#

i hope so lets try it

prisma shard
#

Is there any way to force player into sneak mode

woven loom
#

block movement if they arnt sneaking

#

👀

prisma shard
#

huh

somber cedar
stuck ibex
#

Yeah isSneaking isn't readonly

distant tulip
prisma shard
#

hwhwoa-dhadas-das

prisma shard
#

My whole life was a lie. 😭

#

lmao

distant tulip
#

lol

prisma shard
#

is isJumping also not readonly

#

would doing isJumping = false
make not allow to jump?

prisma shard
#
/**
 * Forces the player into sneak mode.
 */
Player.prototype.forceSneak = function () {
    this.isSneaking = true;
};```
It doesn't show the typings
#

when i type player.

#

no typeings for forceSneak prototype

distant tulip
#

eh, why do you need a prototype for one line of code

prisma shard
#

lol idk

#

but tell tho

distant tulip
#

not sure

round bone
#

also, this is just a one line, so why you have to use a new function to force someone to sneak

prisma shard
#

meoew mew lol

#

ok ok ok idk

#

I will not do the prototype

#
/**
 * Run multiple commands at once.
 * 
 * @param  {...string} commands
 * 
 * @example
 * player.dimension.runCommands(`say Giving apple to player`, `give @s apple 1`, `say Done!`)
 * 
 */
Dimension.prototype.runCommands = function (...commands) {
    for (cmd of commands) {
        try {
            this.runCommand(cmd);
        } catch (e) {
            throw new Error(`Failed to run commands:`, e);
        }
    }
}
#

is this silly to do

#

:)

#

lol

prisma shard
round bone
#
/**
 * Run multiple commands at once.
 * @param {...string} commands
 * @example
 * player.dimension.runCommands(`say Giving apple to player`, `give @s apple 1`, `say Done!`)
 */
Dimension.prototype.runCommands = function (...commands) {
    for (command of commands) 
        this.runCommand(commands);
}
#

you're throwing an error anyway, so why catching it?

prisma shard
#

what?

#

throwing error anyways?

#

oh wait i see

#

lol it was silly i knew

shy leaf
#

because the sneaking persists for like, less than a tick

#

it prolly depends on client fps

prisma shard
#

uh

#

how about doing in runInterval

prisma shard
#

ok i se

shy leaf
#

the player would shake crazy

distant tulip
shy leaf
#

does the player have to sneak?

prisma shard
#

huh

shy leaf
#

like

#

is it a requirement or

prisma shard
#

no

#

not

shy leaf
#

whatcha trying

prisma shard
#

idk

#

making some utils

prisma shard
shy leaf
#

or you can check for player input

#

and make it work only if player is holding shift (sneak key)

distant tulip
#

what if we disabled the input permission for Sneak

shy leaf
prisma shard
#

wait i thought of this

#

how about doing this

distant tulip
#

native methods

shy leaf
#

there should be InputPermission method for Player

prisma shard
#

i mean yeah

#

i do know t has native mthods

#

but

#

what happen if we do this

wary fjord
#

If we remove animation will it remove from all server forms, even custom ones?

shy leaf
distant tulip
prisma shard
#

wtf wait its rainng
I

#

I FOROGR THE CLOTES

#

it was dryingh

shy leaf
#

back to the beginning

distant tulip
#

"lets inform BAO members before i go collect them"

prisma shard
#

back

prisma shard
shy leaf
#

no

prisma shard
#

hunger comoponent exist tho

shy leaf
#

we lack in attribute component for api

#

i get the health and movement part but what on earth is up with the rest of two

#

attribute component is just very undercooked rn but

#

i hope we can see more in the future

prisma shard
#

    /**
     * @param {Player} player
     * @returns {boolean} 
     */
    static isMoving(player) {
        const vel = player.getVelocity();
        if (vel.x !== 0 || vel.y !== 0 || vel.z !== 0) return true;
        else if (vel.x === 0 || vel.y === 0 || vel.z === 0) return false;
    }```
#

i made this thing

#

will it work

#

does it have any issues or it will work fine

#

Maybe or i can optimize it more?

shy leaf
#
const speed = Math.hypot(vel.x, vel.y, vel.z);
return speed > 0;
abstract girder
#

how to detect damage per second

plucky light
#

what is wrong with this code? It returns player was undefined

  const player = event.player;
  if (!player) {
    console.warn("[DEBUG] playerJoin triggered but player was undefined.");
    return;
  }```

using "@minecraft/server","version": "1.18.0"
prisma shard
remote oyster
#

Would be more efficient to use the player spawn event.

prisma shard
#

yeah

#
if (!event.initialSpawn) return;```
#

doing this will make it like playerJoin

remote oyster
#

Yea, the only con is you have an event being triggered more often versus the other. So its a matter of weighing the pros and cons. In this instance it's probably worth it.

prisma shard
# remote oyster Yea, the only con is you have an event being triggered more often versus the oth...
/**
 * Forces the player to look at a specific target position.
 * 
 * @param {Player} player
 * @param {Vector3} targetPos
 */
function lookAt(player, targetPos) {
    const head = player.getHeadLocation();
    const dx = targetPos.x - head.x;
    const dy = targetPos.y - head.y;
    const dz = targetPos.z - head.z;

    const distanceXZ = Math.sqrt(dx * dx + dz * dz);

    const yaw = Math.atan2(-dx, -dz) * (180 / Math.PI);
    const pitch = -Math.atan2(dy, distanceXZ) * (180 / Math.PI);

    player.teleport(player.location, {
        rotation: { x: pitch, y: yaw },
        facingLocation: {
            x: targetPos.x,
            //substracting from player's camera height (-1.62)
            y: targetPos.y - (player.getHeadLocation().y - player.location.y) - 0.1,
            z: targetPos.z
        }
    });
}```
Also, need some help
Can you tell me if the math is correct
#

I'm trying to make a function, that forces the player to look within the location

remote oyster
#

I would probably need to run it on a computer and verify the numbers but I'm at work.

prisma shard
#

No problem

remote oyster
#

Also, if anyone is in the OSS server, I got a question there.

#879773489601585244 message

#

Actually, I'll just open the question here.

fallow minnow
#

does anyone know how to actually fetch the open ai api through server-net?

plucky light
wheat condor
ivory bough
#

How to make it so that only 1 entity of the same family can exist at a time?

wheat condor
prisma shard
#

get all entities then do .filter(() => ) to exclude out the one entity getEntities({families: "monster"})[0]

#

then you can kill other entities

#

so the one entity will only exist

#

idk what i jsut said

#

someone correct me

#

i just threw words out of mind

wheat condor
#

Without checking every tick

prisma shard
#

though

#

i didnt tell him to check every tick

gaunt salmonBOT
round bone
#

🙏

round bone
#

no problem, just don't spam it here

honest spear
#

Hello BAO scripters whats is going on today?

honest spear
round bone
honest spear
#

yea

round bone
honest spear
#

nice

round bone
#

is 1.21.80 coming out today or in the next week?

honest spear
#

idk, but what feature are you look for the most?

#

i think there are inventory events for player right?

round bone
#

I want to see how slash commands will be working in a stable look

honest spear
#

i might be wrong tho§

#

ahhh

#

true

round bone
round bone
honest spear
#

i wish i had more time of free time for script api

round bone
#

😭

random flint
honest spear
round bone
#

just few commisions

round bone
honest spear
#

ahh i still think we are not getting whole execution information but i already said so for scriptEvent

#

target and execution location are two separeted things

#

same for dimension and more

#

its not always the target's one

round bone
#

at this moment, I think that using some proxy or mod-loader is a better options for slash commands

honest spear
#

yea, depends on your usecases

#

i would preffer vanilla if i could

remote oyster
#

I'll probably continue to create custom commands with help as a parameter to get information about the command.

round bone
honest spear
#

💀

round bone
remote oyster
#

Yea, I just parse commands. More control. The idea of having commands show up in the chat window seems fine, but I've never had issues with parsing commands. Been a thing since coding was born. It worked then, it's worked all these years, it will work in the future.

round bone
#

parsers sometimes might be a struggle

#

slash commands are fixing it in some way

honest spear
#

depends

remote oyster
#

I feel like it may present restrictions.

honest spear
#

but UI feedback is really in need

#

but parsing it self is not problem, TypeScript is parsing whole Typescript so parsing has almost no limits

remote oyster
#

Just your imagination

honest spear
#

i hate my imagination

remote oyster
#

Haha

honest spear
#

bc it produces 3 useless project per month

round bone
#

for fresh programmers it might be a bit

round bone
shell sigil
#

Is there a way to save an object or array to an entity so that the data is retained even after I exit the world
How I can put this to entity
Example
[1,2,3,4,5]

round bone
#

and I am a colorblind

#

and that's how I am making front-end for websites

honest spear
#

and JSON obejct

round bone
#
Entity.setDynamicProperty("some-key", JSON.stringify(yourArray))
shell sigil
#

It's working thanks

round bone
#

no problem mate

#

👌

honest spear
#

jk

#
Entity.prototype.setDynamicProperty("some-key", JSON.stringify(yourArray))
round bone
#

this is a prototype

#

yeah

#

I am too lazy to type prototype

random flint
round bone
#

also most of those people aren't even that deep-diving into JS

random flint
#

howwww

honest spear
#

the guys could get not a function error bro

#

poor guy

#

why did you do that to him

round bone
#

this guy is 2 steps ahead us all

#

that's why he did it!

honest spear
#

We have special event in scripting discord server

#

and you can check the questions that are based on JS knownledge

round bone
#

I prefer royalty and TypeScript

honest spear
#

all right, but that questions are really tuff

round bone
#

this is confusing sometimes

honest spear
#

yea i know this one

#

but i make something that counts on JS knowledge and not fun facts

round bone
random flint
round bone
#

😭

honest spear
#

not mean to be for production

#

but yea

random flint
#

Imma intercept the Function class prototype lol 🙏🏼
too bad my form was cleared after I left it unsent for 2 days

round bone
#

I am a type of guy who tries to keep everything organised

#

that's why I like everything strict, OOP and optimised as much as I can

honest spear
#

i hate OOP in JS

round bone
#

also

#

OOP in TypeScript is pretty good ngl

honest spear
#

functional is better for JS

#

OOP with typescript is not bad

#

but always depends on your cases

#

for scripts in general i prefer functional

round bone
#

I always try to put everything in classes

#

also grouping functions in a class with a private constructor as static methods is pretty good

honest spear
#

yea thats one of the things i do as well

#

static class only with private constructor is good

valid ice
#

The only OOP I know is when my world crashes and I go "OOPS"

round bone
#
import { MinecraftMessageMode } from "@prisma/client";
import { ConnectionManager } from "../../../globals/managers/ConnectionManager";

class MinecraftMessagesService {
    private constructor() {}

    public static async deleteAndGetMessagesMode(mode: MinecraftMessageMode) {
        return await ConnectionManager.getDatabaseConnection().minecraftMessages.deleteMany({
            where: {
                server: mode
            }
        })
    }

    public static async addMessageToMode(message: string, mode: MinecraftMessageMode): Promise<void> {
        await ConnectionManager.getDatabaseConnection().minecraftMessages.create({
            data: {
                content: message,
                server: mode
            }
        })
    }
}

export { MinecraftMessagesService }
#

that's some example from my code

honest spear
random flint
#

I put random BS on my main.js file and pray it works 🙏🏼

round bone
#

I don't like tab 2

honest spear
#

but yours is 5?

round bone
#

it's 4

honest spear
#

ohh

#

damn

#

why it looks so spacy

round bone
#

I don't know

distant tulip
#

i don't think i ever used classes in script api

honest spear
#

yea also script api is designed a bit differently

random flint
round bone
#

in my IDE it looks okay

honest spear
#

maybe its bc i don't like how long your lines are

round bone
#
import { MinecraftMessageMode } from "@prisma/client";
import { ConnectionManager } from "../../../globals/managers/ConnectionManager";

class MinecraftMessagesService {
  private constructor() { }

  public static async deleteAndGetMessagesMode(mode: MinecraftMessageMode) {
    return await ConnectionManager.getDatabaseConnection().minecraftMessages.deleteMany({
      where: {
        server: mode
      }
    })
  }

  public static async addMessageToMode(message: string, mode: MinecraftMessageMode): Promise<void> {
    await ConnectionManager.getDatabaseConnection().minecraftMessages.create({
      data: {
        content: message,
        server: mode
      }
    })
  }
}

export { MinecraftMessagesService }
honest spear
#

man this chaining is crazy

#

i wrap the code when there are more chained accessing

distant tulip
honest spear
#

but the code is not bad eather just sayin

round bone
#

the minecraftMessages is a Prisma model

round bone
honest spear
#

btw i have something similar

round bone
#

I have set 200 printWidth in Prettier

round bone
#

why both pairs in the same line?

honest spear
round bone
#

Prettier is customizable

#

and easy to use for newbies

honest spear
#

but its good

round bone
#

what is Prettier missing for you?

honest spear
#

i don't like it bc it thinks its smarter than me

#

inline functions has to be in one line whole and thats different from other lines

round bone
#

oh I understand

honest spear
#

there are more little things i want

round bone
#

I like using Prettier just to keep with the standards

distant tulip
#

i feel the same way, but i learned to live with it, lol
don't want anyone to see my weird formatting

round bone
#

also I can style in a easy way some code of my friends that is horribly organised in some cases

honest spear
#

anyway i just wrote Raknet implementation and i already hate that project

honest spear
#

i am glad i leveled up

#

i use to write JS with .d.ts

round bone
#

I'm in 10th grade right now, and I think that I am much higher than everyone from my class and even school

honest spear
#

so lot of ppl asked my if where is the TS source code

round bone
honest spear
round bone
#

writing d.ts from a scratch is a pain sometimes

honest spear
#

i used to do so and i was pretty ok, but you have to keep in mind when you change the function in JS

round bone
#

you have to change some code in 2 places

#

it's like the same problem with databases

#

you DON'T WANT to have to change something in 2 places if you're doing it for only 1 thing

honest spear
#

¯_(ツ)_/¯

#

yea tell me about it

#

TS is just simplier on all cases

#

but i use to write code that wasn't even possible with TS

#

like static inheritance and getter overriding and other things like that

round bone
#

it's possible with TS

honest spear
#

not properly

#

i mean for example static abstract functions

round bone
#

there's a small workaround

honest spear
#

yea

#

but bad

round bone
#

but not enough

honest spear
#

not forced to implement it

#

¯_(ツ)_/¯

round bone
#
class SomeClass {
    protected constructor() {}

    public static someAbstractMethod(): void {
        throw new Error()
    }
}
round bone
honest spear
#

well yea these little things i hate about TypeScript, i wish ts covered more JS style than trying to make a diff language

round bone
#

TS is a large superset of JS

honest spear
#

thats also reason why i want to create own TS compiler in the future

round bone
#

I'll stick with TypeScript for front-end absolutely

honest spear
#

yea

#

TS is goat

round bone
#

TypeScript is pretty good language

honest spear
#

yea

#

i write 80% of my code in TS

#

maybe more

round bone
#

I write most of my code in TS

honest spear
#

only few test scripts for local use are in JS

round bone
#

sometimes C/C++ in other projects

honest spear
#

i don't count there langs

round bone
#

but not a big fan of C langs

honest spear
#

C# is not bad tho

#

i like it more than Java

#

C++ is also noce, C is worse C++

remote oyster
remote oyster
#

Lol

remote oyster
honest spear
round bone
#

but I don't know about Kotlin tbh

honest spear
#

Kotlin is something that my brothe use

#

idk for what tho

#

maybe for mobile app development

round bone
round bone
#

then probably back-end services (mostly Spring)

remote oyster
wheat condor
#

||isnt this off topic?||

round bone
round bone
honest spear
round bone
#

I like Script API too

#

we're back in the topic!

honest spear
#

i like linux tho

wheat condor
#

who likes linux?!

round bone
#

Linux is pretty good, but I prefer Windows just for MC:BE

#

also Windows has a bit better look, even if Linux is much more customizable

honest spear
#

yea for games its better anyway and powershell is also not that bad

wheat condor
#

windows has a lot of great quality of life features

remote oyster
round bone
round bone
#

(worst joke of my life)

round bone
#

you are already my friend

remote oyster
round bone
#

wheat condor
#

java is good but very old

honest spear
#

i like how even reacted the ppl who just spectating here and read all the message we type here

round bone
#

they're moderating us

honest spear
#

💪

round bone
#

our messages are recorded and saved to the government

warm mason
honest spear
remote oyster
round bone
#

we should make a group that is spreading Python hate all accross this server

honest spear
#

Well C# was my first language my dad showed to me

remote oyster
wheat condor
#

i mean its basically javascript but variables are an headhache

wheat condor
round bone
#

I have been learning Python for 3 months in 2020

#

then started with some basic web-dev (HTML/CSS)

honest spear
# remote oyster Respect

After he showed me the C# i was sure i don't want to do that, so i left all that stuff for another 6 months but .bat files were not good enought so i have to learn real lang

round bone
#

then moved onto JS and React,js

#

and I don't really remember how it went then

#

wait, I have learned add-ons development before React

honest spear
#

i grow up on .bat files

#

bc dad showed them to me

round bone