So i want that the bot # the user he is talking to because ${member} (i saw that on youtube) doesnt work and so i want to ask what i have to write so that he writes "Hello #(the users name)..." remember please he is writing that as a dm.
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.on('ready', () => {
console.log('This Bot is online!');
})
client.login(token);
client.on('guildMemberAdd', member => {
member.send('Hello ${member}, welcome to the PotatoHost Server!');
});
The problem isn`t with the member, is with the client.login(), it should always be at the end if the code!
I hope this will help you. have a great day!
Edit:Also, some members have locked dm's, so you should use a try-catch function, and if you got an err send the welcome message in the chat.
A try-catch function works like that:
try{
member.send("message here")
}catch(error){
member.guild.channels.get("here the Id of the channel you want to send the welcome message in").send("message here")
}
if you don't like the idea of sending the message in a channel in your server just put instead:
console.log(error)
I had the same problem then I started, this should help you solve the problem:
client.on("guildMemberAdd", async member => {
const dmErr = false;
try {
await member.send()
} catch (error) {
dmErr = true;
} if (dmErr === true) {
member.guild.channels.get("Id of the channel here").send()
}
});
Related
I'm making a stats checker bot in discord.js v12.0.0 because I don't want to deal with slash commands and intents, just wanted this to be a quick little project that I throw together. But, after coding for a while a command I made didn't work, and I decided to console log msg.content to see if that was the issue. It shows as completely blank when I log msg.content, as well as logging msg itself. NO, I am not running a self bot, I read that doing that can also give this issue.
Images:
Code:
import Discord from 'discord.js';
const client = new Discord.Client();
import fetch from 'node-fetch';
client.on('ready', () => {
console.log(`online`);
});
let lb;
async function fet() {
await fetch("https://login.deadshot.io/leaderboards").then((res) => {
return res.json();
}).then((res) => {
lb = res;
})
}
client.on('message', async msg => {
console.log(msg)
let channel = msg.channel.id;
if (msg.author.id == client.user.id) return;
if (channel != 1015992080897679370) return;
await fet();
let r;
for (var x in lb.all.kills) {
if (msg.content.toLowerCase() == lb.all.kills[x].name.toLowerCase()) {
r = lb.all.kills[x].name;
}
}
if (!r) return msg.channel.send('Error: user not found')
})
client.login(token)
Discord enforced the Message Content privileged intent, since September 1st.
Here's the announcement from Discord Developers server (invite)
Source message: Discord Developers #api-announcements
You can fix this, but you do need to use intents...
const client = new Discord.Client({
ws: {
intents: [Discord.Intents.ALL, 1 << 15]
}
})
You also need to flip the Message Content intent switch in developer portal
It's much better to update to version 13+, v12 is deprecated and is easily broken.
I'm trying to make my bot say a simple message whenever someone tells it 'hello'. Currently, the code of the command itself looks like this:
const { SlashCommandBuilder } = require('#discordjs/builders');
const greeter = "default";
const greetOptions = [
`Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('say hi to Hal!'),
execute(message, args) {
let greeter = message.user.username;
msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
},
};
The code I am using to manage when commands are typed looks as follows:
let prefix = "hal, ";
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length);
const command = args.toLowerCase();
console.log(`${message.author.tag} called ${command}`);
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
When I run it, it throws the error, "Cannot read properties of undefined (reading 'username').
If You want to mention a user you can do ${message.author}. But if you want to say for ex. Hello, Brandon then you need to do ${message.author.username}. The message ${message.author.tag} does not always function and also I recommend you const user = message.mentions.users.first() || message.author or just const user = message.author for short so then you can do ${user.username}. Maybe this might fix the bot failing to respond otherwise if it doesn't tell me.
Fix the first code and change msg.channel.send to message.channel.send.
I am making a command to kick all members from a discord server. Here is my code:
client.on("message", message =>{
if (message.content.startsWith(prefix + "amstronglikeabullinapool")) {
message.channel.send("ok i dont care")
const user = message.member;
var allMembers = message.guild.members
allMembers.kick()
message.channel.send("oki")
}
})
I am getting the error:
allMembers.kick is not a function
You could try fetching all members first, loop through them and kick every member separately.
Example:
const allMembers = await message.guild.members.fetch();
allmembers.forEach(member => {
member.kick()
.catch(error => console.log(error))
});
When I start the bot there comes the Ready message but wehen one of somebody send for example a link into a channel nothing happens. Ther comes no error. I had to reduce the code because of the stackoverflow limit. There were three other parts but they worked. Only these two parts doesnt work.
const Discord = require('discord.js');
const client = new Discord.Client();
const TOKEN = '';
const PREFIX = '!';
//ready
client.once('ready', () => {
console.log('Ready!');
});
//welcome
client.on('guildMemberAdd', member => {
console.log('User joind');
});
//commands
client.on('message', message => {
if (!message.content.startsWith(PREFIX)) return;
if (message.author.bot) return;
if (!message.guild) return;
}
//delete links
else if (message.content.includes('https://')) {
console.log('Link!!!');
}
});
client.login(TOKEN);
Most likely the message does not have the required prefix, thus the the function just returns.
When a user joins the server, the bot sends a welcome message, i want to take that welcome message's ID and make the bot delete it if the users leaves after he joins. I tried to save the message's id in a variable and make the bot delete the message when the user leaves but without success. I already took a look at the docs, but I really can't understand how to make it.
Define an object to hold the welcome messages by guild and user. You may want to use a JSON file or database (I'd highly recommend the latter) to store them more reliably.
When a user joins a guild...
Send your welcome message.
Pair the the message's ID with the user within the guild inside of the object.
When a member leaves the guild...
Fetch their welcome message.
Delete the message from Discord and the object.
Example setup:
const welcomeMessages = {};
client.on('guildMemberAdd', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.send(`Welcome, ${member}.`);
if (!welcomeMessages[member.guild.id]) welcomeMessages[member.guild.id] = {};
welcomeMessages[member.guild.id][member.id] = message.id;
} catch(err) {
console.error('Error while sending welcome message...\n', err);
}
});
client.on('guildMemberRemove', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.fetchMessage(welcomeMessages[member.guild.id][member.id]);
if (!message) return;
await message.delete();
delete welcomeMessages[member.guild.id][member.id];
} catch(err) {
console.error('Error while deleting existing welcome message...\n', err);
}
});
To do this you would have to store the id of the welcome message and the user that it is tied to (ideally put this in an object). And when the user leaves you would use those values to delete that message.
Example code:
const Discord = require('discord.js');
const client = new Discord.Client();
const welcomeChannel = client.channels.find("name","welcome"); // Welcome is just an example
let welcomes = [];
client.on('message', (message) => {
if(message.channel.name === 'welcome') {
const welcomeObj = { id: message.id, user: message.mentions.users.first().username };
welcomes.push(welcomeObj);
}
});
client.on('guildMemberRemove', (member) => {
welcomes.forEach(welcome, () => {
if(welcome.user === member.user.username) {
welcomeChannel.fetchMessage(welcome.id).delete();
}
});
});
This only works if the welcome message includes a mention to the user so make sure that's in the welcome message.
Also I can't test this code myself at the moment so let me know if you encounter any problems.