How do I create a slash command in discord using discord.js - javascript

I am trying to create a slash command for my discord bot, but I don't know how to execute code when the command is exuted
The code I want to use will send a message to a different channel (Args: Message)
Here is the code I want to use
const channel = client.channels.cache.find(c => c.id == "834457788846833734")
channel.send(Message)

You need to listen for an event interactionCreate or INTERACTION_CREATE. See the code below, haven't tested anything, hope it works.
For discord.js v12:
client.ws.on("INTERACTION_CREATE", (interaction) => {
// Access command properties
const commandId = interaction.data.id;
const commandName = interaction.data.name;
// Do your stuff
const channel = client.channels.cache.find(c => c.id == "834457788846833734");
channel.send("your message goes here");
// Reply to an interaction
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Reply message"
}
}
});
});
For discord.js v13:
client.on("interactionCreate", (interaction) => {
if (interaction.isCommand()) {
// Access command properties
const commandId = interaction.commandId;
const commandName = interaction.commandName;
// Do your stuff
const channel = client.channels.cache.find(c => c.id == "834457788846833734")
channel.send("your message goes here");
// Reply to an interaction
interaction.reply("Reply message");
}
});

Related

Edit Snipe command sending more than one embed instead of just one

const editedMessages = new Discord.Collection();
client.on("messageUpdate", (oldMessage, newMessage) => {
if(oldMessage.content === newMessage.content)return
client.on('message', message => {
if (message.author.bot) return;
const args = message.content.trim().split(/\s+/g);
const command = args.shift().toLowerCase();
switch (command) {
case 'y!edit':
const msg = editedMessages.get(message.channel.id);
if (!message) return message.reply('There is nothing to snipe');
const edembed = new Discord.MessageEmbed()
.setColor('#deffff')
.setAuthor(newMessage.author.tag, newMessage.author.avatarURL({ dynamic: true }))
.setDescription(`**Old message:** ${oldMessage.content} \n **New message:** ${newMessage.content}`)
.setFooter(`ID: ${newMessage.author.id}`).setTimestamp()
message.channel.send({ embeds: [edembed] }).catch(err => console.error(err));
break;
}
});
});
client.on('messageUpdate', message => {
editedMessages.set(message.channel.id, message);
});
I want it to send only one embed when the command is used repeatedly. As you can see in the screenshot provided, every time the command was used it sent the previous embeds too. I've been stuck on this command line for ages.
It appears as if you are forgetting to close your preexisting bot connections.

Only reply in dms discord.js

So I was working on this project where people will DM the BOT and run command and it replies test. But it doesn't reply.
client.on("messageCreate", async message => {
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (message.channel.type === 'dm') {
message.reply("test");
}
}
});
That's because you didn't enable the intents for getting a dm message,
try putting those two on your client declarations :
const client = new Discord.Client({
intents : ['DIRECT_MESSAGES','GUILD_MESSAGES'],
partials: ["CHANNEL","MESSAGE"]
})
here is a way:
1.Create a file named ** 'privateMessage.js'** and in the main file add:
const privateMessage = require('./privateMessage')
client.on('ready' ,() =>{
console.log('I am online')
client.user.setActivity('YouTube Music 🎧', {type:'PLAYING'})
privateMessage(client, 'ping', 'pong')
})
and in the file we just created privateMessage.js add:
module.exports=(client, triggerText, replyText)=>{
client.on('message', message =>{
if(message.content.toLowerCase()===triggerText.toLowerCase()){
message.author.send(replyText)
}
})
}

Updating the prefix for a guild doesent require a full restart to apply but adding a new guild to my database does for some reason

so i have code setup so when a guild joins they are added to the database with default settings i setup. if they decide to change the prefix it works fine they can change the prefix and it will update and they can immediately start using it.
BUT for some reason when a guild is added i have to restart the bot or use nodemon and make it auto restart upon changes for that new guild before they can use ANY commands. is there a difference in how im adding this info to the database compared to adding the prefix?
below is the code i use to add the server to the database and below that is the code i use to let them change prefix. im trying to get the commands to work for the server that just invited the bot without having to restart the bot to avoid bugs down the line when its trying to do something and is then restarted cause someone invited the bot.
/// adding a guild to the database upon invite
bot.on('guildCreate', async (guild) => {
// Guild the user needs to have the role in
let myGuild = await bot.guilds.fetch(process.env.BOT_GUILD);
console.log(myGuild);
// Role that the user needs
let requiredRole = process.env.PAID_ROLE;
console.log(requiredRole);
// find default channel
let defaultChannel = "";
guild.channels.cache.forEach((channel) => {
if(channel.type == "text" && defaultChannel == "") {
if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
defaultChannel = channel;
console.log(defaultChannel);
}
}
});
// Member object of the user in guildA
try{
let guildOwner = await myGuild.members.fetch(guild.ownerID);
console.log(guildOwner);
if (!guildOwner)
return console.log(`Oops, ${guild.owner} is not a member of your server.`);
}catch(error) {
return console.log(`Oops, ${guild.owner} is not a member of your server.`),
defaultChannel.send('Please kick the bot, have the guild owner join this discord https://discord.gg/tDTjBAaCAn, Then you can reinvite the bot and you will be properly added to the database and can use the bot! dont forget to check out the premium features while your there if you decide you want more features from Gate Bot!');
}
//Check if they have the role
let guildOwner = await myGuild.members.fetch(guild.ownerID);
let ownerHasPaidRole = guildOwner.roles.cache.has(process.env.PAID_ROLE);
if (ownerHasPaidRole){
console.log(`Woohoo, ${guildOwner} has the required role`);}
try {
/// insert serverid and serverownerid into servers db
await connection.query(
`INSERT INTO Servers (serverId, serverOwnerId, paidRole) VALUES ('${guild.id}', '${guild.ownerID}', 1)`
);
/// insert server id into serverconfig db
await connection.query(
`INSERT INTO ServerConfig (serverId) VALUES ('${guild.id}')`
);
}catch(err){
console.log(err);
}});
Message handler to use the change prefix command
///allowing the script to see files from the commands folder
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
bot.commands.set(command.name, command);
}
///Message Handler
bot.on('message', async (message) => {
const prefix = guildCommandPrefixes.get(message.guild.id);
console.log('caught message');
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
///basic ping pong test command
if(command === 'help'){
bot.commands.get('help').execute(message);
}
///basic ping pong test command
else if(command === 'ping'){
bot.commands.get('ping').execute(message);
}
///change the servers prefix
else if(command === 'changeprefix'){
bot.commands.get('changeprefix').execute(message, connection, prefix, guildCommandPrefixes);
}
///arguments test
else if (command === 'argsinfo'){
bot.commands.get('argsinfo').execute(message, command, args)
}
///message command list
else if (command === 'autoungate'){
bot.commands.get('autoungate').execute(message, args, Discord);
}});
command used to change prefix.
module.exports= {
name: 'changeprefix',
description: "this will change the prefix in the database for the set guild id",
execute: async (message, connection, prefix, guildCommandPrefixes) =>{
setTimeout(() => {message.delete();}, 3000);
if (message.content.toLowerCase().startsWith(prefix + 'changeprefix')){
if (message.member.id === message.guild.ownerID) {
var guild = message.guild
paidRole = await connection.query(`SELECT paidRole FROM Servers Where '${guild}' === serverId`);
const [cmdName, newPrefix ] = message.content.split(" ");
if (paidRole === '1'){
if (newPrefix) {
try {
await connection.query(
`UPDATE ServerConfig SET cmdPrefix = '${newPrefix}' WHERE serverId= '${message.guild.id}'`
);
guildCommandPrefixes.set(message.guild.id, newPrefix);
message.channel.send(`Updated guild prefix to ${newPrefix}`).then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}catch(err) {
console.log(err);
message.channel.send(`Failed to update guild prefix to ${newPrefix}`).then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}}
else {
message.channel.send('You need to input a prefix to change to!').then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}}
else {
message.channel.send('You need to purchase the premium version for prefix customization.').then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}}
else {
message.channel.send('You do not have permissions to do this command!').then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}
}
}}
I made sure my paidRole variable in my database could be set to null.
Upon guild creation the guild is marked null for a split second to get it in the database. I used UPDATE to update the role to either 1 or 0 in the database based on their role in my Discord.
When you use UPDATE it will "refresh" the bot and apply automatically some changes without making it restart possibly causing some issues.
Here's the code I ended up using:
/// adding a guild to the database upon invite
bot.on('guildCreate', async (guild) => {
// Guild the user needs to have the role in
let myGuild = await bot.guilds.fetch(process.env.BOT_GUILD);
try {
/// insert serverid and serverownerid into servers db
await connection.query(
`INSERT INTO Servers (serverId, serverOwnerId, paidRole) VALUES ('${guild.id}', '${guild.ownerID}', NULL)`
);
/// insert server id into serverconfig db
await connection.query(
`INSERT INTO ServerConfig (serverId) VALUES ('${guild.id}')`
);
}catch(err){
console.log(err);
// find default channel
let defaultChannel = "";
guild.channels.cache.forEach((channel) => {
if(channel.type == "text" && defaultChannel == "") {
if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
defaultChannel = channel;
console.log(defaultChannel);
}
}
});
// Member object of the user in guildA
try{
let guildOwner = await myGuild.members.fetch(guild.ownerID);
if (!guildOwner)
return console.log(`Oops, ${guild.owner} is not a member of your server.`);
}catch(error) {
return console.log(`Oops, ${guild.owner} is not a member of your server.`),
defaultChannel.send('Please kick the bot, have the guild owner join this discord https://discord.gg/tDTjBAaCAn, Then you can reinvite the bot and you will be properly added to the database and can use the bot! dont forget to check out the premium features while your there if you decide you want more features from Gate Bot!');
}
//Check if they have the role
let guildOwner = await myGuild.members.fetch(guild.ownerID);
let ownerHasPaidRole = guildOwner.roles.cache.has(process.env.PAID_ROLE);
if (ownerHasPaidRole){
console.log(`Woohoo, ${guildOwner} has the required role`);
await connection.query(
`UPDATE Servers SET paidRole = '1' WHERE serverId = ${guild.id}`
);
}
else {
await connection.query(
`UPDATE Servers SET paidRole = '0' WHERE serverId = ${guild.id}`
);
}
}});

Discord.js | Making a message sniper command

I'm trying to make a bot log/snipe a message, when someone says 'zsnipe', I want to know how would i make 'zsnipe' a command but its not working, am I doing something wrong? here's the code:
bot.on('messageDelete', message => {
const embed8 = new Discord.MessageEmbed()
.setAuthor(`${message.author.username}#${message.author.discriminator}`, message.author.avatarURL({dynamic : true}))
.setDescription(message.content)
if (message.content === 'zsnipe'){
message.channel.send(embed8)
}
})
Your Help Will be Appreciated!
Here is some code that saves the last deleted message in a channel and allows it to be retrieved when someone says zsnipe.
Warning: the deleted messages will be lost if the bot restarts.
const deletedMessages = new Discord.Collection();
bot.on('message', async message => {
if (message.author.bot) return;
const args = message.content.trim().split(/\s+/g);
const command = args.shift().toLowerCase();
switch (command) {
case 'zsnipe':
const msg = deletedMessages.get(message.channel.id);
if (!msg) return message.reply('could not find any deleted messages in this channel.');
const embed = new Discord.MessageEmbed()
.setAuthor(msg.author.tag, msg.author.avatarURL({ dynamic: true }))
.setDescription(msg.content);
message.channel.send(embed).catch(err => console.error(err));
break;
});
bot.on('messageDelete', message => {
deletedMessages.set(message.channel.id, message);
});

Discord.js Embed error Cannot send an empty message

so I'm trying to make a help command with list of commands showed in embed. My code kinda works but it throws an error "DiscordAPIError: Cannot send an empty message" and I've tried already everything I know and what I've found but I can't fix it.
Here's the code
const Discord = require('discord.js');
const { prefix } = require('../config.json');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands', 'cmds'],
usage: '[command name]',
cooldown: 5,
execute(msg, args) {
const data = [];
const { commands } = msg.client;
if (!args.length) {
const helpEmbed = new Discord.MessageEmbed()
.setColor('YELLOW')
.setTitle('Here\'s a list of all my commands:')
.setDescription(commands.map(cmd => cmd.name).join('\n'))
.setTimestamp()
.setFooter(`You can send \`${prefix}help [command name]\` to get info on a specific command!`);
msg.author.send(helpEmbed);
return msg.author.send(data, { split: true })
.then(() => {
if (msg.channel.type === 'dm') return;
msg.reply('I\'ve sent you a DM with all my commands!');
})
.catch(error => {
console.error(`Could not send help DM to ${msg.author.tag}.\n`, error);
msg.reply('it seems like I can\'t DM you! Do you have DMs disabled?');
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return msg.reply('that\'s not a valid command!');
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
msg.channel.send(data, { split: true });
},
};
You should try replace this line :
msg.channel.send(data, { split: true });
with
msg.channel.send(data.join(' '), { split: true }); since your data variable is an array and not a string
The problem is as the error states. You are trying to send an empty message somewhere.
You can try replacing msg.channel.send(data) with msg.channel.send(data.join('\n')), since the data variable is an array.
I don't see why sending an array doesn't work though.

Categories