Androz2091 / discord-player

🎧 Complete framework to simplify the implementation of music commands using discord.js v14
https://discord-player.js.org/
MIT License
589 stars 192 forks source link

feat: add async context api for hooks #1893

Closed twlite closed 5 months ago

twlite commented 5 months ago

Alternate api for hooks

Previous methods still work and this mode is opt-in. In order to enable this api, the command handler needs to provide context to HooksContextProvider and hooks must be called without any arguments. The benefit of this approach is you don't need to care about passing guild id every time you want to access something inside the command. Hooks will resolve correct data even if the same command is executed multiple times concurrently.

Note: This only works inside the call stack created by withContext function.

const { withContext } = require('discord-player');

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) return;

    // assuming the following code is your target command to be executed
    const command = getCommandSomehow(); // shape is roughly { execute: Function }

    const context = { guild: interaction.guild };

    // provide context and execute the command
    await withContext(context, () => command.execute(interaction));
});

Then discord-player hooks can be used without providing guild id.

const { useQueue } = require('discord-player');

// your command
export async function execute(interaction) {
    // here we are not passing any arguments, discord-player will automatically resolve correct queue based on the context
    const queue = useQueue();
}
vercel[bot] commented 5 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
discord-player-website ✅ Ready (Inspect) Visit Preview Mar 28, 2024 8:05pm
twlite commented 5 months ago

This is now available in @dev for testing