When I execute the command in discord the bot reply's with a button that says "Subscribe!", once you click it, about 3 seconds later it just says "Interaction Failed" with no console error. I have been looking at this for an hour now and trying to figure it out myself, but I've gotten past that point and I need help.
sub-yt.js;
module.exports = {
data: {
name: "sub-yt",
},
async execute(interaction, client) {
await interaction.reply({
content: `https://youtube.com/duanetv`,
});
},
};
interactionCreate.js;
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
if (interaction.isChatInputCommand()) {
const { commands } = client;
const { commandName } = interaction;
const command = commands.get(commandName);
if (!command) return;
try {
await command.execute(interaction, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `interactionCreate has failed.`,
ephemeral: true,
});
}
} else if (interaction.isButton()) {
const { buttons } = client;
const { customId } = interaction;
const button = buttons.get(customId);
if (!button) return new Error("Button failed.");
try {
await button.execute(interaction, client);
} catch (err) {
console.error(err);
}
}
},
};
handleComponents.js;
const { readdirSync } = require("fs");
module.exports = (client) => {
client.handleComponent = async () => {
const componentFolders = readdirSync(`./src/components`);
for (const folder of componentFolders) {
const componentFiles = readdirSync(`./src/components/${folder}`).filter(
(file) => file.endsWith(".js")
);
const { buttons } = client;
switch (folder) {
case "buttons":
for (const file of componentFiles) {
const button = require(`../../components/${folder}/${file}`);
buttons.set(button.data.name, button);
}
break;
default:
break;
}
}
};
};
Related
Index.js
const Discord = require("discord.js");
const client = new Discord.Client({ disableMentions: 'everyone' });
require('dotenv').config();
const Eco = require("quick.eco");
client.eco = new Eco.Manager();
client.db = Eco.db;
client.config = require("./config");
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
const fs = require("fs");
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err);
files.forEach(f => {
if (!f.endsWith(".js")) return;
const event = require(`./events/${f}`);
let eventName = f.split(".")[0];
client.on(eventName, event.bind(null, client));
});
});
fs.readdir("./commands/", (err, files) => {
if (err) return console.error(err);
files.forEach(f => {
if (!f.endsWith(".js")) return;
let command = require(`./commands/${f}`);
client.commands.set(command.help.name, command);
command.help.aliases.forEach(alias => {
client.aliases.set(alias, command.help.name);
});
});
});
client.login(process.env.TOKEN);
Message.js
const { MessageEmbed } = require('discord.js');
const fs = require('fs');
let visitor = require('../database/visitor.json');
let level = require('../database/level.json');
let place = require('../database/place.json');
let money = require('../database/money.json');
module.exports = async (client, message) => {
if (message.content === "market") {
message.reply(`yup, what?`);
}
if(!visitor[message.author.id]){
visitor[message.author.id] = {
totalvis: 0,
totalbuyer: 0
};
}
if(!level[message.author.id]){
level[message.author.id] = {
level: 1,
exp: 0
};
}
if(!place[message.author.id]){
place[message.author.id] = {
pla: "Hongria"
};
}
if(!money[message.author.id]){
money[message.author.id] = {
balance: 20
};
}
if(level[message.author.id].exp > 300) {
let amount = Math.floor(Math.random() * 60) + 20;
money[message.author.id].balance = money[message.author.id].balance + amount;
level[message.author.id].level++;
level[message.author.id].exp = 0;
let embed = new MessageEmbed()
.setTitle(`${message.author.username} Level Up`)
.addField(`Rewards`, `+ ${amount} Money`)
.setColor("#E5E5E5")
.setTimestamp()
message.channel.send(embed);
}
fs.writeFile('./database/visitor.json', JSON.stringify(visitor, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/level.json', JSON.stringify(level, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/place.json', JSON.stringify(place, null, 2), (err) => {
if (err) console.log(err);
});
fs.writeFile('./database/money.json', JSON.stringify(money, null, 2), (err) => {
if (err) console.log(err);
});
if (!message.guild || message.author.bot) return;
if (message.channel.id === client.config.countChannel) require("../counter")(message, client);
client.prefix = client.db.fetch(`prefix_${message.guild.id}`) ? client.db.fetch(`prefix_${message.guild.id}`) : client.config.prefix;
if (!message.content.startsWith(client.prefix)) return;
let args = message.content.slice(client.prefix.length).trim().split(" ");
let commandName = args.shift().toLowerCase();
let command = client.commands.get(commandName) || client.commands.get(client.aliases.get(commandName));
if (!command) return;
client.ecoAddUser = message.author.id;
command.execute(client, message, args);
};
Command.js
const { MessageEmbed } = require("discord.js");
const fs = require('fs');
exports.execute = async (client, message, args) => {
if (!client.config.admins.includes(message.author.id)) return;
message.channel.send("**Rebooting system..**").then(m => {
setTimeout(() => {
m.edit("**Wait a sec...**").then(ms => {
setTimeout(() => {
ms.edit("**Done.**")
}, 3000)
})
}, 3000);
})
.then(message => process.exit())
.then(() => client.login(process.env.TOKEN))
}
exports.help = {
name: "reboot",
aliases: ["rb"],
usage: `reboot`
}
I use Discord.js version 12.5.3, my discord bot status is online, but if I try some command, my bot not send any message but in console, no errors. I used to be able to use this method, but now I want to try to make a discord bot again, and I use the same code without changing anything, but now my bot can't send any messages
I turn Privileged Gateway Intents in Discord Developer Portal, and it work!
(sry for my English)
I just want to make a simple reaction message, connection to vocal where user use one word as "exemple" in this "it is an exemple", and play one song.mp3, after the bot deconnect when he finish this song.mp3.
This is my index.js
const { Client, VoiceChannel, Intents } = require('discord.js');
const client = new Client({ intents: 32767 });
const dotenv = require('dotenv'); dotenv.config();
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
entersState,
StreamType,
AudioPlayerStatus,
VoiceConnectionStatus,
} = require ('#discordjs/voice');
const { createDiscordJSAdapter } = require ('./?');
const player = createAudioPlayer();
client.login(process.env.DISCORD_TOKEN);
function playSong() {
const resource = createAudioResource('./music/try.mp3', {
inputType: StreamType.Arbitrary,
});
player.play(resource);
return entersState(player, AudioPlayerStatus.Playing, 5e3);
};
client.on('ready', async () => {
console.log('Discord.js client is ready!');
try {
await playSong();
console.log('Song is ready to play!');
} catch (error) {
console.error(error);
}
});
async function connectToChannel(channel = VoiceChannel) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: createDiscordJSAdapter(channel),
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
};
client.on('messageCreate', async (message) => {
if (!message.guild) return;
if (message.content === '-join') {
const channel = message.member?.voice.channel;
if (channel) {
try {
const connection = await connectToChannel(channel);
connection.subscribe(player);
await message.reply('Playing now!');
} catch (error) {
console.error(error);
}
} else {
void message.reply('Join a voice channel then try again!');
}
}
});
I have this error :
Screenshot of console error
This error is here in my index.js :
const { createDiscordJSAdapter } = require ('./?');
I just don't know how import this function createDiscordJSAdapter ....
I have my .env file true, (the bot is connected to my server).
I have my folder music with my song name "try.mp3".
And this index.js :D
If someone can help me to build this simple exemple,
Thx !
Sunclies
Discord added these slash commands in v13, I have followed the discordjs.guide website on how to do it.
My code is:
//packages
const { Client, Collection, Intents } = require("discord.js");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const disbut = require("discord-buttons");
client.commands = new Collection();
const moment = require("moment");
const { MessageEmbed } = require("discord.js");
const AntiSpam = require("discord-anti-spam");
const ms = require("ms");
const { Slash } = require("discord-slash-commands");
const slash = new Slash(client);
const rtkn = ">r";
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { token, owner, bowner, clientid, guildid, prefix } = require("./config.json");
const fs = require("fs");
const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
const commands = [];
const cmds = [];
disbut(client);
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const commands = [];
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: "There was an error while executing this command!", ephemeral: true });
}
});
const rest = new REST({ version: "9" }).setToken(token);
(async () => {
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands });
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
})();
const clean = (text) => {
if (typeof text === "string") return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/#/g, "#" + String.fromCharCode(8203));
else return text;
};
client.on("message", (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(prefix + "eval")) {
if (message.author.id !== owner) return;
try {
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
message.channel.send(clean(evaled), { code: "xl" });
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
}
}
});
client.on("message", (message) => {
const args = message.content.split(" ").slice(1);
if (message.content.startsWith(prefix + "eval")) {
if (message.author.id !== bowner) return;
try {
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
message.channel.send(clean(evaled), { code: "xl" });
} catch (err) {
message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``);
}
}
});
client.on("warn", (err) => console.warn("[WARNING]", err));
client.on("error", (err) => console.error("[ERROR]", err));
client.on("disconnect", () => {
console.warn("Disconnected!");
process.exit(0);
});
process.on("unhandledRejection", (reason, promise) => {
console.log("[FATAL] Possibly Unhandled Rejection at: Promise ", promise, " reason: ", reason.message);
});
client.login(token);
//ping.js contents below.
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
async execute(interaction) {
await interaction.reply("Pong!");
},
};
My ping.js file is:
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder().setName("ping").setDescription("Replies with Pong!"),
async execute(interaction) {
return interaction.reply("Pong!");
},
};
When I run the code, it registers the slash commands fine, but when I run it, it says "interaction failed." Please help.
Your code is not well structured. You have a lot of deprecated modules and you declared commands twice. The problem however, is that you never call client.commands.set. In your for...of loop, you called commands.push instead of client.commands.set.
I donβt know how the SlashCommandBuilder function works, but I suspect the toJSON method would return something that looks like this:
{
name: 'commandName',
description: 'description',
options: []
}
You have to change your loop to look like this:
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
const data = command.data.toJSON()
client.commands.set(data.name, data);
}
I'm currently trying to update a document in mongoDb. I'm new to mongo and reading the documentation didn't help me at all + I'm not getting any errors
My code
const Guild = require('../schemas/GuildSchema')
module.exports = {
name: 'whitelist',
description: "whitelist",
async execute(bot, message, args, PREFIX, Discord, settings, fs) {
if (message.author.id != "173347297181040640") {
return message.channel.send("Sorry only Bacio001 can whitelist!")
}
if (!args[1]) {
return message.channel.send("No guild id given!")
}
try {
Guild.findOneAndUpdate(
{ guildid: args[1]},
{ $set: { whitelisted : true } }
)
} catch (e) {
console.log(e);
}
let guild = bot.guilds.cache.get(args[1]);
message.channel.send(`Whitelisted ${guild.id} with the name ${guild.name} !`)
}
}
https://gyazo.com/a58a9d8175a8a38674b32a2776fa48cb
So I ended up finding the issue I had to await the Guild.findOneAndUpdate
const Guild = require('../schemas/GuildSchema')
module.exports = {
name: 'whitelist',
description: "whitelist",
async execute(bot, message, args, PREFIX, Discord, settings, fs) {
if (message.author.id != "173347297181040640") {
return message.channel.send("Sorry only Bacio001 can whitelist!")
}
if (!args[1]) {
return message.channel.send("No guild id given!")
}
try {
await Guild.findOneAndUpdate(
{ guildid: args[1]},
{ whitelisted : true }
)
} catch (e) {
console.log(e);
}
let guild = bot.guilds.cache.get(args[1]);
message.channel.send(`Whitelisted ${guild.id} with the name ${guild.name} !`)
}
}
I am trying to move all of my currency/shop commands/ Sequelize database into the command handler from index.js (works perfectly in index.js file) but I am running into issues transferring data from the index.js file into the individual command files. Any help on how to properly integrate the index.js commands into the command handler would be greatly appreciated. I realize this is a lot to go through but it would really mean a lot to me if anyone was able to help me out
index.js:
Reflect.defineProperty(currency, 'add', {
value: async function add(id, amount) {
const user = currency.get(id);
if (user) {
user.balance += Number(amount);
return user.save();
}
const newUser = await Users.create({ user_id: id, balance: amount });
currency.set(id, newUser);
return newUser;
},
});
Reflect.defineProperty(currency, 'getBalance', {
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
client.once('ready', async () => {
const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', async message => {
if (message.author.bot) return;
currency.add(message.author.id, 1);
if (!message.content.startsWith(prefix)) return;
const input = message.content.slice(prefix.length).trim();
if (!input.length) return;
const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);
if (command === 'balance') {
const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}π°`);
} else if (command === 'buy') {
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);
} else if (command === 'shop') {
const items = await CurrencyShop.findAll();
return message.channel.send(items.map(i => `${i.name}: ${i.cost}π°`).join('\n'), { code: true });
} else if (command === 'leaderboard') {
return message.channel.send(
currency.sort((a, b) => b.balance - a.balance)
.filter(user => client.users.cache.has(user.user_id))
.first(10)
.map((user, position) => `(${position + 1}) ${(client.users.cache.get(user.user_id).tag)}: ${user.balance}π°`)
.join('\n'),
{ code: true }
);
}
});
converting balance command to balance.js
balance.js:
const { currency, getBalance, id, tag } = require('../index.js');
module.exports = {
name: "balance",
description: "checks balance",
execute(message) {
const target = message.mentions.users.first() || message.author;
message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}π°`);
},
};
error:
TypeError: Cannot read property 'getBalance' of undefined
Command Handler
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).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 !== 'text') {
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);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
the bot sends an error from the command handler as seen above
EDIT: Cherryblossom's post seems to work. i have 1 more issue with immigrating the buy command though I dont know how to make the async work as async doesnt work in command handler. here is what i tried
const { currency, CurrencyShop} = require('../index.js');
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);```
What's happening is that in balance.js, currency is undefined. You need to export currency from index.js:
module.exports = { currency }
Also, in balance.js, you don't need to (and actually can't) import/require properties of other objects (getBalance, tag, id). Sorry if that doesn't make sense but basically you only need to require currency:
const { currency } = require('../index.js')
Edit
await can only be used in an async function. Edit the execute function so it is like this:
async execute(message) {
// your code here
}
When calling execute, use await. You'll need to make the message handler async as well:
client.on('message', async message => {
// code...
try {
await command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
}