I'm trying to figure out how to set up a reason argument properly for my moderation commands.
I plan to have it be executed like this:
!warn <#UserMention> [reason]
I have it set up so any word that comes after the command name would be sliced into an array of arguments.
let messageArray = message.content.split(/\s+/g);
let cmd = messageArray[0];
let args = messageArray.slice(1);
let command = cmd.slice(prefix.length);
I could just have moderators put the reasons between quotes so the console reads it as one string, but that creates a slight inconvenience. How would I splice any amount of arguments starting at args[1] to make a full string labeled "reason"?
If I understand you correctly, all you're having trouble with is getting a single message instead an array of arguments.
You can just Array#join the arguments:
let msg = messageArray.slice(1).join(' ');
This will join all the words of the message with a single space. See the MDN documentation.
The easiest is to use array.Reduce
someArray = ["I","like","icecream"]
someArray.reduce((total, value) => total + value, "")
//becomes "Ilikeicecream"
Feel free to add spaces at the end of each word.
Related
I have this string:
"$warn #Test use of bad language"
and I want to get the part from 'use' to 'language' (from index 2 to index x)
How can I do that with differnent parts after the #Test and with different length each time?
I'm new to JS and it might be super easy / dumb, but I need to know. Thx!
i tried message.slice(2, message.length - 1). i found an answer though.
You can split the string into different bits for this using string.split
const [command, mention, ...args] = message.content.split(" ")
const reason = args.join(" ")
// command = "$warn"
// mention = "#Test"
// reason = "use of bad language"
Using destructuring here makes it easier to give a readable name to different parts of the message content
I am making a discord bot and one of the commands allows the user to send and embed to any channel with whatever text they want, but I want them to be able to start a new line in the body of the embed too. Simply having them type "\n" in their message in the command does, not work, the bot will output that \n in the embed instead of making a new line. Is there an easy way to do this?
Embed:
const sayEmbed = new Discord.MessageEmbed()
.setColor('#4d4d4d')
.setTitle(header.join(' '))
.setDescription(args.join(' '))
The description field is where this is occurring when there is a "\n" in the args array it will not make a new line it will simply send.
You don't actually need to use \n, you can just create a new line when sending the message, and discord.js will do all the parsing work for you. I tested this out with my bot:
So I made a kind of simple DIY sort of thing. (LOL, actually I made this as I saw the question, took like 5 mins.)
It allows you to disect a message using the operator | (The one below BackSpace).
I tried using this in an eval command, so I'm sure it works.
The codes are:
// Creating array variables so it doesn't return undefined when we try to `.concat()` it.
let sentences = [];
let temp = [];
// Loops every args
for(l=0;l<args.length;l++) {
// Adding the args as an array to the `temp` variable.
temp = temp.concat(argss[l])
// If we meet `|` which is a sentence separator.
if (args[l] === "|") {
// Join the `temp` array, making it a sentence while removing the `|` operator.
sentences = sentences.concat(temp.join(' ').slice(0, -2));
// Resetting `temp` to reset the saved sentence and start a new one.
temp = [];
}
}
Using .join(' ') will not work since it returns a string from an array, and therefore joining \n cannot be used.
The above method may be more efficient. They use a command such as:
// Say prefix is `.` and the command is `embed`
.embed <header> | <content> | <title1> | <sentence1> | <title2> | <sentence2> |
and you will get sentences[0], sentences[1], sentences[2], sentences[3], sentences[4], sentences[5] respectively. You can then add this to your embed.
This will also allow multi string input, instead of a single args. Don't forget the | at the end since without it, it will ignore the whole last sentence.
const sayEmbed = new Discord.MessageEmbed()
.setColor('#4d4d4d')
.setTitle(sentences[0]) // <header>
.setDescription(sentences[1]) // <content>
.addField(sentences[2], sentences[3]) // <title1> <sentence1>
.addField(sentences[4], sentences[5]) // <title2> <sentence2>
// The more you add, the more it'll allow, you'll have to set it yourself.
TL;DR: A simpler answer:
sentences = args.join(" ").split(" | ");
Sorry, I tend to do things the hard way a lot.
I'm trying to run this code:
var elements_var = "Csus2 FM Dm CM";
var elements = ["Csus2","FM","Dm","CM"];
var note_var = (elements.join('\xa0'));
console.log("elements.join output:")
console.log(note_var);
console.log("Regular string output:")
console.log(elements_var);
note_2 = note_var;
const chordsClip = scribble.clip({
// Use chord names directly in the notes array
// M stands for Major, m stands for minor
notes: note_var,
pattern: 'x---'.repeat(4)
});
And this is the Console output:
As you can see while console displays "Csus2 FM Dm Cm" correctly in both regular string (elements_var) and elements.join output (note_var), note_var seems to be missing it's first char when passing it to another function.
Function works perfectly when elements_var is inserted instead of note_var. What's happening? How can I fix this issue?
Using \u0020 instead of \xa0 solved the problem.
But still don't know why this happen when using \u0020 cause it has nothing to do with the first char of the first element in the array.
I have spent hours, close to 8 hours none stop on this, I am trying to use jQuery/JS to create two arrays, one which is dynamic as it is loading a chat script and will be split by whitespace in to an array, for example:
String: Hello my name is Peter
Converted to (message) array: ['hello','my','name','is','peter'];
I have a set array to look out for specific words, in this example let us use:
(find array) ['hello','peter'] however, this array is going to contain up to 20 elements and I need to ensure it searches the message array efficiently, please help.
I can help you with that.
var arrayOfWords = $(".echat-shared-chat-message-body").last().text().split(" ");
That code is actually working! i went to an open chat in this website so I can tested.
So just replace the word REPLACE with your DOM object :)
var arrayOfWords = $("REPLACE").last().text().split(" ");
If I understood well, you're asking to filter an array of string (from an incoming string) given a second array.
In your described case you'll certainly not have to worry about efficiency, really. Unless your incoming message is allowed to be very very big.
Given that, there is a dozen of options, I think this is the most succinct:
const whitelist = [
'hello',
'peter'
]
const message = 'hello my name is Peter'.split(' ')
const found = message.filter(function(word) {
return whitelist.indexOf(word) > -1
}
You can treat invariant case:
const whitelistLower = whitelist.toLowerCase()
const foundInvariantCase = message.filter(function(word) {
return whitelist.indexOf(word.toLowerCase()) > -1
}
Or use ESS Set:
const whitelistSet = new Set(whitelist)
const found = message.filter(function(word) {
return whitelistSet.has(word)
}
So lets say I have a mailto email in which a checkbox question exists that asks the user to pick the best fruits out of a list of fruits (check all that apply.) They end up with apples, bananas, and pears. The mailto email that they trigger then contains the following (assuming the checkboxes in the question are named bestFruits):
...
bestFruits=apples
bestFruits=bananas
bestFruits=pears
...
So in my javascript file, I have the following line to parse values from the email:
var bestFruits = mail.bodyText.match(/bestFruits=\s*(\S.*\S)\s*/);
So my issue is that this would (presumably) take only one value by the end. What I need, is for the javascript to loop and add each value of bestFruits in the email to the bestFruits var so that each value (apples, bananas, and pears) are all in the bestFruits var.
Is there any way to do this? I tried making a for loop, but I couldn't determine the syntax to loop through the mailto email body and add each instance of bestFruits to the variable.
I'm still extremely new to all this, as I was thrust in recently. If I'm missing something fundamental, I'd appreciate a quick pointing-out. If you require any more info, I'd be happy to try to provide it.
Thanks for reading guys!
You don't need looping. You do need to match all the fruits (as per your example, matching all single words after bestFruits), remove bestFruits= from the matches, join the resulting array and store it in a variable. Like this:
var bestFruits = mail.bodyText.match(/bestFruits=\w+/g)
.map(function(x){return x.split('=')[1]})
.join(',');
What does it do:
Matches all your best fruits.
Takes each bestFruits=abc element and replaces it with abc (i.e., splits with = separator and takes the second part)
Makes the string of your fruits (converts the resulting array to string with , joiner).
You were very close - modified your regex a little bit:
var body = `this=is
an=example
bestFruits=apples
bestFruits=bananas
bestFruits=pears
of=doing
things=ok?
`;
var re = /bestFruits=(.*)/g;
var fruitMatches = body.match(re);
var bestFruits = fruitMatches.map(function(fruitMatch) {
return fruitMatch.split('=')[1];
});
console.log(bestFruits); // ["apples", "bananas", "pears"]
Fiddle