As title says, I'm trying to write some code that will ban a user if their message is replied to with the word ban. I think the way im getting the id of the original message is wrong but I'm not sure how to implement it otherwise. The error im getting is "TypeError: Cannot read properties of undefined (reading 'id')"
client.on("messageCreate", (message) => {
if (message.content == "ban" && message.type == 'REPLY') {
const member = message.reference.author.id;
message.guild.members.ban(member).then(console.log)
.catch(console.error);
}
})
Change your current code to:
const client = new Discord.Client({ intents: [ "GUILDS",
"GUILD_MESSAGES",
"GUILD_MEMBERS" ] });
client.on("messageCreate", (message) => {
if (message.content == "ban" && message.type == 'REPLY') {
const member = message.author.id;
message.guild.members.ban(member).then(console.log)
.catch(console.error);
}
})
To access the Server Members Intent:
Go to discord/developers
In Applications, click your project/bot
Click the BOT section
Scroll down until you see the Privileged Gateway Intents
Find for the Server Members Intent
Enable it
Now try the script again
I'm suggest you do like this:
const client = new Discord.Client({ intents: [ "GUILDS",
"GUILD_MESSAGES",
"GUILD_MEMBERS" ] });
client.on("messageCreate", async (message) => {
if (message.content == "ban" && message.reference) {
const msg = await message.channel.messages.fetch(message.reference.messageId);//cache the message that replied to
const member = msg.member//cache the author of replied to
member.ban(member).then(console.log)//ban the user
.catch(console.error);
}
})
Related
client.on('messageCreate', message => {
if(message.author.bot) return;
if(message.channel.id == "1012047542462185572"){
var messageContent = message.content;
client.channels.cache.get('1012048291111903292').send(messageContent)
}
});
This code can only send a message from a channel to another though a bot but it's only the bot speaking, I want to add which user is speaking. How can i implement this?
Use this
client.on('messageCreate', async (message) => {
if(message.author.bot) return;
if(message.channel.id == "1012047542462185572") {
const { content, member, author } = message
const channel = await client.channels.fetch('1012048291111903292')
// for nickname:
const str = `**${member.displayName}:**\n${content}`
// for username and tag
const str = `**${author.tag}:**\n${content}`
// you may only use one of these. when you
// adapt it to your own code, remove one of
// these "str", keep the one you want
channel.send({ content: str })
}
})
My discord.js version is v13, and it's not sending a message, nor is it giving an error in the console so that I can try to figure out what is wrong with it.
The code itself is over 4000 lines of code, so I tried putting it in a separate script to only test one function (which is the ping function), yet still nothing.
If you ask, this the async is only apart of another function in the main script where I use await a lot.
const Discord = require('discord.js');
const client = new Discord.Client({ intents: [ 'DIRECT_MESSAGES', 'GUILD_MESSAGES' ] });
const config = require("./config.json");
client.on("ready", () => {
console.log(`Main script ready! Currently in ${client.guilds.size} servers!`);
client.user.setActivity("Using a test script");
});
client.on('messageCreate', async message => {
if(message.author.bot) return;
if(message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase()
if (message.channel.type == "dm") return;
if(command === "ping") {
const m = await message.channel.send("Loading...")
m.edit(`Pong! ${m.createdTimestamp - message.createdTimestamp}ms. API ${Math.round(client.ping)}ms`)
}
});
client.login(config.token);
You are missing Intents.FLAGS.GUILDS.
Change:
const client = new Discord.Client({ intents: [ 'DIRECT_MESSAGES', 'GUILD_MESSAGES' ] });
to
const client = new Discord.Client({ intents: [ 'GUILDS', 'DIRECT_MESSAGES', 'GUILD_MESSAGES' ] });
Just had a simple question, I have some moderation slash commands on discord bot running on Discord.js V13, and I need to get the user ID of the person who runs the slash command. So I can then check for the permissions of the user on the guild to make sure he has the Ban_Members permission per example. And also how do I get the guild ID of where the slash command was executed
Thanks! If I wasn't clear feel free to ask me to clarify something
The code I tried
client.ws.on("INTERACTION_CREATE", async (interaction) => {
if (interaction.data.component_type) return;
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command == "mute") {
const guildId = interaction.guildId;
console.log(guildId);
// client.api.interactions(interaction.id, interaction.token).callback.post({
// data: {
// type: 4,
// data: {
// embeds: [muteembed],
// ephemeral: "false",
// },
// },
// });
}
});
And I just receive undefined in the console log
Something else I tried
client.on("interactionCreate", async (interaction) => {
if (interaction.data.component_type) return;
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command == "mute") {
const guildId = interaction.guildId;
console.log(guildId);
// client.api.interactions(interaction.id, interaction.token).callback.post({
// data: {
// type: 4,
// data: {
// embeds: [muteembed],
// ephemeral: "false",
// },
// },
// });
}
});
And I get this error:
if (interaction.data.component_type) return;
^
TypeError: Cannot read properties of undefined (reading 'component_type')
its usually
interaction.user.id
interaction.member.id
The two things you need is a user and a guild. Make sure you check there is a guild, otherwise things will go wrong.
if(!interaction.guild) return; // Returns as there is no guild
var guild = interaction.guild.id;
var userID = interaction.user.id;
so I made an event handler for my discord bot so that the index.js file would be neat. But for some reason the welcome message that I made whenever someone joins the server doesn't work.
Here's my event handler code:
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, Discord, client));
} else {
client.on(event.name, (...args) => event.execute(...args, Discord, client));
}
}
And Here's my welcome message code:
module.exports = {
name: 'welcome',
once: false,
execute(Discord, client) {
const welcomechannelId = '753484351882133507' //Channel You Want to Send The Welcome Message
const targetChannelId = `846341557992292362` //Channel For Rules
client.on('guildMemberAdd', (member) => {
let welcomeRole = member.guild.roles.cache.find(role => role.name === 'Umay');
member.roles.add(welcomeRole);
const channel = member.guild.channels.cache.get(welcomechannelId)
const WelcomeEmbed = new Discord.MessageEmbed()
.setTitle(`Welcome To ${member.guild.name}`)
.setThumbnail(member.user.displayAvatarURL({dynamic: true, size: 512}))
.setDescription(`Hello <#${member.user.id}>, Welcome to **${member.guild.name}**. Thanks For Joining Our Server.
Please Read ${member.guild.channels.cache.get(targetChannelId).toString()}, and assign yourself some roles at <#846341532520153088>. You can chat in <#753484351882133507> and talk with other people.`)
// You Can Add More Fields If You Want
.setFooter(`Welcome ${member.user.username}#${member.user.discriminator}`,member.user.displayAvatarURL({dynamic: true, size: 512}))
.setColor('RANDOM')
member.guild.channels.cache.get(welcomechannelId).send(WelcomeEmbed)
})
}
}
I get no error, but whenever someone joins the server, he/she won't be given the role and the welcome message doesn't appear. I put the welcome message code on an events folder that the event handler is handling. Can anyone help?
The issue lies within the welcome code.
In the handler code you have the following line:
client.on(event.name, (...args) => event.execute(...args, Discord, client));
This triggers the client on the name property set in the welcome code.
You currently have it set to welcome, which is not a valid event.
The bot is now listening for a welcome event, which will never happen.
First course of action is setting the name property to guildMemberAdd like this:
module.exports = {
name: 'guildMemberAdd',
//the rest of the code
Then you have another issue.
Within the welcome code you have client.on() again.
This will never work, unless by some incredibly lucky chance 2 people join within a millisecond of each other, but even then you'll only have 1 welcome message.
Removing the following:
client.on('guildMemberAdd', (member) => {
//code
})
will fix that issue.
Then the last thing to do is having the member value being imported correctly.
We do this by changing the following line:
execute(Discord, client) {
to:
execute(member, Discord, client) {
//code
The resulting code will look like this:
module.exports = {
name: 'guildMemberAdd',
once: false,
execute(member, Discord, client) {
const welcomechannelId = '753484351882133507' //Channel You Want to Send The Welcome Message
const targetChannelId = `846341557992292362` //Channel For Rules
let welcomeRole = member.guild.roles.cache.find(role => role.name === 'Umay');
member.roles.add(welcomeRole);
const channel = member.guild.channels.cache.get(welcomechannelId)
const WelcomeEmbed = new Discord.MessageEmbed()
.setTitle(`Welcome To ${member.guild.name}`)
.setThumbnail(member.user.displayAvatarURL({dynamic: true, size: 512}))
.setDescription(`Hello <#${member.user.id}>, Welcome to **${member.guild.name}**. Thanks For Joining Our Server.
Please Read ${member.guild.channels.cache.get(targetChannelId).toString()}, and assign yourself some roles at <#846341532520153088>. You can chat in <#753484351882133507> and talk with other people.`)
// You Can Add More Fields If You Want
.setFooter(`Welcome ${member.user.username}#${member.user.discriminator}`,member.user.displayAvatarURL({dynamic: true, size: 512}))
.setColor('RANDOM')
member.guild.channels.cache.get(welcomechannelId).send(WelcomeEmbed)
}
}
Happy coding!
I encounter error "TypeError: Cannot read property 'client' of undefined" while writing my command in i think its from this line did i write it correctly? (i'm not quite sure since i'm new to coding and was getting help from a friend) I'm using discord v12 btw
if(client.guilds.cache.get(order.guildID).client.me.hasPermission("CREATE_INSTANT_INVITE")) {
// Send message to cook.
message.reply(`Order has been sent to ${client.guilds.cache.get(order.guildID).name}`);
// Get invite.
}else {
// Bot delivers it's self.
client.channels.cache.get(order.channelID).send(`${client.users.cache.get(order.userID)}, Here is your taco that you ordered. Remember you can do \`.tip [Amount]\` to give us virtual tips, and \`.feedback [Feedback]\` to give us feedback on how we did. ${order.imageURL}`);
// Logs in console.
console.log(colors.green(`The bot did not have the Create Instant Invite Permissions for ${client.guilds.get(order.guildID).name}, so it delivered the taco itself.`));
}
if it was not the problem the full code for the command is here:
const { prefix } = require('../config.json');
const Discord = require('discord.js');
const fsn = require("fs-nextra");
const client = new Discord.Client();
const colors = require("colors");
module.exports = {
name: 'deliver',
description: 'Deliverying an order',
args: 'true',
usage: '<order ID>',
aliases: ['d'],
execute(message) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
if (message.member.roles.cache.find(r => r.id === '745410836901789749')) {
if(message.guild.channels.cache.find(r => r.id === '746423099871985755')) {
fsn.readJSON("./orders.json").then((orderDB) => {
let ticketID = args[1];
let order = orderDB[ticketID];
// If the order doesn't exist.
if(order === undefined) {
message.reply(`Couldn't find order \`${args[1]}\` Try again.`);
return;
}
// Checks status.
if (order.status === "Ready") {
// Delete ticket from database.
delete orderDB[ticketID];
// Writes data to JSON.
fsn.writeJSON("./orders.json", orderDB, {
replacer: null,
spaces: 4
}).then(() => {
// If bot has create instant invite permission.
if(client.guilds.cache.get(order.guildID).client.me.hasPermission("CREATE_INSTANT_INVITE")) {
// Send message to cook.
message.reply(`Order has been sent to ${client.guilds.cache.get(order.guildID).name}`);
// Get invite.
}else {
// Bot delivers it's self.
client.channels.cache.get(order.channelID).send(`${client.users.cache.get(order.userID)}, Here is your taco that you ordered. Remember you can do \`.tip [Amount]\` to give us virtual tips, and \`.feedback [Feedback]\` to give us feedback on how we did. ${order.imageURL}`);
// Logs in console.
console.log(colors.green(`The bot did not have the Create Instant Invite Permissions for ${client.guilds.get(order.guildID).name}, so it delivered the popsicle itself.`));
}
}).catch((err) => {
if (err) {
message.reply(`There was an error while writing to the database! Show the following message to a developer: \`\`\`${err}\`\`\``);
}
});
}else if(order.status === "Unclaimed") {
message.reply("This order hasn't been claimed yet. Run `.claim [Ticket ID]` to claim it.");
}else if(order.status === "Claimed") {
if(message.author.id === order.chef) {
message.reply("You haven't set an image for this order! yet Use `.setorder [Order ID]` to do it.");
}else {
message.reply(`This order hasn't been set an image yet, and only the chef of the order, ${client.users.get(order.chef).username} may set this order.`);
}
}else if(order.status === "Waiting") {
message.reply("This order is in the waiting process right now. Wait a little bit, then run `.deliver [Order ID] to deliver.");
}
});
}else {
message.reply("Please use this command in the correct channel.");
console.log(colors.red(`${message.author.username} used the claim command in the wrong channel.`));
}
}else {
message.reply("You do not have access to this command.");
console.log(colors.red(`${message.author.username} did not have access to the deliver command.`));
}
}
}
You're not required to add client while checking for the client's permissions.
You can simply use the following to check your client's permissions:
if(client.guilds.cache.get(order.guildID).me.hasPermission("CREATE_INSTANT_INVITE")) {
// code here
}