How can I get a variable into a argument? - discord.js

I have the following code :
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
var number = command.length - 1;
var times = args[number ***Here I want the last position of the user input***];
If you write an command in a text channel, the last argument from the user input should get into the times variable. Here's one example: the user writes '!test some random text 3' and the last argument (in this case 3) should get into a varable. Hope you can help me

You can use args.length - 1 so in your case var times = args[args.length - 1]

Related

How can I make my bot ping a person with a command example: !eat #the user i want, the bot: #the user has been eated

I want to do a command for example eat and i want the bot ping, here is an example :D
bot.on('message', (message) => {
const parts = message.content.split('');
if (parts [0] == '!eat'){
if (parts [1] == 'The member that i want to be pinged by the bot') {
message.channel.send('The user that i pinged on command has been eated!')
}
};
}
I have made a few changes:
I have added a global prefix variable, so that the prefix can easily be changed.
I have added checks to make sure the function exits if the message was sent by a bot or doesn't start with the prefix.
I have added some code to split the message into a command and arguments.
I have replaced the if statement with a switch statement.
I highly recommend that you read the Discord.js guide, as it's very beginner friendly and will allow you to write even better code than in this answer. Much of the code in this answer is taken from the Discord.js guide.
const prefix = '!';
bot.on('message', (message) => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/\s+/g);
const command = args.shift().toLowerCase();
switch (command) {
case 'eat':
const member = message.mentions.members.first();
if (!member) return message.reply('Could not find the mentioned user.');
message.channel.send(`${member.user.username} has been eaten!`);
break;
default:
message.reply(`The command \`${command}\` was not recognized`);
}
});
Explanation
The command prefix is set:
const prefix = '!';
The function exits if the message was sent by a bot or doesn't start with the prefix:
if (message.author.bot || !message.content.startsWith(prefix)) return;
The prefix is removed from the start of the message, and the message is split at all whitespace gaps:
const args = message.content.slice(prefix.length).trim().split(/\s+/g);
The first argument is removed, converted to lowercase and stored in the command variable:
const command = args.shift().toLowerCase();
The first mentioned user is found:
const member = message.mentions.members.first();
If there is no mentioned user, a warning message is returned:
if (!member) return message.reply('Could not find the mentioned user.');
A message is sent to the server saying "[the user] has been eaten!":
message.channel.send(`${member.user.username} has been eaten!`);
References
Message.mentions
<#${message.member.id}> That will ping the author of the message just use (``) and not (' ') and that will ping the author

How to make a discord.js bot repeat a user's message without including the prefix and command name?

Okay this most likely has a really simple answer but I couldn't find the same thing online and I can't figure it out on my own thinking.
So in the args for responding to a prefix, i have this:
case 'say':
const usermsg = message.content
message.channel.send(usermsg)
break;
Since it's the entire contents, it responds with the c!say too then it triggers itself. But the triggering isn't the issue, I want the c!say not included in the message. (I know I don't need the const for this, I just wanted to experiment different combinations of stuff in a separate line)
Update:
So I found a second method of approaching this by using the arguments part, like this:
case 'say':
message.channel.send(args[1])
message.delete(1)
break;
So this does what I want but only for the second argument, meaning it doesn't work for more than 1 word. So my current thought is subtracting args[0] (the c!say phrase) from message.content.
Found a fix to the issue, instead of sending the arguments or subtracting text I used the replace command.
case 'say':
let saymsg = message.content
message.channel.send(saymsg.replace("c!say",""))
message.delete(1)
break;
I can't believe I didn't remember the world replace sooner, but that's it, it works.
case 'say':
const usermsg = message.content.split(' ');
message.channel.send(usermsg.slice(0).join(' '));
break;
This code will take in the full user string, slice out the first argument (the command and prefix), then join the rest of the message and send it in chat.
bot.on('message', message => {
var sender = message.author;
var msg = message.content.toUpperCase();
var prefix = '>';
var cont = message.content.slice(prefix.length).split(" ");
var args = cont.slice(1);
for (x = 0; x < profanities.length; x++) {
if (message.content.toUpperCase == profanities[x].toUpperCase()) {
message.channel.send('Hey! Don\'t say that');
message.delete();
return;
}
if (msg.startsWith(prefix + 'SAY')) {
message.delete();
var saymsg = message.content;
message.channel.send(saymsg.replace(prefix + 'say', ''))
}
}
}

Matlab, AppDesigner-Convert image on a good type and use it in "imread" function

I use AppDesigner inMATLAB to show photos with changed RGB. But there is the problem with character of the photo.
When I switch on my own fuction "changeRGB", finally "choosenImage" has 20bytes, class "char" and size(1x10). OK!
There is no problem in using the "function OpenButtonValueChanged". OK!
There is the problem with "function UploadButtonPushed". OK!
ABOUT THE PROBLEM:
When I click button which callback is "function UploadButtonPushed" I get the error:
"Error using imread>parse_inputs (line 502)
The file name or URL argument must be a character
vector or string scalar."
"Error in imread (line 342)
[source, fmt_s, extraArgs, was_cached_fmt_used] =
parse_inputs(cached_fmt, varargin{:});"
WHY?
Because in the "function UploadButtonPushed" my choosenImage has 1977624bytes, class "uint8" and size(681x968x3). So it's too bug for "imread".
WHAT I TRIED:
When in "function OpenButtonValueChanged" I convert a photo, adding "char": (myimage = char(app.clickedImage)); the class of the photo is changing from uint8 to char but the size.
When I use "num2cell", the claas of the photo is changing on "cell" but size and number of bytes are the same- so big. And I get the Error: "Error using imread>parse_inputs (line 502) The file name or URL argument must be a character vector or string scalar."
In my own function "changeRGB" I used "imread(image)" and here is the problem with the size of the photo. Do you know how to get the correct one?
%my own properties in AppDesigner- to use them in different functions
properties (Access = public)
clickedImage;
addR = 1;
addG = 1;
addB = 1;
end
%first function in AppDeesigner
function OpenButtonValueChanged(app, event)
value = app.OpenButton.Value;
[file, howManyFiles] = chooseImagesFromComputer; %myown function
%I load 3 images which are showed as miniatures
myFile1 = imread(file{1});
imshow(myFile1, 'Parent', app.UIAxes1_1);
myFile2 = imread(file{2});
imshow(myFile2, 'Parent', app.UIAxes1_2);
myFile3 = imread(file{3});
imshow(myFile3, 'Parent', app.UIAxes1_3);
%take values of changed RGB from the slider
app.addR = app.SliderR.Value
app.addG = app.SliderG.Value
app.addB = app.SliderB.Value
%work only on one image to change its colors. app.clickedImage, app.addR, app.addG, app.addB are properties at the beginning of the code
app.clickedImage = file{1};
app.clickedImage = changeRGB(app.clickedImage,app.addR,app.addG,app.addB); %changeRGB- my own function- here is the problem. I add it bottom
imshow(app.clickedImage,'Parent',app.UIAxesMain);
end
%second function in AppDesigner
%here is the button to upload color of the photo
function UploadButtonPushed(app, event)
myimage = app.clickedImage;
myimage = changeRGB(myimage,app.addR,app.addG,app.addB);
imshow(myimage);
end
%here is my own function in matlab, not in AppDesigner, which makes problem:
function [changedImage] = changeRGB(choosenImage, addR, addG, addB)
whos
loadedImage = imread(choosenImage);
R = loadedImage(:,:,1); %extract one of the color channels
G = loadedImage(:,:,2);
B = loadedImage(:,:,3);
RBG = cat(3,R,G,B);
R_adj2 = R + addR;
G_adj2 = G + addG;
B_adj2 = B + addB;
changedImage = cat(3,R_adj2,G_adj2,B_adj2);
end
First, you make unnecessary operations in changeRGB
function [changedImage] = changeRGB(choosenImage, addR, addG, addB)
loadedImage = imread(choosenImage);
loadedImage = bsxfun(#sum, loadedImage, reshape([addR, addG, addB], [1 1 3]);
end
Then this function return an array (the modified image) so in UploadButtonPushed(app, event) when you run myimage = app.clickedImage;, you are passing the modified array instead of the image path, that you set here app.clickedImage = changeRGB(app.clickedImage,app.addR,app.addG,app.addB);
So you have to change the design of your variables, because app.clickedImage is saving either the image path, or the image itself. Consider having 2 different variables.
A good advice also is to use matlab debugger which is really good help to find the source of this kind of problems.

NodeJs Readline value put into array

I'm using NodeJS readline module to read from a text file. Its returning every line to the console however I want it to add the returned lines to an array. This is the code I got so far, but its not working. I thought the rd.on acted as a sortof for loop but it doesn't look like it. Any help would be appreciated!
function getinfomation2(){
var firstfile = [];
var secondfile = [];
var countvar = 0;
readline = require('readline');
var rd = readline.createInterface({
input: fs.createReadStream('../FixtureProfiles/CFIP1.json'),
output: process.stdout,
terminal: false
});
// Add fixture details from file to array to later be called
rd.on('line', function(line) {
// if fails console.log(line) returns line in console
firstfile(countvar) = line;
console.log(firstfile(countvar))
countvar = countvar +1;
});
}
firstfile(countvar) = line is incorrect.
Array access operators are [ and ] (see Array docs on MDN).
Also check out Array.push:
firstfile.push(line)

Clearing my array leaves blank array positions

So I'm facing a problem with an AS3 class that's not operating the way I need it to. It's a simple problem, but a complex set of methods that cause it.
Firstly, the 'quiz' I'm building has 6 questions loaded as external SWFs inside of a Shell, run by a class. First we declared a var "a_quiz" to hold 6 values pushed from the external SWFs. These 6 values are reduced to a string and then checked against another array that contains the correct answers. The following loadQuiz function is designed to launch one of three random quizes and clear the a_quiz array so it can take new answers:
public function loadQuiz():void {
a_quiz.length=0;
trace("loadQuiz");
n_quizCorrect = n_quizScore = 0;
n_currentQuiz = Math.floor(Math.random() * (n_totalTopics - n_quizStart + 1) + n_quizStart);
loadTopic(n_currentQuiz);
}
Now I've tested the Shell and confirmed that the trace "loadQuiz" fires every time. And the first time you load the quiz, everything behaves as it should. The 6 questions trace correct or incorrect responses and push 6 binary values into the a_quiz array. The output looks like this:
loadQuiz
incorrect
correct
incorrect
incorrect
incorrect
incorrect
0,1,0,0,0,0
you failed
Then I jump back to the main menu and launch again. This deploys the loadQuiz function all over again. The first line of the function:
a_quiz.length=0;
should be emptying the a_quiz array to accept new answers to mark against. But when I complete the quiz I get this:
loadQuiz
correct
correct
correct
correct
correct
correct
,,,,,,1,1,1,1,1,1
you failed
For some reason beyond my understanding, the push values are stacking on top of empty positions, so when the strings compare...they won't match. What is going on here?
The push function:
function handleClick(evt:MouseEvent):void{
var tempCORRECT = a_answerSheet.toString();
var tempSELECTION = a_selected.toString();
//
if(tempSELECTION == tempCORRECT){
trace('correct');
parentObj1.a_quiz[ parentObj1.n_currentQuestion - 1 ] = 1;
}else{
trace('incorrect');
parentObj1.a_quiz[ parentObj1.n_currentQuestion - 1 ] = 0;
}
parentObj1.n_currentQuestion ++;
// GOTO NEXT SLIDE
parentObj1.LOADNEXT('up');
}
The problem originated in the loading of the Quiz itself.
as you can see on the handleClick function:
parentObj.n_currentQuestion++
was increasing an integer variable on the parentObj's timeline called n_currentQuestion. The problem then, originated in how the quiz was logging n_currentQuestion when the quiz loads with this function:
public function loadQuiz():void {
a_quiz= [];
trace("loadQuiz");
n_quizCorrect = n_quizScore = 0;
n_currentQuiz = Math.floor(Math.random() * (n_totalTopics - n_quizStart + 1) + n_quizStart);
loadTopic(n_currentQuiz);
}
So to correct the error, I needed to add a line to the loadQuiz, so that it would always load with n_currentQuestion set to 1.
public function loadQuiz():void {
a_quiz= [];
n_currentQuestion = 1;
trace("loadQuiz");
n_quizCorrect = n_quizScore = 0;
n_currentQuiz = Math.floor(Math.random() * (n_totalTopics - n_quizStart + 1) + n_quizStart);
loadTopic(n_currentQuiz);
}

Resources