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.
Related
The idea of this command is to add a user to the .txt file full of customers info so it can be used by other parts of the bot.
The problem is no matter what i put into the options that pop up here
Command Example
it will always return "undefined" for each option like so.
Example Reply
i think the issue is its not actually returning anything from the interaction when asking for that information inside the execute function. im not quite sure why though.
here is the code in question.
const { SlashCommandBuilder } = require('discord.js');
const fs = require('fs');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('addfrozencustomer')
// command description
.setDescription('Add a frozen customer account/discord')
.addStringOption(option =>
option.setName('id')
.setDescription('The ID of the customer')
.setRequired(true))
.addStringOption(option =>
option.setName('username')
.setDescription('The username of the customer')
.setRequired(true))
.addStringOption(option =>
option.setName('email')
.setDescription('The email of the customer')
.setRequired(true)),
async execute(interaction) {
const { id, username, email } = interaction.options;
const data = `${id}:::${username}:::${email}`;
fs.appendFile('users/frozencustomers.txt', `${data}\n`, (error) => {
if (error) {
console.error(error);
return;
}
console.log('The data was successfully written to the file.');
});
interaction.channel.send(`Successfully added frozen customer:\n ID: ${id}\n User: ${username}\n Email: ${email}`);
}
};
Out of everything i have tried the code above is the closest iv come to getting this to work as intended.
You can't grab interaction options values directly from the interaction.options object, it has seperate methods to grab each type of value, in your case:
const
username = interaction.options.getString("username"),
id = interaction.options.getString("id"),
email = interaction.options.getString("email")
You can read more about this here: https://discordjs.guide/slash-commands/parsing-options.html#command-options
I seem to be having serious trouble sending DM's to all users with a specific role.
Here is my bot code:
bot.on('message', async message => {
members = message.guild.roles.cache.find(role => role.id === "12345678998765").members.map(m => m.user.id);
members.forEach(member_id => {
sleep(5000).then(() => {
message.users.fetch(member_id, false).then((user) => {
user.send("some message");
});
});
});
});
This code gives me the error:
Cannot read properties of null (reading 'roles')
on this line:
members = message.guild.roles.cache.find(role => role.id === ....
However that is not the issue. When I comment out the sleep command to send the message and output the member roles using:
members.forEach(member_id => {
console.log(member_id)
//sleep(5000).then(() => {
// bot.users.fetch(member_id, false).then((user) => {
// user.send("some message");
// });
//});
});
I get a list returned in the console of all the user ID's.. So it must be returning the roles.
How do I send a message to all users with a specific role ID ?? I want to be able to loop through them and put a wait in to reduce the API requests and spam trigger.
To fix your first issue, message.guild will be null in DM. Make sure it isn't DM, or if it has to be, choose a guild with client.guilds.cache.get("id").
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
//...
})
To fix your other issue, you can run GuildMember#send() rather than getting the IDs and fetching the users
bot.on("message", async message => {
let { guild } = message
if (!guild) guild = bot.guilds.cache.get("id")
let members = guild.roles.cache.get("12345678998765").members
// I used .get here because it's getting by ID
members.forEach(member => {
sleep(5000).then(() => member.send("some message"));
});
})
The above code will get all the GuildMembers and loop through every one of them, "sleeping" for 5 seconds (if the sleep parameter is milliseconds) and send the member a DM
bot.on('channelCreate', async channel => {
if (!channel.guild) return;
const fetchedLogs = await channel.guild.fetchAuditLogs({
limit: 1,
type: 'CHANNEL_CREATE',
});
const logbook = channel.guild.channels.cache.get("ChannelID")
const deletionLog = fetchedLogs.entries.first();
if (!deletionLog) return logbook.send(`A channel was updated but no relevant autid logs were found`);
const { executor, user } = deletionLog;
if (user.id) {
logbook.send(`${executor.tag} created a channel`);
} else {
logbook.send(`A channel was created but idk who did.`);
}
});
I am a newbie when it comes to fetching actions through Discord Audit Logs; so I am experimenting and somehow came up with this code. However, when I create a channel, it does not send any messages saying that a channel has been created by #user. I have no idea what my next step will be. All I wanted to do was to know who created the channel.
Discord.JS: v12.2.0
client.on("channelCreate", async channel => {
if (!channel.guild) return false; // This is a DM channel.
const AuditLogFetch = await channel.guild.fetchAuditLogs({limit: 1, type: "CHANNEL_CREATE"}); // Fetching the audot logs.
const LogChannel = client.channels.cache.get("722052103060848664"); // Getting the loggin channel. (Make sure its a TextChannel)
if (!LogChannel) return console.error(`Invalid channel.`); // Checking if the channel exists.
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first(); // Getting the first entry of AuditLogs that was found.
LogChannel.send(`${Entry.executor.tag || "Someone"} created a new channel. | ${channel}`) // Sending the message to the logging channel.
});
If the code I provided is not working, please make sure the bot has access to view AuditLogs.
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()
}
});
I want to, with discord.js, tell if any given message mentions any user on the server.
Message.mentions is what you're looking for: you can either check .users or .members. If there's at least one element in one of these collections, then someone has been mentioned:
client.on('message', message => {
if (message.mentions.members.first()) // there's at least one mentioned user
else // there's no mentioned user
});
Keep a map of users and match with incoming messages
const Discord = require('discord.js')
const client = new Discord.Client()
const map = {}
client.on('message', msg => {
if (msg.content.indexOf('#') !== -1) {
const users = msg.content.match(/#[a-z\d]+/ig)
users.forEach((user) => {
if (map[users.slice(1)]) {
console.log(`${users.slice(1)} mentioned in server`)
}
})
}
})
client.on('ready', () => {
setInterval (function (){
for(u in Bot.users){
map[client.users[u].username] = true
}
}, 10000)
})
client.login('token')