//Ping Command With Slash
client.on('ready', () => {
client.application.commands.create(
{
name: 'ping',
description: `To see Bot's ms`
},
config.id
);
client.on('interactionCreate', interaction => {
if (interaction instanceof Discord.CommandInteraction && interaction.commandName === 'ping') {
interaction.reply({content: `šPong i have ${Math.round(client.ws.ping)} ms`, ephemeral: true})
}
});
});
This is the command that I have in my index, as I do not want this command in commands folder.
Can someone help me make a command for kick so when I type /kick - I have two options for user and reason?
Related
I'm trying to make a discord.js bot which whenever someone types a certain command on Discord, it opens a program on my PC:
client.on("message", (message) => {
if (message.content == "!ping") {
//here I want to open a program on my pc
}
});
Assuming you are using Node you can include the execFile function from the child_process package and just call it from the command line.
const { execFile } = require("child_process");
client.on("message", (message) => {
if(message.content == "!ping") {
execFile("<path to file>", ["optional arg1", "optional arg2"]);
}
});
Or if you just want to run a command, just exec
const { exec } = require("child_process");
client.on("message", (message) => {
if(message.content == "!ping") {
exec("<shell command>", ["optional arg1", "optional arg2"]);
}
});
Check out https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback for documentation.
You may need to "npm install child_process"
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;
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);
I have a working bot, with a functioning command handler, and I have a reload command to update my code for preexisting commands. Anytime I add a new command, I have to restart the whole bot. Since this particular bot has scripts on intervals running, restarting my bot would terminate all running intervals, forcing all users to manually restart them. I don't want to have to resort to restarting my bot anytime I add a new command, so I need help.
Here's my reload command right now:
const botconfig = require("../config.json");
module.exports = {
name: 'reload',
type: "Developer",
description: 'Reloads a command (developer only)',
cooldown: 1,
execute(message, args) {
if (message.author.id != botconfig.developerid) return message.channel.send("Only my developer can use this command...");
message.channel.send("Developer command confirmed!");
if (!args.length) return message.channel.send(`You didn't pass any command to reload!`);
const commandName = args[0].toLowerCase();
const command = message.client.commands.get(commandName) ||
message.client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return message.channel.send(`There is no command with name or alias \`${commandName}\`, ${message.author}!`);
delete require.cache[require.resolve(`./${command.name}.js`)];
try {
const newCommand = require(`./${command.name}.js`);
message.client.commands.set(newCommand.name, newCommand);
message.channel.send("Command `" + command.name + "` was reloaded!");
} catch (error) {
console.log(error);
message.channel.send("There was an error while reloading the `" + botconfig.prefix + command.name + "` command. \n\nError is as follows:\n``${error.message}`");
}
},
};
I want to add an optional "new" argument before the command name to look specifically for new commands, as the current code works, but it only sees preexisting commands. If it would be simpler to change the current code to look for new commands in addition, but still error out if it finds none, that'll be fine too.
Yes, you can use the following code so if the command is already loaded, it deletes it.
const botconfig = require("../config.json");
module.exports = {
name: 'reload',
type: "Developer",
description: 'Reloads a command (developer only)',
cooldown: 1,
execute(message, args) {
if (message.author.id != botconfig.developerid) return message.channel.send("Only my developer can use this command...");
message.channel.send("Developer command confirmed!");
if (!args.length) return message.channel.send(`You didn't pass any command to reload!`);
const commandName = args[0].toLowerCase();
if(message.client.commands.get(commandName)){
const command = message.client.commands.get(commandName) ||
message.client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return message.channel.send(`There is no command with name or alias \`${commandName}\`, ${message.author}!`);
delete require.cache[require.resolve(`./${command.name}.js`)];
}
try {
const newCommand = require(`./${commandName}.js`);
message.client.commands.set(commandName, newCommand);
message.channel.send("Command `" + commandName+ "` was reloaded!");
} catch (error) {
console.log(error);
message.channel.send("There was an error while reloading the `" + botconfig.prefix + commandName + "` command. \n\nError is as follows:\n``${error.message}`");
}
},
};