#Script API General
1 messages · Page 77 of 1
1.21.80 which is preview.
Or could be your script is laggy
/**
* 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
Client problem or you're script is running heavy before spawning it.
👆 this i was talking abt
^
yeah thats pretty much what i got
just use function.
and btw, what's the purpose of adding vectorY twice and multiplying by 0.4?
i just changed my script version manifest to 2.0.0-beta, how do i fix this?
so do you not have some initial delay with that code?
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.");
}
}
});```
can someone plss help me
Hi
without using runtime identifiers?
huh
oof, thanks tho
worldLoadAfterEvent
you can't read the property if the world hasn't loaded yet
say what the problem/error is and what are you trying to do, don't just send the script like that and ask for help without any context
i see, thank you
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?
It is.
lol they removed iut.
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
https://github.com/cykna/otsuki-addon/tree/master/behavior_packs/Enchanted/src
to understand it better, here's the repo
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
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
1.18 should be a last version
Yeah I have it set to 1.18
what errors are you getting?
In vs code it says worldInitialize is deprecated
And in game subscribe is undefined
And so is registerCustomComponent
what typings are you using?
NPM versions
I think that the name has already changed for 1.18 release
Use worldLoad
Oh
Wdym?
What are your NPM package versions
sorry,
"@minecraft/server": "1.18.0",
"typescript": "^5.4.5"
i also can't find worldLoad anywherew
hmm, weird
its worldInitialize in 1.18.0
Not for me
For some reason
Well I don’t even see worldload so I dunno
How to make banner red?
const banner = new ItemStack("minecraft:banner", 1)
banner.lockMode = 'slot'
inventory.setItem(player.selectedSlotIndex, banner)
Heh, I guess you can't. Color must be stored in NBT somewhere.
Unless you can give data values with scripting?
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');
}
}
});```
does the checking of component is correct?
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
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
do commands actually run significantly slower than scripts?
depends
its kinda indistinguishable with our bare eyes but
in mass quantity, scripts are significantly faster
ah ok, thanks!
and its generally recommended to use native functions if possible
runCommand is a Plan B
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
i see, thanks
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?
i think you might have the versions shifted
server is supposed to be v2.0.0-beta
server-ui is supposed to be 1.3.0
it should be like dis:
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "2.0.0-beta"
},
{
"module_name": "@minecraft/server-ui",
"version": "1.3.0"
}
]
I think both server and server UI have to be beta
checking player if is op is a property or a method?
is there a way to make blocks in a certain area explosion-proof?
i think its a method? im unsure
yeah its a method
how to write values using js? Example: if player moves script writes value "moving": true in json file, when not then fald?
You can’t write files
Only bds
Can't save data to files
modalform body is not a thing anymore?
the closest thing you can do is:
- use a back-end server (Express will be probably the best choice for things like this)
- handle on back-end player's moving state
- send HTTP requests from Minecraft server
cons:
- you must use also a HTTP request to get from back-end server the state of moving back (on Minecraft server)
- you would have to host additional Node.js
.
Alright
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
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 😅
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.
Javascript is very similar to Java but it isn’t based on variable types meaning that you can assign everything as a const
Typescript is JavaScript but you have to declare types, they are basically the same language in a different version of it
actually
since You guys are talking about typescript, Can anyone clear my doubt?
I have a confusion about TS
So if I sript, I will just always make it a .ts file?
No, Minecraft accepts only js
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.
Typescript is made to add TYPE definitions to avoid type errors, like your npm package uses a .ts file to generate your type auto completions for visual studio
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?
is there a technique for damage and knockback cancelation?
JSON editing
I know that method but I couldn't do it dynamically like the filter and tag things
Ask in entities thread
No, it will need to be transpiled from .TS to .JS. You will need to set up your environment to basically compile/convert them to JavaScript. This typically implies having a script handle that process. Usually in a file called package.json.
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
Do you know where I can finde a tutorial on how to set it up?😅
search engine exist
Interfaces are just types of things that aren’t actually a class or a variable, like
Vector3 isn’t a class or a variable it’s just an interface used to give a name to the object
{x,y,z}
It’s done so if some function require a Vector3 you know it’s x y z
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
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.
And this?
dont know if you mind to get ping
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.
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"]
}
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
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"]
}
Ahhhhh
My package.json file is too big but here you go
https://github.com/Visual1mpact/Paradox_AntiCheat/blob/rewrite/package.json
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
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.
thank you very much
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.
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.
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? 😅
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 😂
How to detect if a monster died from a specific item?
What is the website to check script component fields based on API version?
Use unofficial ones
Jaylys as example
Thanks
Is it possible to get the owner of the world? Or everyone that is OP on a world?
Add a tag or dp to the first player to join
There isOp but it is beta and don't work on servers
How do I see if isOp is to be in the new 2.0.0-stable or if it'll just be in 2.1.0-beta
It's in 2.0.0-beta.
It will work on BDS (after making a small change in server.properties), but Realms, not so much.
2.0.0-beta in 1.21.70/1.21.80 and 2.0.0 in 1.21.90
Yes, its been around for a while.
thankfully i use bun to transpile ts, seriously i hate configuring tsconfig
Never heard of bun. I believe tsconfig is pretty simple and straightforward.
it is like npm but faster
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
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
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
})```
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36m<REPL0>.js[0m:[33m7[0m:[33m5[0m - [31merror[0m[30m TS2322: [0mType 'void' is not assignable to type 'string[]'.
[7m7[0m ranks = ranks?.forEach(function (value, index, array) {
[7m [0m [31m ~~~~~[0m
There are no errors from ESLint.
very helpful
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
how to get a players inventory like return an array of the items in their inventory? it is used with getComponent right? but how
Hi here. How can i have a translation for my addons? like a different language for my scripts
so i got npm how do i get minecraft math into my project?
its not an module of the api
op
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
up
iterate for every slot and call Container#getItem() for each one
theres no method that returns an array
wha
can someone help me with a math problem in my post pls 🙏
#1365849295345025025
where do i put it?
not to my knowledge.
its specified at the side of the "download" button
it says dist? does that mean i have to put in the dist of the pack?
scripts folder
do i need to add it to the manifest too?
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.
k
managed to make it work, now when i getItem() then item.nameTag returns undefined, and tried item.name too its also undefined
i have vanilla items in my inv btw
typeId
so if i rename the item, the nametag will work?
how about on custom items if typeid doesnt match its name
In experimental version you can access ItemStack#localizationKey, to get the translation in a RawText
world.sendMessage({ translate: item.localizationKey })
okay thanks
is that in 1.21.70?
and also one last thing is <ItemStack>.durability and <ItemStack>.isEnchanted a thing?
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.
Perfect, that's exactly what I was looking for, thank you!
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
up
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.
show your code.
the event seems setup correctly, but the readability here...
How to update a pack without changing manifest? So when I update a pack on my realm all dynamic properties wont reset.
What does this mean?
the way the code is written.
but that's not your issue right now
so possibly it's a game bug?
it could be.
Only update header.version of the pack in the manifest. Don't change its UUID in header.uuid.
does someone know about vector math? i need some help with this
#1365849295345025025
🙏
onPlayerDestroy —> onPlayerBreak
Incorrect naming ig
name has changed in the last update
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");
});
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
they removed that.
use entity.setDynamicProperty('whatever', 20)
im just remembering that
you have any for 3d placement?
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
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
};```
thanks
oops lol
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");```
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?
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
the error is not related to the code you sent
or the code is not complete
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.
familyComponent?.hasTypeFamily(`${nameSpace}_head`)
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
useless
very useless
lol
why the entityHitEntity event would fire if the entity doesn't even exists, xD
what happen if the entity died?
It will still be valid for some time.
so the if statement here is for the some.
You will always get an entity object. If you want to protect yourself from errors, you can check isValid
you could just use optional chaining
It happens periodically and not necessarily when I am hitting something so I wasn’t sure if it’s related to a block update in scripting or similar as the first time it happened I thought it was falling gravel.
either way I’ll try your code as an update. Thanks
Except for some entities that don't have death animation.
- Armor Stand
- End crystal
- Most inanimate entity
It'll still technically give Entity class, but not valid for modification 😔
well, that is still not undefined
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
How do I send a chat message to a select few people?
const players = [] // Array of players
players.forEach(p => p.sendMessage('Hii'))
It only sends to whomever you populate in the array.
oop, just realised, my apologies 😅
No worries. Just wanted to make sure 😀
let allPlayers = world.getAllPlayers()
allPlayers.forEach(player => {})```
I did that instead xD
Basically the same thing
Yea basically haha. An array of player objects.
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.
Ye ik
Ok, as long as you know. 😅
Uhhhh how do I prevent this? The script is very laggy, just mapping the world for some data, not a public addon
was i mentioned lol, bro summoned me out of nowhere
const players = world.getPlayers({ name: "Steve" })
players.forEach(p => p.sendMessage('Hii'))
use filter in getPlayers()
Is there a workaround for these errors?
#1067535608660107284 message
yes
It appears you are executing them in beforeEvent. If so, you will need to wrap those in a function and call that function with system.run().
This will offset their execution so that the read permission is elevated to read/write.
https://jaylydev.github.io/scriptapi-docs/features/script-privileges.html#read-only-mode is this right
Yes
how do i make a item open a scriptevent
"open"
your comment didn't help, lol
wdym by 'open'?
trigger a scriptevent? if so why would you need that
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
why do you need that
just trigger the code the script event is triggering directly
- use
runCommand - privilage error, use
system.run() - why? Cus
runCommandAsyncis getting removed in Script V2 - Just do what Minato said
system.sendScriptEvent
if you really need to send it
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")
}
})```
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.sendScriptEvent("skygen:player_quest_menu", "")
}
})```
import { world, system } from "@minecraft/server"
world.beforeEvents.itemUse.subscribe(data => {
let player = data.source
if (data.itemStack.typeId == "minecraft:compass") {
system.sendScriptEvent("skygen:player_quest_menu", "")
}
})
console.warn('main.js loaded')
No errors in [code](#1067535608660107284 message)
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.
Thanks!
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
Wow thanks!
bruh
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
Are you counting the broken blocks because that math ain't mathing if you are lol.
lol
fixed
yeah 🥺
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?
Yo how can I add tags like "Minecraft:is_axe" to an item via scripting?
you cant add item tags in scripting
What about with item components?
no.
Item Component? No.
Custom API Component? Still No.
Item Events? Bruh
guys upvote and share your ideas about damage/knockback event cancelation in official minecraft feedback
https://discord.com/channels/1138536747932864532/1161696320482988182
I can't wait for it to be implemented
it's been 2 years since it's suggested
I asked about this at Creator Camp
yet dev ignored it since it's probably not very specific or probably they couldn't do it for a certain purpose.
They replied that it was a "complex system" and we were afraid of breaking it if we added it, but we see that you want it.
I thought so
is it possible to make a particle being rendered at all times or the sound through scripts?
or render the entity even when im not seeing it is that possible?
How can I copy some JSON data out of the game?
you can't
What about putting it in a pre-filled command block or book?
- Both Command Block and Book & Quill text content currently can't be read or modified by Script-API.
- 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.)
- 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.
Thanks! Yeah I need a ton of data, exporting a map of the world. I'll use console.log
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!");
}
}
I often forgot that Entity.kill() is a thing.
I always use .remove() to instantly delete an entity out of existence.
does .kill work on items
I am just curious
Item Entity? yea.
ItemStack? Error: Not a function.
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)
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
<Player> exploded by 200x End Crystal
it didn't work... 
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
Is it possible to use the Container class to make a new Container
no
So it's still only possible with JSON UI?
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
wanna make mine area use this
use rawMessage
thanks
👀
this is great
BlockVolume and runJob()...
hi
RawMessage interface
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?
Probably the jump power of the player integer overflows or similar
I thought it as nonsense too
who made this 😂
Let me guess, the class is called something like PlayerUtils
lmao lmao
you guessed it
i think its like giving player a fear of not jummping
💀
like giving that much jump boost, so the player would not want to jump
unless they woud go to sky lmao
Can you imagine the faces of people with autojump turned on?
how to make simulated player use items
That only works in Java
Same goes with levitation. It makes you fall faster
-# (Java too)
i see
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)
]```
what is your script api version
I have tried both 1.18.0 and 2.0.0-beta and get the same error
sorry that is the "@minecraft/server" version
yep
also, have you closed the event brackets
use system instead world
hm oh yes
system worked. Thanks alot!
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
Did anything change regarding itemUseOn?
removed
use playerInteractWithBlock
there is event.itemStack in it now
yea itemUseOn was removed.
Either use playerInteractWithBlock or playerInteractWithEntity if thats a entity
it has itemStack property as minato said
hi there, is it possible to change a entity target using API?
nope
Can't find property of 'subscribe' of undefined means that the property you're trying to subscribe to doesn't exist
can someone help me fix somethign quick
it looks simple but ive just started coding and i have no idea what ive done wrong
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
u should make it spawn one projectile at minimum charge, 2 at half and 3 at full charge
That might look better tbh
Just tell the problem
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
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
oh i see the docs enhantable component is right
Is it only my thought or this thread is dying?
What?
I mean I’ve always seen like 20 messages per second

People have such a weird obsession with things "dying". 💀 also doesnt help that the 20 messages per second are usually off topic.
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.
👀
Is there also the inventory change event?
Yes.
Correct me if I'm wrong but I think it's only afterEvent.
😭
Before event would be cool.. but like I image what cancelling the pickup of an item how would look like
/**
*
* @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 )
Depend on how you want it to work
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.
But i think that returning the ItemStack is enough becouse you let the user to do what he want
I don't want to set the item again outside the function. But to do that I have to do player.getComponent('inventrry')
And i dont want want to put the player parameter in the function
What i dooo
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)
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
We need 2 more messages here to reach 99999 messages
I m gonna make it reach 99 999
Done
It's hit 99999 mutliple times now
It just resets a certain amount back since discord can't seem to display over said number
that moment when you spend a long time making localization strings and forget that lore doesn't support it
that sucks.
I mean I still needed it I guess
Just sucks that there's no way to just turn the localization key into a string
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
dude we need a distance() method, i am so tired of calculating the distance manually
can't you turn it on via json ui?
I don't think so
Hence why we have functions
no
I don't want to make a function for every project, a distance method is just too convenient
you can't just make a file for functions you commonly use
and import that into each project?
you are really complaining about making a function
honestly great idea
It could be a nice thing to have in vector-utilities
yeah, jayly has a minified version of minecraft-math
distance included.
Ye, AI is great for tasks like that
was runCommandAsync removed
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
the player wouldnt exist if theyre not online so it wouldnt work at all
as in, the player object is stored
where is it stored?
in a class
hmmmmm
is that sarcasm
no i genuinely dont really know
'world.beforeEvents.worldInitialize'
was this removed or replaced
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
that's fair, I'm just wondering because it'd be easier to check isValid instead of making a function to check if the player is online instead
i just don't have an alt to test it tbh
it is world.afterEvents.worldLoad and system.beforeEvents.startup in 2.0.0-beta
ive never stored the player object before soooo...
cant give a clear answer, sorry
It's all good
question, would you mind joining my world for a second so i can test it?
im on a lecture rn so i cant, sorry
all good
Any property or method from the player object is no longer available the moment that object exits the world. Even if you copied the object to a database and accessed it later, that object won't change. It will remain stagnant.
made a new account and tested it
isValid becomes false once the player leaves
let's goooo
easy
It's false because it doesn't exist.
How are you storing it.
If you are copying the object then the copied object doesn't reference the original object.
just setting the player object to an undefined let
but anyways, it works and I'm happy
I don't think you understand what it's doing though.
???
But if it's getting you the results you seek then so be it
explain what I'm misunderstanding please
from my understanding the player leaves so the player object is no longer valid and is false
lmao bro gave up
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.
Not even close.
damn the typing stopped so i thought you gave up
That was your ego speaking out loud.
no? i just thought you gave up typing
ok , why does the isValid become false then?
Because it doesn't exist.
if the object didn't exist wouldn't it throw an error
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.
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
how do i check the owner of a tamed entity?
like this?
Why no 0.1.0
bruh wdym calculating it manually... Make it a function or um It already has a function in Vector3Utils, @minrcraft/math.js....
Oh i didnt read the full messege history
You were already replied lol
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
make it to check if .getEnchantments() returns an empty array
how
okay a bit
hmmmmmmm
const enchants = enchantableComponent.getEnchantments();
if (enchants.length === 0) {
// no encchantment
}```
like that?
@shy leaf
legnth right
maybe
i hope so lets try it
Is there any way to force player into sneak mode
huh
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.Player.html#example-alwayssneakts dunno if this works
Yeah isSneaking isn't readonly
Player.isSneaking = true
hwhwoa-dhadas-das
SNEAKING ISNT READ ONLY !??!
My whole life was a lie. 😭
lmao
lol
is isJumping also not readonly
would doing isJumping = false
make not allow to jump?
.
/**
* 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
also thus
eh, why do you need a prototype for one line of code
not sure
overriding library classes is not a good idea tbh
also, this is just a one line, so why you have to use a new function to force someone to sneak
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
what do you think about it
^
/**
* 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?
its weird though
because the sneaking persists for like, less than a tick
it prolly depends on client fps
eh weird
uh
how about doing in runInterval
ok i se
the player would shake crazy
does the player have to sneak?
huh
whatcha trying
how da hell you do blank msgs
you could try this method
or you can check for player input
and make it work only if player is holding shift (sneak key)
what if we disabled the input permission for Sneak
the only downside is that mobile touch controls keep the sneak button for a tick and release
player.runCommand("inputpermission set @s sneak disabled");
wait i thought of this
how about doing this
native methods
there should be InputPermission method for Player
If we remove animation will it remove from all server forms, even custom ones?
the tick delay would bash you
player.inputPermissions.setPermissionCategory(5, false)
"lets inform BAO members before i go collect them"
back
wait Is it possible to get hunger?
no
hunger comoponent exist tho
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
/**
* @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?
instead of checking for every direction, try this:
Math.hypot(vel.x, vel.y, vel.z)
const speed = Math.hypot(vel.x, vel.y, vel.z);
return speed > 0;
how to detect damage per second
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"
Documentation for @minecraft/server
WorldAPI.afterEvents.playerJoin.subscribe((event) => {
const player = world.getPlayers({ name: event.playerName })[0];
if (!player) {
console.warn("[DEBUG] playerJoin triggered but player was undefined.");
return;
}
})
Would be more efficient to use the player spawn event.
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.
/**
* 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
I would probably need to run it on a computer and verify the numbers but I'm at work.
No problem
Also, if anyone is in the OSS server, I got a question there.
#879773489601585244 message
Actually, I'll just open the question here.
does anyone know how to actually fetch the open ai api through server-net?
still says playerJoin triggered but player was undefined
It’s becouse the player joined, but the player as entity is not loaded yet, you have to use playerSpawn
How to make it so that only 1 entity of the same family can exist at a time?
What do you mean by “family”?
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
That’s a bad way of doing that
You can listen for EntitySpawn event, get all the entities:
if there is alredy one entity in the world from that family remove the spawned entity
Without checking every tick
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server-ui
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server-net
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
@jaunty relic use #debug-playground next time
🙏
Srry
no problem, just don't spam it here
Hello BAO scripters whats is going on today?
you are so true ngl
yeah
yea
waiting for next stable right now
nice
is 1.21.80 coming out today or in the next week?
idk, but what feature are you look for the most?
i think there are inventory events for player right?
I want to see how slash commands will be working in a stable look
this is the second thing that I am waiting for
I am still thinking how they missed an origin param in command handle
i wish i had more time of free time for script api
😭
I make each ItemType from ItemTypes.getAll() be placed on a furnace every time the script reloads so I get the most accurate Item Smelting recipe.
isn't it the first param?
I haven't been using script API for like 4-5 months for something bigger
just few commisions
interesting
it is right now, but in the first release of them, it was missing
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
at this moment, I think that using some proxy or mod-loader is a better options for slash commands
I'll probably continue to create custom commands with help as a parameter to get information about the command.
I prefer using Script API also, for stability, but sometimes community makes better things
2 days before navi released custom commands i started working on my own command parser with syntax feedback
💀
it's a sign to work on a wrapper for new commands
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.
yea
depends
I feel like it may present restrictions.
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
Just your imagination
i hate my imagination
Haha
bc it produces 3 useless project per month
yeah, it's not a problem
for fresh programmers it might be a bit
my imagination is like a rainbow
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]
dynamic properties
and JSON obejct
stringify array and save it to dynamic property
Entity.setDynamicProperty("some-key", JSON.stringify(yourArray))
It's working thanks
player use entity with low-capital first latter it hurt my eyes 🤓
jk
Entity.prototype.setDynamicProperty("some-key", JSON.stringify(yourArray))
wha- whyy???
also most of those people aren't even that deep-diving into JS
howwww
I wonder how is your JS skills doing 👀
We have special event in scripting discord server
and you can check the questions that are based on JS knownledge
we ain't doing pure JS here
I prefer royalty and TypeScript
all right, but that questions are really tuff
this is confusing sometimes
yea i know this one
but i make something that counts on JS knowledge and not fun facts
"umm, this is production-level code" 🤓
you mean the weird af requirement? 😭🙏🏼
Listener.thingy += someFunction
Listener.trigger()
Listener.thingy -= someFunction
why would someone even write this for production
😭
Imma intercept the Function class prototype lol 🙏🏼
too bad my form was cleared after I left it unsent for 2 days
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
i hate OOP in JS
functional is better for JS
OOP with typescript is not bad
but always depends on your cases
for scripts in general i prefer functional
I always try to put everything in classes
also grouping functions in a class with a private constructor as static methods is pretty good
yea thats one of the things i do as well
static class only with private constructor is good
The only OOP I know is when my world crashes and I go "OOPS"
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
already don't like that tab size
I put random BS on my main.js file and pray it works 🙏🏼
I don't like tab 2
but yours is 5?
it's 4
I don't know
i don't think i ever used classes in script api
yea also script api is designed a bit differently
You should. It's like comparing a tidy room with mine
in my IDE it looks okay
maybe its bc i don't like how long your lines are
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 }
idk, i never been in a situation where i needed it
basic js stuff is more than enough
but the code is not bad eather just sayin
it's an express app with clustering, I need to prevent creating a connection for primary worker
the minecraftMessages is a Prisma model
just my formatting
I agree. 🙏🏼
btw i have something similar
I have set 200 printWidth in Prettier
68 line...
why both pairs in the same line?
i don't like prettier settings
what is Prettier missing for you?
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
oh I understand
there are more little things i want
I like using Prettier just to keep with the standards
i feel the same way, but i learned to live with it, lol
don't want anyone to see my weird formatting
also I can style in a easy way some code of my friends that is horribly organised in some cases
anyway i just wrote Raknet implementation and i already hate that project
i use to write compilers code, basicly that stuff what TSC products
i am glad i leveled up
i use to write JS with .d.ts
I'm in 10th grade right now, and I think that I am much higher than everyone from my class and even school
so lot of ppl asked my if where is the TS source code
yea i know that feeling
I would use a TypeScript at this point
i am using now, but i was someone else before
writing d.ts from a scratch is a pain sometimes
i used to do so and i was pretty ok, but you have to keep in mind when you change the function in JS
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
¯_(ツ)_/¯
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
static inheritance?
it's possible with TS
there's a small workaround
but not enough
class SomeClass {
protected constructor() {}
public static someAbstractMethod(): void {
throw new Error()
}
}
yeah
well yea these little things i hate about TypeScript, i wish ts covered more JS style than trying to make a diff language
TS is a large superset of JS
thats also reason why i want to create own TS compiler in the future
I'll stick with TypeScript for front-end absolutely
TypeScript is pretty good language
I write most of my code in TS
only few test scripts for local use are in JS
sometimes C/C++ in other projects
i don't count there langs
but not a big fan of C langs
Lol
As much as I dislike Windows, I do actually like C# and it pains me to say that haha.
i like windows bc i can play bedrock on it
I like more Java than a C#
but I don't know about Kotlin tbh
Kotlin is something that my brothe use
idk for what tho
maybe for mobile app development
most of people that are using Kotlins are secret fans of Java, that can't claim that they like Java to themselves xD
most popular
then probably back-end services (mostly Spring)
BDS knocked on my door, looked me dead in the eye, and said, “May I introduce you to a lovely time on Linux, where the blocks are plentiful and the crashes are… well, a unique feature.”
||isnt this off topic?||
the better version of Minecraft
🤫
I like Script API 👍
I use linux daily to start my discord bot that crashed over the night
i like linux tho
who likes linux?!
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
yea for games its better anyway and powershell is also not that bad
windows has a lot of great quality of life features
Kotlin is just a better version of Java. It's the C++ of C lol.
functions are just a funny things!
#idontlikepython
(worst joke of my life)
I used to use Python frequently when I worked on AOSP. It was alright lol.
☕
java is good but very old
i like how even reacted the ppl who just spectating here and read all the message we type here
they're moderating us
💪
our messages are recorded and saved to the government
I just didn't know what to write.
thats all right, you are my guys!!! We are on same side of python not enjoying
I was never a fan of Java. Even when I worked on AOSP I could never come to terms with it. I just simply dealt with it.
we should make a group that is spreading Python hate all accross this server
Well C# was my first language my dad showed to me
Respect
i mean its basically javascript but variables are an headhache
doubtful
my dad can't even understand english 😭
(in italy its normal tho)
I have been learning Python for 3 months in 2020
then started with some basic web-dev (HTML/CSS)
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
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
the only language that my 11-yo brain was able to process
