How to add timed mute to discord.js - javascript

I'm making a discord bot and i want to add a timed mute function like in other moderation bots where you can say who you want to mute and for how long. I have done muting in general but now need the timed mute stuff so please help me. I am also not very good with Javascript so please tell me where i implement the code if you give me some. The mute file:
module.exports = {
name: "mute",
description: "mutes the mentioned user",
execute(message, args) {
const mutedRole = message.guild.roles.cache.find(
(role) => role.name === "muted"
);
const target = message.mentions.members.first();
if (!mutedRole) {
message.channel.send("Cannot find mute role.");
} else {
target.roles.add(mutedRole);
message.channel.send("Muted " + target + " ✅");
}
},
};
i want it that its -mute {user} {time}
an example is: -mute #ani 10s
if you want the main file here you go:
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "!";
const fs = require("fs");
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.once("ready", () => {
console.log("Ani Bot is online!");
client.user.setActivity("with depression");
});
client.on("message", (message) => {
if (message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === "test") {
client.commands.get("test").execute(message, args);
} else if (command === "mute") {
client.commands.get("mute").execute(message, args);
} else if (command === "unmute") {
client.commands.get("unmute").execute(message, args);
} else if (command === "join") {
client.commands.get("join").execute(message, args);
} else if (command === "leave") {
client.commands.get("leave").execute(message, args);
}
});

You can use the function setTimeout() right after you mute a user.
//you call the function unmuteUser after 10000 milliseconds
setTimeout(unmuteUser(user), 10000);
function unmuteUser(user){
//code that unmute
...
}

Related

TypeError: command.execute is not a function. (After typing !rps on discord channel)

When I try to use !rps, discord shows me that there is no command and I get somethink like that in the console
I don`t know do I need to change something in my index.js code or in my rps.js code
https://imgur.com/sGjGR4t
const Discord = require('discord.js');
const fs = require('fs');
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES] });
client.command = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}/`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.command.set(command.name, command);
}
}
const prefix = '!';
client.once('ready', () => {
console.log('Bot jest online');
client.user.setActivity('Minecraft')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.command.has(commandName)) return;
const command = client.command.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Nie ma takiej komendy!')
}
});
client.login("TOKEN");
And the rps.js code, I tried to move rps.js to other folder but it does not solve the problem
const Discord = require('discord.js')
module.exports = {
name: "rps",
description: "rock paper scissors command",
usage: "!rps",
async run(bot, message, args) {
let embed = new Discord.MessageEmbed()
.setTitle("RPS")
.setDescription("React to play!")
.setTimestamp()
let msg = await message.channel.send(embed)
await msg.react("🗻")
await msg.react("✂")
await msg.react("📝")
const filter = (reaction, user) => {
return ['🗻', '✂', '📝'].includes(reaction.emoji.name) && user.id === message.author.id;
}
const chices = ['🗻', '✂', '📝']
const me = choices[Math.floor(Math.random() * choices.lenght)]
msg.awaitReactions(filter, { max: 1, time: 60000, error: ["time"] }).then(async (collected) => {
const reaction = collected.first()
let result = new Discord.MessageEmbed()
.setTitle("Result")
.addFields("Your Choice", `${reaction.emoji.name}`)
.addField("Bots choice", `${me}`)
await msg.edit(result)
if ((me === "🗻" && reaction.emoji.name === "✂") ||
(me === "✂" && reaction.emoji.name === "📝") ||
(me === "📝" && reaction.emoji.name === "🗻")) {
message.reply('You lost!');
} else if (me === react.emoji.name) {
return message.reply(`It's a tie!`);
} else {
return message.reply('You won!');
}
})
.catch(collected => {
message.reply('Process has been canceled, you failed to respond in time!');
})
}
}
In your rps.js file, you are defining the function to be run as run but in your index.js file, you are using the execute function so you can either change how you run the command in your main file or you can change the function name in your command file. Another place where you could get an error is the arguments you pass. In your main file, you are passing two arguments to your command file, message and args while in your command file, you are expecting three, bot, message and args. So you can either change the order of the arguments you pass or you can just remove the bot parameter in the command file:

SyntaxError: Cannot use import statement outside a module discord.js

I'm new to coding in general so expect nooby behaviour.
i try to make discord music bot and it cant join voice chat and when i type node .an error pops up
i dont know where put import, i tried everywhere but i doesnt work, ping and youtube command work only play doesnt
This is the main code:
const { Client, Intents, DiscordAPIError } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const prefix = '!';
const fs = require('fs');
const Discord = require('discord.js');
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.once('ready', () => {
console.log('Musicbot is online!');
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
} else if (command == 'youtube'){
client.commands.get('youtube').execute(message, args);
} else if (command == 'play'){
client.commands.get('play').execute(message, args);
} else if (command == 'leave'){
client.commands.get('leave').execute(message, args);
}
});
client.login('token');
https://stackoverflow.com/questions/ask#
This is the play command code:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
async execute(message, args){
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Musisz być na kanale głosowym by użyć tej komendy!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('Nie masz odpowiednich uprawnień');
if (!permissions.has('SPEAK')) return message.channel.send('Nie masz odpowiednich uprawnień');
if (!args.length) return message.channel.send('You need to send the second argument!');
import { joinVoiceChannel } from "#discordjs/voice";
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
const stream = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1});
on('finish', () =>{
voiceChannel.leave();
});
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
}else {
message.channel.send('Nie znaleziono wideo');
}
}
}
Pls help
Try replacing import { joinVoiceChannel } from "#discordjs/voice"; with const { joinVoiceChannel } = require("#discordjs/voice");.
This error occurred because you tried using es modules import inside commonjs. You can however use dynamic imports on commonjs if needed.

How do I make a discord bot welcome command and leave command

I want to create an embedded welcome command and leave command. I would like an embedded DMS message for the person who joined the server.
This is the code I have so far:
const fs = require('fs');
const Discord = require('discord.js');
const {
prefix,
token
} = require('./config.json');
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);
}
const cooldowns = new Discord.Collection();
client.on('guildMemberAdd', member => {
if (!member.guild) return;
let guild = member.guild
let channel = guild.channels.cache.find(c => c.name === "welcome");
let membercount = guild.members
if (!channel) return;
let embed = new Discord.MessageEmbed().setColor("GREEN").setTitle("New Server Member!").setDescription(`Welcome, ${member.user.tag} to **${guild.name}!**`).setThumbnail(member.user.displayAvatarURL()).setFooter(`You are the ${membercount}th member to join`);
message.guild.channels.cache.find(i => i.name === 'sp').send(embed)
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: "idle", //You can show online, idle.... activity: {
name: "with lower lifeforms!", //The message shown type: "PLAYING", // url: "" //PLAYING: WATCHING: LISTENING: STREAMING:
}
});
});
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.Discord(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);
}
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)) {
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(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.`);
}
}
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
Now on Discord, you will need to enable intents. To do this, go to the Discord Developer Portal, select your application, and go onto the Bot tab. If you scroll about half way down, you'll see a section called Privileged Gateway Intents. You need to tick Server Members Intent under that title. For what you're doing, Presence Intent shouldn't be required, but you can tick it in case you do ever need it.

making an invite manager with discord.js

I am making a discord bot that has a command where it will tell you every bodies invites from greatest to least in the discord server. This is the code I have but I don't know why it isn't working.
module.exports = {
name: 'invites',
description: 'invite command',
callback: (message) => {
const { guild } = message;
guild.fetchInvites().then((invites) => {
const inviteCounter = {};
invites.forEach((Invite) => {
const { uses, inviter } = Invite;
const { username, discriminator } = inviter;
const name = `${username}#${discriminator}`;
inviteCounter[name] = (inviteCounter[name] || 0) + uses;
});
let replyText = 'invites:';
for (const invite in inviteCounter) {
const count = inviteCounter[invite];
replyText += `\n${invite} has invited ${count} member(s)!`;
}
message.reply(replyText);
});
},
};
This is my command handler, i have 2 other commands that i know work and I've been changing the invite command some cause I cant get it to work.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '+';
const fs = require('fs');
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.once('ready', () =>{
console.log('Baysides-utilities is online!');
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ticket'){
client.commands.get('ticket').execute(message, args, client, fs);
}
if(command === 'invites'){
client.commands.get('invites');
}
if(command === 'grow'){
client.commands.get('grow').execute(message, args, client, fs);
}
});
client.login('I have it in the code just not showing it here');

Working on a Discord bot with discord.js, tempmute won't work

making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boosted❤️",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.

Categories

Resources