How to detect if the bot has been mentioned? - javascript

How can I detect if my bot is mentioned?
I tried these thus far:
if (msg.content.toLowerCase().includes('#The Guardian of The Bar#5180')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}
if (msg.content.toLowerCase().includes('#The Guardian of The Bar')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}
if (msg.content.includes('#The Guardian of The Bar#5180')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}
if (msg.content.includes('#The Guardian of The Bar#5180')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}

I'm not experienced in discord.js, but according to this in the documentation, a message object has a method message.isMemberMentioned(User or GuildMember). Using this method, one can use
client.on('message', message => { //this event is fired, whenever the bot sees a new message
if (message.isMemberMentioned(client.user)) { //we check, whether the bot is mentioned, client.user returns the user that the client is logged in as
//this is where you put what you want to do now
}
});
I would like to recommend, that you read the documentation fully, before you try to make a bot.
On v12 discord.js you now have to use message.mentions.has(bot.user)

Related

How do I define the guild I want to use ".channels" on?

I'm setting up a bot analytics staff channel for my discord bot's support server.
I want the bot to be able to send a message and then edit it every minute. But, when I try to do this, I get an error saying that I didn't define the guild that I want to use .channels on. The exact error is TypeError: Cannot read property 'channels' of undefined.
I've tried defining my guild in many different ways, including making it into a variable and combining it with the function that finds the guild itself. But, none of these possible solutions, some of which coming from some related Stack Overflow posts, have worked for me.
I've also tried looking at some tutorials, but they also haven't worked either: the code always says that I'm not defining my guild correctly.
//Stats For Staff Channel
let serverchannel = bot.guilds.get("498548588318556210").channels.get("528288924917825556");
let servercount = bots.guilds.size
let uptimetotalseconds = (bot.uptime / 1000);
let uptimehours = Math.floor(uptimetotalseconds / 360);
uptimeseconds %= 3600;
let uptimeminutes = Math.floor(uptimetotalseconds / 60);
let uptimeseconds = uptimetotalseconds % 60;
let uptime = "Total Uptime: \n \n Hours: " + uptimehours + "\n Minutes: " + uptimeminutes + "\n Seconds: " + uptimeseconds + "\n Total Uptime In Seconds: " + uptimetotalseconds + "\n Total Uptime In MiliSeconds " + bot.upTime + "\n \n \n \n"
let messagetobesent = "**Bot Status** \n \n" + "Server Count: **" + servercount + " guilds** \n \n" + "Total Uptime: \n Hours: **" + uptimehours + "** \n" + "Minutes: **" + uptimeminutes + "** \n \n **Thats it!These stats are updated every minute and more are being added soon. ** "
serverchannel.send(messagetobesent)
while (true) {
setTimeout(function() {
message.edit(messagetobesent)
}, 60000);
}
The bot should grab the support server and channel that I want the message to be sent to by using their ids. Then, it should send a message stored as a variable in that channel. Finally, every minute it will edit that message with the new value of the variable.
TypeError: Cannot read property 'channels' of undefined.
This error actually means that it couldn't find the guild you're trying to get, Are you sure that bot.guilds.get("498548588318556210") actually returns a guild? Maybe bot is defined by another Discord.js client inside your code that's not in the guild you're trying to get? Or is there actually a guild with that ID? Or is your client actually a member of that guild?

How do I make a command with the length of how many arguments are in the command?

This may sound weirdly phrased, but I don't know how else to describe it. I'm trying to make a discord bot with a command where certain people can write javascript code to do things with the bot on the fly, but I don't know how to make it work with multiple spaces. I want it to work with as many spaces as possible or as little spaces as possible, but this only works with ones with exactly 10 spaces.
if(command === '!cmd') {
if(message.author.id != ownerid) {
bot.guilds.get(guildid).channeks.get(generalchan.sned("YOU ARE NOT ALLOWED TO USE THIS COMMAND\nTHIS IS YOUR ONLY WARNING"))
} else if(message.author.id === ownerid) {
eval(messageArray[1] + " " + messageArray[2] + " " + messageArray[3] + " " + messageArray[4] + " " + messageArray[5] + " " + messageArray[6] + " " + messageArray[7] + " " + messageArray[8] + " " + messageArray[9]);
message.delete();
}
}
Let evalStr = ""
For(let element of messageArray){
evalStr += element + " "
}
eval(evalStr)
You'll need to slice out the trailing space character.
But you're taking message.content then splitting each word into an array. Then trying to fuse the array back together adding the spaces back in. You should just delete the first x chars of message. content where x is prefix.length + command and eval the result.
Eval commands are very dangerous. Please make sure you know what you're doing before implementing these.
EDIT: This guide is worth taking a look at and bookmarking.
https://anidiotsguide.gitbooks.io/discord-js-bot-guide/examples/command-with-arguments.html

Returning a concatenated string from a functions' properties in javascript

I'm a total JS beginner. Here is the JsBin link formLetter test should be passing.
TL;DR
This:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender
};
console.log(formLetter("Hermione", "Luna","How are you?"));
Should return:
"Hello Hermione,
How are you?
Sincerely,
Luna"
But instead I get this:
"Hello [object Object],
undefined
Sincerely,
undefined"
Edit
Sorry for the confusion. I'm working on different problems inside one JsBin. This is the correct JsBin with the isolated code.
This is because you are only getting one object passed into the function call. This object contains the information you need in lieu of the named arugments you have provided.
The first argument, recipient being [object Object] tells you that it's an object. undefined means that nothing was passed in their place. This signifies the common pattern of a config or param object being passed to the function call. Because of this, what you have as named arguments should really be property look ups on the object provided as the first argument.
Your function definition should look more like:
var formLetter = function (letter) {
// do something with letter
};
Inside of that function call, you may then hit the properties of the letter object to see if they contain what you need, Doing console.log debugging in dev tools will help track it down.
The line:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender
};
in your example needs one semicolon after "sender", like:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender;
};
Your undefined is related to the use of anidated console.log.
You do:
console.log(longMessage.formLetter("Hermione", "Luna","How are you?"));
and (in the JsBin) you have also:
var longMessage = {
formLetter: function(recipient, sender, msg) {
console.log("Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender);
}
};
In the example of your question you have them corrected.
Double check the code you post, please.
After looking at your test in jsbin, I noticed that in your assert.deepEqual() method you run formLetter(letter) and compares it to the concatenated string you created.
The problem is that formLetter() expects three string values and you send it an object (letter). That's why you get [Object object] in the first location and undefined in the others.
You should run formLetter(letter.recipient, letter.msg, letter.sender) in your assert and it should work properly.

Retrieve returns from another JavaScript file

I've created a HTML file in PAGE directory called Test-Page-1.html. And in the root, I've a JavaScript file called Script.Con.js.
In the html file, I have this script:
(function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
})
/** FORGIVE THE CODE'S CLUMSINESS **/
I want Script.Con.js to get the value returned by the Flush() function. I don't know how to do this, please help me out. Thanks in advance.
You can include var statement before calling IIFE by including () before or following last closing parenthesis to set identifier for value returned by IIFE
<script>
var result = (function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100, // missing `,` here
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
}()); // `result` should be accessible by `Script.Con.js`
</script>
<script src="Script.Con.js"></script>
The way that's written, your Script.Con.js file's code can't call Flush — and neither can anything else, you've used a named function expression to create a function you never keep any reference to. NFEs don't even add the name to the current scope, so nothing can ever refer to that function.
You have a couple of options:
Make it a function declaration instead by removing the () around it, and then have Script.Con.js call it:
function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100 ,
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
}
Then in Script.Con.js:
var order = Flush();
Note that the prompts won't happen until Script.Con.js calls Flush().
Run it immediately and save the result in a variable, then have Script.Con.js use the variable:
var order = (function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100 ,
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
})();
Note the () at the end to actually call it. That will trigger the prompts immediately, and save the result to order. Then your Script.Con.js code would use the order variable directly.
Side Note: The overwhelming convention in JavaScript is that non-constructor functions like this start with a lowercase letter, e.g. flush rather than Flush. (Also a bit confused about the name "flush" but...)
Side Note 2: You were missing a , after id: 10100. Added above.

Twitch Bot in Node JS log system

I'm working on a twitch bot in node.js and using tmi.js https://github.com/Schmoopiie/tmi.js
My problem is with the logging system I created. I think I'm misunderstanding node.js from the ground up here. I need to get the username from the chatter that just typed something.
This is my code:
client.on('chat', function (channel, user, message, self) {
fs.open('logs/' + user +'.txt','r',function(err,fd){
if (err && err.code=='ENOENT')
{
fs.writeFile('logs/' + user +'.txt', '[' + 'GMT' + moment().format('Z ') + moment().format('D.M.YYYY H:mm:ss') + '] ' + user + ': ' + message, function (err) {});
} else {
fs.appendFile('logs/' + user +'.txt', '[' + 'GMT' + moment().format('Z ') + moment().format('D.M.YYYY H:mm:ss') + '] ' + user + ': ' + message + '\n', function(){});
}
});
});
this triggers everytime a user types a message in chat. And I thought the variable "user" would have the value of the chatter that just typed something.
But the value of user is always [object Object]
Am I overlooking something? I can't find a way to get the username of the current chatter.
Thanks for the help guys
I can't say I have any experience with tmi.js, but it appears the user variable you're getting there is an object, not a string. When you try to cast it to a string using +, you get [object Object] by default. Try doing this:
fs.appendFile('logs/' + JSON.stringify(user) +'.txt', '[' + 'GMT' + moment().format('Z ') + moment().format('D.M.YYYY H:mm:ss') + '] ' + JSON.stringify(user) + ': ' + message + '\n', function(){});
or, even better, because you want that just for debugging:
console.log(user);
And check the console. It probably won't be pretty, but at least you'll be able to see what's inside the user variable. Perhaps it will be an object with a username property, and you'll be able to simply use user.username?

Categories

Resources