Get all arguments after args[0] discord.js

笑着哭i 提交于 2021-02-02 09:55:54

问题


I was trying to make a mute command, and I was adding a system where you can mute them for a reason. The bot would reply "(Username of user) was muted. Reason: (The reason)". For me args[0] is just mentioning the user that you want to mute, but I can't figure out how to get all after args[0]. I've tried doing something like this message.channel.send('I have muted' + (mutedUser) + 'Reason: ' + args[1++]. But that obviously didn't work - I was kind of guessing - I turned to listing 4 arguments like this.

message.channel.send('I have muted ' + taggedUser.user.username + ' Reason: ' + args[1] + ' ' + args[2] + ' ' + args[3] + ' ' + args[4])

But obviously, that's not very efficient - Does anyone know how to get all arguments after args[0]?


回答1:


Take the array of args and slice() the number of arguments you want to delete, then join() the remaining array elements into a single string

Quick Tip Use Template literals for easier formatting with strings and variables

const reason = args.slice(1).join(' ');

message.channel.send(`I have muted ${mutedUser}, Reason: ${reason}`);



回答2:


You can use Array.prototype.join() and Array.prototype.slice()

const str = 'first second third fourth fifth sixth seventh...';
const args = str.split(' ');

console.log(args[0]); // first
console.log(args.slice(1).join(' ')); // everything after first

console.log(args[3]); // fourth
console.log(args.slice(4).join(' ')); // everything after fourth

// basically, `Array.prototype.join()` can join every element of an array (with an optional separator- in this case a space)
console.log(args.join(' ')); // join all elements with a space in between

// and `Array.prototype.slice()` can slice off elements of an array
console.log(args.slice(5)); // slice off 5 elements

// now you can combine these two :)



回答3:


In a generic scenario, you can use destructuring assignment as so:

const [foo, ...bar] = args;

Here, foo is equal to args[0] and the rest of args is contained within bar as an array.

Specific to your case you could probably do this within your command:

const [mutedUser, reason] = args;

And then as Elitezen suggested, use template literals to send your message.

message.channel.send(`I have muted ${mutedUser}, Reason: ${reason}`);


来源:https://stackoverflow.com/questions/64369728/get-all-arguments-after-args0-discord-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!