I know this is a duplicate but it is a specific issue i think.
I am getting an error while performing a slash command: „The application did not respond“.
What I am trying to do is an Slash Command, that can only be performed by someone with the Administrator Role. The command should be give the User role to the mentioned user.
If someone knows a better way to do that or a GitHub Link etc. I would like to see this as well. Anyway - here is my code:
const DiscordJS = require('discord.js');
const { Routes } = require('discord-api-types/v9');
const { Intents, Client, MessageEmbed } = require('discord.js');
const { token, client_id, guild_id, admin_role_id, user_role_id } = require('./config.json')
const client = new DiscordJS.Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
})
client.on('ready', () => {
console.log('The bot is ready')
const guild = client.guilds.cache.get(guild_id)
let commands
if (guild) {
commands = guild.commands
}
else {
commands = client.application?.commands
}
commands?.create({
name: 'user',
description: 'Makes the mentioned member a user.',
requireRoles: true,
options: [{
name: 'user',
description: 'The user the role should be given to.',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.USER
}]
})
})
client.on('interactionCreate, a', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, options } = interaction
if (commandName === 'user') {
const user_id = options.get('user')?.value;
const guild = client.guilds.cache.get(guild_id);
if (!guild) {
return console.log(`Can't find the guild with ID ${server_id}.`);
}
guild.members.fetch(user_id)
.then(member => {
console.log(member.roles.cache)
const embedSuccess = new MessageEmbed()
.setColor('#5ee067')
.setDescription('<#' + user_id + '> was given the <#&' + user_role_id + '> role.');
const embedUserInfo = new MessageEmbed()
.setDescription('Dear <#' + user_id + '>, \n you are able…');
const embedFailure = new MessageEmbed()
.setColor('#ffa2a2')
.setDescription("Could not perform command because the user that requested it doesn't have the required roles to execute it.")
if (interaction.user.roles.cache.has(admin_role_id)) {
const member = interaction.options.getMember('target');
member.roles.add(user_role_id)
interaction.reply({
content: '<#' + user_id + '>',
embeds: [ embedSuccess, embedUserInfo ]
})
}
else {
interaction.reply({
embeds: [ embedFailure ]
})
}
})
.catch(console.error);
}
})
client.login(token)
Thanks.
Related
So I was making welcome system on my discord bot and encountered the problem where my code dosent work (dosent respond) but there is no error.
So i made command to set welcome channel --It Works
I also setted Schema (i using mongoDB) where i will save guildId, ChannelId & RoleID. --Work
Then i have file: welcomer.js which actually need to send the message when user join, but it dosent, i also dont have any errors in console:
SetChannel.js:
async execute(interaction, client, message) {
try {
if(!interaction.member.permissions.has('ADMINISTRATOR')) return interaction.reply('You are not allowed to use this command')
const channel = interaction.options.getChannel('channel')
const role = interaction.options.getRole('role')
Schema.findOne({Guild: interaction.guild.id}, async(err, data) => {
if(data) {
data.Channel = channel.id
data.Role = role.id
data.save()
} else {
new Schema({
Guild: interaction.guild.id,
Channel: interaction.channel.id,
}).save()
}
})
interaction.reply(`${channel} has been set as welcome channel
${role} will be given to the new members when they join the server.`)
//.then(console.log)
.catch(console.error)
}
catch(err) {
console.log(err)
}
}
}
welcomeSchema.js:
const mongoose = require('mongoose')
const Schema = new mongoose.Schema({
Guild: String,
Channel: String,
Role: String,
})
module.exports = mongoose.model('welcome-channel', Schema)
welcomer.js:
//const client = require('../index')
const Schema = require('../database-schema/welcomeSchema')
const { MessageEmbed, Client, Intents, Discord } = require('discord.js')
const allIntents = new Intents(32767);
const client = new Client({intents: [ allIntents ]})
client.on('guildMemberAdd', async (member, guild) => {
Schema.findOne({ Guild: member.guild.id }, async (e, data) => {
if (!data) {
return console.log('No channel to send the message!')
}
const channel = member.guild.channels.cache.get(data.Channel)
let role = member.guild.roles.cache.get(data.Role)
const embed = new MessageEmbed()
.setTitle('Welcome!')
.setColor('BLURPLE')
.setDescription(`Welcome to the server, ${member.tag}! I hope you will have a great time here.`)
.setTimestamp()
channel.send({ embeds: [embed] })
member.role.add()
})
})
I need some help please,
When I click on the button Submit, it doesn't do what I want it to, it doesn't show up with any errors, and the bot doesn't crash so I'm not sure how to fix it.
This has never happened to me before so I'm just wondering I'm someone could point me in the right direction.
Suggest.js :
const { ButtonInteraction, MessageEmbed } = require("discord.js");
const DB = require('../Structures/Handlers/Schemas/SuggestDB');
const { APPLICATIONID } = require("../Structures/config.json")
const Embed1 = require('../Commands/Suggest/suggestion');
module.exports = {
name: "interactionCreate",
/**
*
* #param {ButtonInteraction} interaction
*/
async execute(interaction) {
if(!interaction.isButton()) return;
const { guildId, customId, message } = interaction;
DB.findOne({GuildID: guildId, MessageID: message.id}, async(err, data) => {
if(err) throw err;
if(!data) return interaction.reply({content: "No data was found in the database", ephemeral: true});
const Embed = message.embeds[0];
if(!Embed) return;
switch(customId) {
case "Submit" : {
await guild.channels.cache
.get(APPLICATIONID)
.send({ embeds: [Embed1] });
}
}
})
}
}
Suggestion.js
const { CommandInteraction, MessageEmbed, MessageActionRow, MessageButton, ButtonInteraction }
= require("discord.js");
const DB = require("../../Structures/Handlers/Schemas/SuggestDB");
module.exports = {
name:"suggest",
description: "Suggest",
options: [
{
name: "suggestion",
description: "Describe your suggestion",
type: "STRING",
required: true
}
],
/**
*
* #param {CommandInteraction} interaction
* #param {ButtonInteraction} interaction1
*/
async execute(interaction) {
const { options, guildId, member, user } = interaction;
const Suggestion = options.getString("suggestion");
const Embed1 = new MessageEmbed()
.setColor("AQUA")
.setAuthor(user.tag, user.displayAvatarURL({dynamic: true}))
.addFields(
{name: "Suggestion", value: Suggestion, inline: false}
)
.setTimestamp()
const row = new MessageActionRow();
row.addComponents(
new MessageButton()
.setCustomId("Submit")
.setLabel("Submit")
.setStyle("PRIMARY")
.setEmoji("📩"),
)
try {
const M = await interaction.reply({embeds: [Embed1], components: [row], fetchReply: true});
await DB.create({GuildID: guildId, MessageID: M.id, Details: [
{
MemberID: member.id,
Suggestion: Suggestion
}
]})
} catch (err) {
console.log(err)
}
},
};
Any help is appreciated.
If you need any more information / code files, just reply and I'll will add it straight away.
I've been struggling to get my new Discord bot's command handler to work, While it is seeing the command files (as indicated by its log entry on startup stating the amount of commands it has loaded) it either isn't sending the messages, or it isn't even executing them.
Here's my code:
const { Client, Intents, Collection } = require('discord.js');
const { token, ownerid, statuses, embedColors, prefix } = require('./cfg/config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const fs = require('fs');
const { config } = require('process');
client.commands = new Collection();
const commands = [];
const cmdfiles = fs.readdirSync('./cmds').filter(file => file.endsWith('.js'));
client.once('ready', () => {
console.clear
console.log(`Ready to go, Found ${cmdfiles.length} commands and ${statuses.length} statuses!`)
setInterval(() => {
var status = Math.floor(Math.random() * (statuses.length -1) +1)
client.user.setActivity(statuses[status]);
}, 20000)
}),
client.on("error", (e) => console.log(error(e)));
client.on("warn", (e) => console.log(warn(e)));
// Command Handler
for (const file of cmdfiles) {
const command = require(`./cmds/${file}`);
commands.push(command.data);
}
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) {
embeds: [{
title: ":x: Oopsie!",
color: config.embedColors.red,
description: `Command ${args.[0]} doesn't exist! Run ${config.prefix}help to see the avaliable commands!`,
footer: app.config.footer + " Something went wrong! :("
}];
} else {
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
embeds: [{
title: ":x: Oopsie!",
description: "Command execution failed",
fields: [
{ name: "Error Message", value: `${e.message}` }
],
footer: app.config.footer + " Something went wrong :("
}];
}
message.channel.send
}});
client.login(token);
and the test command is
module.exports = {
name: "test",
description: "does as it implies, dingusA",
async execute(client, message, args) {
message.channel.send("This is a message!");
}
}
You need the GUILD_MESSAGES intent in order to receive messages in guilds.
Add the following intent in your code
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES ]
})
This applies to other things as well eg. DIRECT_MESSAGES for DMs and etc.
i have a problem sending text from yaml. Saving text works but sending does not. Here's the code:
const { Message, MessageEmbed } = require("discord.js")
const { channel } = require('./kanal')
const db = require('quick.db')
module.exports = {
name: "reklama",
guildOnly: true,
description:
"Change guild prefix. If no arguments are passed it will display actuall guild prefix.",
usage: "[prefix]",
run(msg, args, guild) {
if (!guild) {
const guld = new MessageEmbed()
.setTitle("Błąd!")
.setColor("RED")
.setDescription("Tą komende można tylko wykonać na serwerze!")
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(`${msg.author.tag} (${msg.author.id})`, `${msg.author.displayAvatarURL({dynamic: true})}`)
msg.channel.send(guild)
}
const { settings } = client
const prefixArg = args[0]
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null })
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama
let Kanal = client.settings.get(guild.id).Kanał
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField("Treść reklamy:", Reklama)
.addField("Kanał do wysyłania reklam:", Kanal)
msg.channel.send(embed)
}
setInterval(() => {
Kanal.send(`${Reklama}`)
}, 1000)
},catch(e){
console.log(e)
}
}
Here is a part of command handler:
const args = msg.content.slice(length).trim().split(" ")
const cmdName = args.shift().toLowerCase()
const cmd =
client.commands.get(cmdName) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(cmdName),
)
try {
cmd.run(msg, args)
} catch (error) {
console.error(error)
}
})
}
The problem is that when I start the bot, it shows me such an error:
let Reklama = client.settings.get(guild.id).Reklama
^
TypeError: Cannot read property 'id' of undefined
The problem is you don't pass the guild variable to your run method. You call cmd.run(msg, args) but run accepts three parameters.
You can either pass the guild or get it from the msg like this:
module.exports = {
name: 'reklama',
guildOnly: true,
description:
'Change guild prefix. If no arguments are passed it will display actuall guild prefix.',
usage: '[prefix]',
run(msg, args) {
// destructure the guild the message was sent in
const { guild } = msg;
if (!guild) {
const embed = new MessageEmbed()
.setTitle('Błąd!')
.setColor('RED')
.setDescription('Tą komende można tylko wykonać na serwerze!')
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(
`${msg.author.tag} (${msg.author.id})`,
`${msg.author.displayAvatarURL({ dynamic: true })}`,
);
return msg.channel.send(embed);
}
const { settings } = client;
const prefixArg = args[0];
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null });
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama;
let Kanal = client.settings.get(guild.id).Kanał;
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField('Treść reklamy:', Reklama)
.addField('Kanał do wysyłania reklam:', Kanal);
msg.channel.send(embed);
}
setInterval(() => {
Kanal.send(`${Reklama}`);
}, 1000);
},
catch(e) {
console.log(e);
},
};
I'm encountering an error while making a command for my discord.js bot which says UnhandledPromiseRejectionWarning: ReferenceError: client is not defined even tho i defined client in the main bot file so i'm pretty confused the code for the command i'm making:
let ticketGen = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split("");
let ticketStr = "";
for(let i = 0; i < 3; i++) {
ticketStr += ticketGen[Math.floor(Math.random() * ticketGen.length)];
}
return ticketStr;
}
const fsn = require("fs-nextra");
const colors = require("colors");
module.exports = {
name: 'order',
description: 'Ordering something',
aliases: ['o'],
execute(message) {
let order = message.content.substring(8);
let customer = message.author.id
fsn.readJSON("./blacklist.json").then((blacklistDB) => {
let entry = blacklistDB[message.guild.id];
// Checks is server is blacklisted or not.
if(entry === undefined) {
// Gets ticket ID.
const ticketID = generateID();
// Sends ticket information to tickets channel.
client.guilds.cache.get("745409671430668389").channels.get("746423099871985755").send({embed: {
color: 0xFFFFFF,
title: message.author.username,
fields: [{
name: "New Order",
value: `${message.author.username} would like to order something.`,
}, {
name: "Order Description",
value: order,
}, {
name: "Order ID",
value: ticketID,
}, {
name: "Guild Infomation",
value: `This order came from ${message.guild} (${message.guild.id}) in ${message.channel} (${message.channel.id}).`,
}, {
name: "Order Status",
value: "Unclaimed",
}],
timestamp: new Date(),
footer: {
text: "Taco Bot"
}
}}).then((m) => {
m = m.id;
//rest of the code
forgive me if it was an stupid error i'm completely new to coding and was watching youtube videos to learn the code for the main bot file:
const fs = require("fs");
const { prefix, token, ownerID } = require('./config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on("ready", () => {
console.log(`ready!.`);
console.log(token);
// Activities
const activities_list = [
`Serving Tacos | .help`,
`Preparing Orders | .help`
];
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index]);
}, 10000);
});
//Joined Guild
client.on("guildCreate", (guild) => {
console.log(colors.green(`Joined New Guild, ${guild.name}`));
});
//Left Guild
client.on("guildDelete", (guild) => {
console.log(colors.green(`Left Guild, ${guild.name}`));
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
process.on("error", () => {
console.log("Oops something happened!");
});
client.login(token);
There is no need to create a new client, and absolutely no need to pass it in as an additional argument in your execute method. As you have seen in the comments, the issue is that while client is defined in your main bot file, it is not defined in your command's file. Variables defined in one file aren't accessible in all other files, unless you specifically export that variable using module.exports.
But luckily, you don't need to export your client or pass it as a parameter; discord.js conveniently has a message.client property on the message object which allows you to access your client easily. All you need to do to fix your code is add a single line to the top of your execute() method in your command file:
module.exports = {
name: 'order',
description: 'Ordering something',
aliases: ['o'],
execute(message) {
const client = message.client; //<- Line added right here
let order = message.content.substring(8);
let customer = message.author.id
fsn.readJSON("./blacklist.json").then((blacklistDB) => {
let entry = blacklistDB[message.guild.id];
// Checks is server is blacklisted or not.
if(entry === undefined) {
// Gets ticket ID.
const ticketID = generateID();
// Sends ticket information to tickets channel.
client.guilds.cache.get("745409671430668389").channels.get("746423099871985755").send({embed: {
color: 0xFFFFFF,
title: message.author.username,
fields: [{
name: "New Order",
value: `${message.author.username} would like to order something.`,
}, {
name: "Order Description",
value: order,
}, {
name: "Order ID",
value: ticketID,
}, {
name: "Guild Infomation",
value: `This order came from ${message.guild} (${message.guild.id}) in ${message.channel} (${message.channel.id}).`,
}, {
name: "Order Status",
value: "Unclaimed",
}],
timestamp: new Date(),
footer: {
text: "Taco Bot"
}
}}).then((m) => {
m = m.id;
//rest of the code
And that's all! Problem solved. That message.client property is amazingly convenient.
Relevant Resources:
https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=client
I will suggest you to add the client in the command.execute() too, because it is easier to use. So you will have:
try {
command.execute(client, message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
And in every command file you just simply do this.
execute(client, message, args) {
//code
}