I'm coding a moderation bot in Discord.js v13, and for the mute, kick, warn and ban commands I need to check user permissions. However, my code fails to compile: "Cannot find name 'member'". I've checked the documentation and I've used the exact same method shown.
Here is my code, the error is in line 67. I've written this in TypeScript, however this should not have any effect on the error.
import { User, Permissions } from "discord.js";
import { SlashCommandBuilder } from "#discordjs/builders";
import mongoose from "mongoose";
import punishmentSchema from "./schemas/punishment-schema";
const config = require("./config.json");
const client = new Discord.Client({
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MEMBERS
]
});
client.on("ready", async () => {
console.log("Ready for your orders, boss!");
await mongoose.connect(`${config.mongodb_uri}`, {
keepAlive: true,
});
const guildId = "868810640913989653";
const guild = client.guilds.cache.get(guildId);
let commands;
if(guild) {
commands = guild.commands;
} else {
commands = client.application?.commands;
}
commands?.create({
name: "ping",
description: "Shows the bot's latency.",
});
commands?.create({
name: "help",
description: "Lists all commands and shows their usage.",
});
commands?.create({
name: "mute",
description: "Allows moderators to mute users.",
});
commands?.create({
name: "ban",
description: "Allows moderators to ban users.",
});
});
client.on("interactionCreate", async (interaction) => {
if(!interaction.isCommand()) return;
const { commandName, options } = interaction;
if(commandName === "ping") {
interaction.reply({
content: `Current latency: \`\`${client.ws.ping}ms\`\``,
ephemeral: false,
})
} else if(commandName === "help") {
interaction.reply({
content: `**__List of available commands:__**\n\n**/ping** Shows the bot's latency.\n**/help** Guess what this one does :thinking:\n**/cases** Allows non-moderators to check their punishment history.\n\n**/warn {user} [reason]** Applies a warning to a user. :shield:\n**/kick {user} [reason]** Kicks a user from the server. :shield:\n**/mute {user} [duration] [reason]** Kicks a user from the server. :shield:\n**/mute {user} [duration] [reason]** Mutes a user. :shield:\n**/ban {user} [duration] [reason]** Bans a user from the server. :shield:\n**/history {user}** Shows the punishment history of a user. :shield:`,
ephemeral: false,
})
} else if(commandName === "mute") {
if (member.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {
console.log('test if kick');
}
} else if(commandName === "mute") {
}
});
client.login(config.token);```
According to docs, interaction object, should have member property. Try to get it with interaction.member or const { commandName, options, member } = interaction;
Related
I get this error when the command executed the command is an unmute command
and my handler is a slash command
when i set the the member as member type in options its work fine but
i want it with ID
if anyone have a solutions and thx
if(target.roles.cache.has(muterole)) {
^
TypeError: Cannot read properties of undefined (reading 'cache')
this the command :
const { MessageEmbed, CommandInteraction } = require("discord.js");
module.exports = {
name: "unmute",
description: "Unmute a Member",
permission: "MANAGE_MESSAGES",
options: [
{
name: "member",
description: "Member ID",
required: true,
type: "STRING"
},
{
name: "reason",
description: "provide unmute reason",
required: true,
type: "STRING"
}
],
/**
*
* #param {CommandInteraction} interaction
*/
async execute(interaction) {
const { guild, channel, member, options } = interaction;
const target = options.getString("member");
const reason = options.getString("reason");
const logchannel = guild.channels.cache.get("877754209016086588");
const muterole = guild.roles.cache.get("944200095040167946");
console.log(target);
const logembed = new MessageEmbed()
.setColor("AQUA")
.setAuthor({ name: `${member.user.tag}`, iconURL: `${member.user.avatarURL({ dynamic: true, size: 512 })}` })
.setDescription(`
${target} got unmuted
by : ${member}
reason : ${reason}
`)
.setTimestamp();
const response = new MessageEmbed()
.setDescription(`
${target} unmuted
`);
if(target.roles.cache.has(muterole)) {
await target.roles.remove(muterole);
await interaction.reply({embeds: [response], ephemeral: true});
await logchannel.send({
content: `${member}`,
embeds: [logembed]
});
} else {
await interaction.reply({content: `${target} is not muted`, ephemeral: true});
}
}
}
USER type supports Snowflake Ids, User Mentions & Member Mentions.
You can add type: "USER" and use
const member = interaction.options.getMember("target"); // for a GuildMember
const user = interaction.options.getUser("target"); // for a User
Once again, it supports user IDs and mentions.
Using a string for fetching a member/user isn't efficient because if the ID provided is invalid, the bot returns null and might lead to a crash.
I've created a simple slash command. It works on the only guild. before that, I was using v12. Now I wanna switch to v13.
Now how can I make these global slash commands?
Code
client.on ("ready", () => {
console.log(`${client.user.tag} Has logged in`)
client.user.setActivity(`/help | ${client.user.username}`, { type: "PLAYING" })
const guildId = "914573324485541928"
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application.commands
}
commands.create({
name: 'ping',
description: 'Replies with pong'
})
commands.create({
name: 'truth',
description: 'Replies with truth'
})
});
client.on('interactionCreate', async (interaction) => {
if(!interaction.isCommand()){
return
}
const { commandName, options } = interaction
if (commandName === 'ping'){
interaction.reply({
content: 'pong'
})
}
```
I'm new in v13 so please explain it simply :|
Simply change the guild declaration. Your code checks if guild is truthy, and uses the guild if it is. Otherwise, it will use global commands
const guild = null
// any falsy value is fine (undefined, false, 0, '', etc.)
In my Discord.JS bot, I have multiple commands setup (ping, beep, etc.) but Discord only recognizes "ping". I have tried multiple setups, and all are the same.
Here is my code:
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName: command } = interaction;
if (command === 'ping') {
await interaction.reply('Pong!');
} else if (command === 'beep') {
await interaction.reply('Boop!');
} else if (command === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (command === 'user-info') {
await interaction.reply(`Your username: ${interaction.user.username}\nYour ID: ${interaction.user.id}`);
}
});
client.login(token);
And here is Discords command view when "/" is enter
As you can see, ping is the only thing being recognized by discord.
It is also worth noting the ‘ping’ command has a description which the original description I setup, so it seems like issue is that Discord is not updating the commands each time the script changes. But, I don’t know how to resolve that issue.
It seems like you only registered the ping command. You have to register each slash command individually.
I guess you registered the slashcommand some tile earlier, and have not removed it since. You are only responding in your code example to slashcommands, but you have to create them in the first hand.
Check here on how to do that.
it may take up to one hour to register a global command tho, so be patient. If you are fine, with slashcommands for one guild only, you can also only create guildCommands. These are up and running within a view minutes (under 10minutes max)
Here is a simple command, with which you can update the slashcommands (this is staright from the docs)
client.on('messageCreate', async message => {
if (!client.application?.owner) await client.application?.fetch();
if (message.content.toLowerCase() === '!deploy' && message.author.id === client.application?.owner.id) {
const data = [
{
name: 'ping',
description: 'Replies with Pong!',
},
{
name: 'pong',
description: 'Replies with Ping!',
},
];
const commands = await client.application?.commands.set(data);
console.log(commands);
}
});
NOTE: you have to be running the master branch of discord.js (aka Discord.js V13). If you have not installed it yet, you can install it by running: npm install discord.js#latest. Make sure, you have uninstalled the "normal" discord.js dependency beforehand, by running npm uninstall discord.js.
If you are not sure what version you currently have installed, simply run npm list
This worked for me, the idea is to render each command separately.
I also went for some hardcoded configs: guild_id & client_id (to win some time in dev mode)
const { Client, Collection, Intents } = require('discord.js');
const { token, client_id, guild_id } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('messageCreate', async message => {
if (!client.application?.owner) await client.application?.fetch();
// => client_id was just a quick fix, the correct value should be the id of the guild owner(s)
if (message.content.toLowerCase() === '!deploy' && message.author.id === client_id) {
const data = [
{
name: 'ping',
description: 'Replies with Pong!',
},
{
name: 'foo',
description: 'Replies with bar!',
},
{
name: 'chicken',
description: 'Replies with sticks!',
},
];
// same here, guild_id should also be replaced by the correct call to the idea number, just as client_id in this code!
for (let i = 0; data.length > i; i++) {
await client.guilds.cache.get(guild_id)?.commands.create(data[i]);
}
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = interaction.commandName;
if (command === 'ping') {
await interaction.reply('pong')
} else if (command === 'foo') {
await interaction.reply('bar')
} else if (command === 'chicken') {
await interaction.reply('nuggets')
}
});
client.login(token);
Hello I am having a bit of an issue with my Discord ticketing system and it is making me really confused... It does not work when it creates the channel of the ticketing system and it is really confusing me...
code:
Open ticket command:
const Discord = require('discord.js')
module.exports = {
name: 'ticket',
description: "opens a ticket",
execute(message, args){
const user = message.author.id;
const name = "ticket-" + user;
if(message.guild.channels.cache.find(ch => ch.name == name)){
message.channel.send("You have already opened a ticket!")
}else{
message.guild.channels.create(name).then((chan)=>{
chan.updateOverwrite(message.guild.roles.everyone, {
SEND_MESSAGES: false,
VIEW_CHANNEL: false
})
chan.updateOverwrite(user,{
SEND_MESSAGES: true,
VIEW_CHANNEL: true
})
message.channel.send("I have created a ticket for you! Please go to the channel at the top of the server, Only you will have access to it and it will be called ticket(id)");
chan.send("Support will be here shortly").then((m)=>{
m.pin()
})
})
}
}
}
close ticket command (this is were the error is):
const Discord = require('discord.js');
module.exports = {
name: 'endticket',
description: "ends the ticket",
execute(client, message, args){
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send("Only a moderator can end a ticket!")
if(message.member.hasPermission("ADMINISTRATOR")) message.channnel.delete()
}
}
console error:
TypeError: Cannot read property 'delete' of undefined
I dont understand what is going wrong...
thank you.
When I used this code to let my bot join my voicechannel, it didnt work, he keeps saying that I am not in a voicechannel, can someone help me because when I run the command I get no error or something.
exports.run = async (client, message) => {
const voiceChannel = message.member.voiceChannel;
if (!message.member.voiceChannel) { return message.channel.send("You are not in a voice channel, Don't force me to be lonely!"); }
const permissions = message.member.voiceChannel.permissionsFor(message.guild.me);
if (permissions.has("CONNECT") === false) { return message.channel.send(":x: I do not have enough permissions to connect to your voice channel. I am missing the Connect permission."); }
if (permissions.has("SPEAK") === false) { return message.channel.send("Wow. Invite me to play music for you, yet I can't speak in the channel. You're more heartless than my owner. Give me the channel permission to speak and then come back and invite me."); }
message.member.voiceChannel.join();
return message.channel.send(`Now tuned into: ${message.member.voiceChannel}. Ready and awaiting orders!`);
};
exports.conf = {
enabled: true,
runIn: ["text"],
aliases: [],
permLevel: 0,
botPerms: [],
requiredFuncs: [],
};
exports.help = {
name: "join",
description: "Joins the VC that you are in.",
usage: "",
usageDelim: "",
};