casual-simulation / casualos

Casual Open Simulation for the Web
https://ab1.bot
MIT License
49 stars 9 forks source link

Add the ability to dynamically add/remove listeners on bots #463

Open KallynGowdy opened 4 months ago

KallynGowdy commented 4 months ago

Currently, the only way to place a listener on a bot is to set a tag with the @ symbol. This means that it is currently only possible to have one listener on a bot for a particular event, and also that every listener must be a script that is compiled by itself.

This has a couple downsides:

Ideally, it would be possible for a script to register a listener for a bot using an API function call. This would allow bots to have multiple listeners for a single event (two @onClick handlers). It would make dynamically adding/removing listeners much easier. It would increase performance by allowing the user to skip the script compilation step and reuse listeners.

Here's the API:

os.addBotListener(bot, tagName, listenerFunction) - Registers a function to be called whenever an event would be sent for the given tag name to the given bot. os.removeBotListener(bot, tagName, listenerFunction) - Unregisters a function to be called whenever an event would be sent for the given tag name to the given bot.

Additionally, functions should be able to be used directly in create() function calls:

create({
  // Registers a onClick listener on the bot during creation
  onClick: () => os.toast("You clicked the bot!"),

  // The registration happens before the @onCreate whisper,
  // so it is possible to do this
  onCreate: () => os.toast("You created the bot!"),
});

Listener functions should have the following structure:

type ListenerFunc = (that: any, bot: Bot, tagName: string) => any