Discord Bot Server Muting - node.js

I'm trying to code a discord bot that server mutes people when i do ".mute #person"
What's wrong with my code?
bot.on('message', msg=>{
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
if(msg.content === ".mute"){
person.setDeaf
}
})
It says "message not defined"

bot.on('message', msg => {...} waits for the event message then passes that information as the variable msg for the function provided.
Inside your function, you refer to message.guild.member but message is undefined (you passed your event information as msg, not message). Change your function parameter to message, so it looks like this:
bot.on('message', message => {...})
That would fix the error you're getting, but I'm not sure that function will actually server mute a user. I think what you want is:
client.on('message', async message => {
if (message.content.startsWith(".mute")) {
let person = message.guild.member(message.mentions.users.first());
await person.edit({mute: true});
}
});
Notice I use message as the parameter for the function, but I put async in front of it because I'm going to be using an asynchronous function. .edit() takes a dictionary of data, see the linked documentation. It is awaited because it is done asynchronously: you call it, then you wait for a response from the server before continuing (to make sure everything happened as expected).
Tested myself, works like a charm.

Related

Discord.js, how to handle error sending private message to user with disabled privacy setting and return right after error?

Is there possible way to handle error that will return right back after error is triggered?
if(command === 'test') {
message.author.send('Dm Test').catch(error => {
message.reply('I failed to send you a private message!')
return;
})
//some code below, should not trigger after sending message error.
The problem is that .catch will respond as last, how to handle this error and immediately return instead of running also code below? I tried to use try { but that didn't work.
message.author.send('👌')
.catch(() => message.reply("Can't send DM to your user!"));
Would like to know if there is another way to handle error. Any help will be much appreciated.
The reason why .catch() executes after the rest of your code is because .send() is asynchronous and returns a Promise. Think of it this way: each time you send a message, discord.js has to send an HTTP request to the Discord API, wait for a response, and then give you the data from the response. That process is not instantaneous and takes some time, which is why using the Promise structure is very useful.
As for the specific problem, you simply want to await the response of your .catch(). This can be done by making the function you are running this code in async. Here is an example:
client.on("messageCreate", async (message) => {
let response = await message.author.send('👌').catch(() => {
message.reply("Can't send DM to your user!"));
return false;
});
// (If error occurred, 'response' will be false)
if (!response) return; // Return if the error occurred
// ... Code for if error did not occur
// (If no error occurred, 'response' will contain sent message)
});
The await keyword will wait until the asynchronous line you are executing has been fulfilled (i.e. until the return value has been obtained or an error has been caught) before continuing on with your code. Note the use of the async keyword. You can only use await within functions marked async.
If you place a return before sending the error message, JavaScript will read that as you're returning the message so if you do the following:
message.author.send('👌')
.catch(() => return message.reply("Can't send DM to your user!"));
you'll have the error message be the final command run and nothing else will follow.
You can use try inside of if & else statement to know if you can dm the person or not.
if(command === 'test') {
try {
message.author.send("Something right here")
} catch {
message.channel.send("I can't dm this person.")
} else {
//something exploration code here
}
}

How to do a 'Report Bug' command with discord.js

I ve been trying to do a report 'bug command'.
This is my code so far:
bot.on('message', async (client, message, args) => {
let parts = message.content.split(" ");
if(parts[0].toLocaleLowerCase() == '!bugreport') {
const owner = client.users.cache.get('567717280759283883');
const query = args.join(" ");
if(!query) return message.channel.send('Bitte schildere den Bug').then(m => m.delete({timeout: 5000}))
const reportEmbed = new Discord.MessageEmbed()
.setTitle('Fehlermeldung')
.setThumbnail(message.guild.iconURL())
.addField('Fehler:', query)
.addField('Server:', message.guild.name, true)
.setFooter(`Gesendet von ${message.author.tag}`, message.author.displayAvatarURL({dynamic: true}))
.setTimestamp();
owner.send(reportEmbed);
}
});
The error code always says that 'content' is undefined, but I do not understand that
Assuming your bot is a Client, it seems you're expecting the message event to pass more arguments than it actually does. Although that would indicate you're trying to read content from undefined, not that content itself is undefined.
The Client#message event allows 1 parameter which is an instance of Message. Change your code to this
bot.on('message', async (message) => {
//code here
})
You probably got confused with message handlers, where you can customize the function to your liking.
The message event only passes the received message according to the discord.js docs.  Your event handler should look more like this at the start:
bot.on('message', async (message) => {
Note this won't completely fix your command, as you'll still be missing the args and client parameters. Here's my best guess as to where to get those from based on how you're using them:
const args = parts.splice(0,1); // gives array of everything after "!bugreport"
const client = bot; // alternatively, replace client with bot in your code

Issue with making a message be reacted to

Hello I have been having an issue with creating a command that will react to any message that includes hello in it. What I want the bot to do is see a sentence such as "Hello how is your day" then pick up hello and react with the waving emoji. The issue is that nothing happens no console error nothing. Please help me fix this error thank you.
My Code:
client.login(token);
client.on('message', async message => {
if (message.content.includes() === 'hello')
await message.react('👋');
});
This is not how the includes method works. You should pass it the string as an argument and it will return a boolean. Try this:
client.login(token);
client.on('message', async message => {
if (message.content.includes('hello'))
await message.react('👋');
});

Unresolved method in WebStorm (discord.js, code works)

I'm wrapping my head around this. Autocompletion does not work .then(r => { HERE }) either.
Kinda starting out with this and would be way easier if it just works (works outside of the promise).
Code runs without any problems as well. delete method is recognized as well but not at that part.
I have this problem in a bigger project as well and it gets me confused.
Trying to find something on the web for a few hours, but couldn't find anything that helps me out. Hope I wasn't blind at some point :P
Whole test source:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", message => {
if (message.content === 'test'){
message.channel.send('something').then(r => r.delete(5000));
}
});
Problem:
If you need to delete command triget message you can use
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", message => {
if (message.content === 'test'){
message.channel.send('something')
message.delete(1000)
.catch(console.error)
}
});
If you use need to delete response message after some time you code must work, but you can try use reply method.
client.on("message", message => {
if (message.content === 'test'){
message.reply('somethink')
.then(msg => {
msg.delete(10000)
})
.catch(console.error);
}
});
Maybe problem in you discord.js version? In v.12 version you need use
msg.delete({ timeout: 10000 })
Just means webstorm can't discern what functions the object will have after the promise resolves. This is because the message create action in discord.js has multiple return types. So it's possible for the message object not to be passed into r, for instance in the event that the message failed to send, possibly by trying to send a message to a channel without the proper permissions.
If you add a check to confirm that r is the same type as message before trying to call .delete() I believe the warning will go away.
You can observe the potential error this highlight is warning you of by removing the bots permission to send messages in a channel, then by sending "test" to that same channel.
Having had the error recently and having found a solution, if for example you want a text channel, by doing a get you can have a text or a voice . so check if the channel instance TextChannel (for my example)
let channel = client.guilds.cache.get(process.env.GUILD_ID).channels.cache.get(config.status_channel);
if (channel instanceof TextChannel) {
await channel.messages.fetch()
}

What's the appropriate use of removeListener in this case?

Bot library for Discord,
bot.on('messageCreate', msg => {
// do some stuff
bot.removeListener('messageCreate', msg);
});
An error I get often is listener must be a function.
messageCreate is fired when a message is received, msg is a reference to the message class, which contains the message id, author, etc.
What I'm trying to get is the bot waiting for a specific reply back from the user, such as Yes or No.
If bot is a Node's EventEmitter, you can use once method instead of on so that it automatically removes the listener after the listener is called once.
bot.once('messageCreate', msg => {
// do some stuff
// you don't need to remove the listener by yourself!
});
To straightly answer your question, the second argument of removeListener must be the listener function that you passed to on.
var listener = msg => {
// do some stuff
bot.removeListener('messageCreate', listener);
};
bot.on('messageCreate', listener);
In discord V12 you can remove the listener like this inside the ready event if you are using some other type of command handler like commando
bot.once("ready", () => {
bot.removeListener("message", client._events.message[0]);
}

Resources