How to create a "TempMute" command? - discord.js

How to create a TempMute command for discord.js which supports the command handler from An Idiot's Guide.
I understand you need to use .addRole(), but I have no idea how to create it with a timer. The range of the timer needs to be from 60 to 15 minutes.

If you want an action to be executed after some time, you need to use setTimeout(). Here's an example:
// If the command is like: -tempMute <mention> <minutes> [reason]
exports.run = (client, message, [mention, minutes, ...reason]) => {
// You need to parse those arguments, I'll leave that to you.
// This is the role you want to assign to the user
let mutedRole = message.guild.roles.cache.find(role => role.name == "Your role's name");
// This is the member you want to mute
let member = message.mentions.members.first();
// Mute the user
member.roles.add(mutedRole, `Muted by ${message.author.tag} for ${minutes} minutes. Reason: ${reason}`);
// Unmute them after x minutes
setTimeout(() => {
member.roles.remove(mutedRole, `Temporary mute expired.`);
}, minutes * 60000); // time in ms
};
This is just a pseudo-code, you'll need to parse the arguments and get the role.

Related

Discord.js Time command

Const currentDate = new Date();
client.on('message', msg => {
if(msg.author.bot) return;
if(msg.content === `${prefix}time`) {
msg.channel.send(currentDate.toLocaleString());
}
})
This does provide the right time for MY timezone but is there anyway to make the bot send a time stamp, different regions see a different time?
Well, you can use Discord's <t:unix-timestamp:t> feature. It'll vary depending on the timezone of the user seeing the message. You can get the Unix timestamp with Date.now() (const unixTimestamp = Date.now()) but that's the timestamp in milliseconds so you will need to divide it by 1000 for seconds.
You also want to use Math.floor since dividing milliseconds will give a decimal value and Discord's timestamp thing won't work.
const unixTimestamp = Math.floor(Date.now() / 1000)
Here's the command using your command handler:
client.on('message', (msg) => {
if (msg.author.bot) return;
if (msg.content === `${prefix}time`) {
const unixTime = Math.floor(Date.now() / 1000);
// you can remove the :t in the end so it's a full date
// :t makes it only the time
msg.channel.send(`The current time is <t:${unixTime}:t>`);
}
});
Also, I recommend using messageCreate and not message as it's deprecated.

Is it possible to make a variable dedicated to a certain author Discord.js?

I'm making a store bot and I ran into some SetInterval errors. I want to make it so each variable has the user's id so when I run a different command, it will know which interval to stop. (If that makes sense).
Here is my code:
if(message.content.startsWith(`!open`) {
var cashier1[message.author.id] = function () {
BalanceJSON[message.author.id].bal += 10
Fs.writeFileSync(`./DB/balance.json`, JSON.stringify(BalanceJSON));
}
setInterval(cashier1[message.author.id], 5000);
}
All this code is in a bot.on('message', message => { })
I wanna be able to stop an certain player's interval with clearInterval(cashier1[message.author.id])
The function setInterval returns a unique id which can be used to clear the interval again (See the example for more information).
The solution to your problem is to store the unique id of the interval in some object or database and use that to clear the interval again. See the example code below:
// Create an object to store the intervals.
const cashierIntervals = {};
// Inside your message handler.
// Some dummy if statement for demonstration purpose.
if (message.content === 'setInterval') {
// Create the setInterval and store the unique id in the cashier intervals object.
// You should probably add more checks to see if there is already an interval stored for this author id etc.
cashierIntervals[message.author.id] = setInterval(() => {
BalanceJSON[message.author.id].bal += 10;
Fs.writeFileSync(`./DB/balance.json`, JSON.stringify(BalanceJSON));
}, 5000);
} else if (message.content === 'clearInterval') {
// Clear the interval based on the author id.
// Again, probably add more checks to see if the author id has an interval stored etc.
clearInterval(cashierIntervals[message.author.id]);
// Delete the stored interval entry from the global intervals object.
// Not necessary but it keeps the intervals object small.
delete cashierIntervals[message.author.id];
}
Create an object that takes an id as a key. Your value will be the function you want to interval
Your main file:
const cashier1 = {
// Template for your key:values
'999999999': yourRepeatingFunction(),
}
// Lets say message.author.id returns '999999999'
// Doing setInterval(cashier1[message.author.id], 5000) Will call yourRepeatingFunction()

(discord.js) How to set a time limit on a command?

I am trying to make a Judge bot for my server that will give the person who used the command the role "Plaintiff", and give the person that they mentioned the "Defendant" role. Everything works perfectly as intended except the fact that multiple trials can be started at the same time. Like if someone uses the command and it makes them the plaintiff and a 2nd person the defendant, if a 3rd person uses the command on a 4th person they will become a defendant and plaintiff as well. I want to make it so that while the events of the command are playing out that nobody else in the server can use the command until the 1st trial ends. I have tried to give the entire server the role "jury" and make it so that if anyone has the role "jury" they can't use the command but i couldn't ever get that to work. Also I tried to set a time limit for the command and that didn't work at all either. I have no clue how to get this working and any advice is appreciated!! Thanks!!!
client.on("message", message => {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "sue") {
let member1 = message.mentions.members.first();
message.member.roles.add("797738368737345536")
member1.roles.add("797738235715256331");
message.guild.members.cache.forEach(member => member.roles.add("797743010346565672"))
message.channel.send("Court is now in session.")
client.channels.cache.find(channel => channel.name === 'courtroom').send( + " **All rise.**");
client.channels.cache.find(channel => channel.name === 'courtroom').send("Plaintiff, you have 2 minutes to state your case.");
setTimeout(function(){
client.channels.cache.find(channel => channel.name === 'courtroom').send("Thank you Plaintiff. Defendant, you now have 2 minutes to defend yourself.");
}, 120000);
setTimeout(function(){
client.channels.cache.find(channel => channel.name === 'courtroom').send("Thank you. The court may be seated as we turn to the jury for their verdict.");
}, 240000);
const Responses = [
"The Jury hereby finds you.... **GUILTY!** You will be sentanced to 10 minutes in jail.",
"The Jury hereby finds you.... **NOT GUILTY!** You are free to go. The Jury is dismissed."
];
const Response = Responses[Math.floor(Math.random() * Responses.length)];
setTimeout(function(){
client.channels.cache.find(channel => channel.name === 'courtroom').send(Response)
if (Response === "The Jury hereby finds you.... **NOT GUILTY!** You are free to go. The Jury is dismissed." ) {
message.member.roles.remove("797738368737345536")
member1.roles.remove("797738235715256331");
message.guild.members.cache.forEach(member => member.roles.remove("797743010346565672"))
}
if (Response === "The Jury hereby finds you.... **GUILTY!** You will be sentanced to 10 minutes in jail.") {
message.member.roles.remove("797738368737345536")
member1.roles.add("797738617338069002")
member1.roles.remove("797738235715256331");
message.guild.members.cache.forEach(member => member.roles.remove("797743010346565672"))
}
}, 250000);
setTimeout(function(){
member1.roles.remove("797738617338069002");
}, 850000);
}
});
You could create a file, so nobody is able to use the command while the file exists.
const fs = require("fs");
if (command_gets_executed) { // If the command gets executed
if (fs.existsSync("./commandAlreadyUsed")) { // Checking if the file exists
// YOUR CODE - When the command should not be usable
} else {
fs.writeFileSync("./commandAlreadyUsed"); // Creating the file
// YOUR CODE - When nobody else used the command before
}
}
And if you want the command usable again just use fs.unlinkSync("./commandAlreadyUsed").
You can try to use a CronJob to set a time limit, I used it before for a similar case, may be it can be useful for you

How to make by bot to leave a server with a guild id

I want my bot to leave a discord server by using ;leave <GuildID>.
The code below does not work:
if (message.guild.id.size < 1)
return message.reply("You must supply a Guild ID");
if (!message.author.id == 740603220279164939)
return;
message.guild.leave()
.then(g => console.log(`I left ${g}`))
.catch(console.error);
You're most likely not supposed to be looking at message.guild.id, since that returns the ID of the guild you're sending the message in. If you want to get the guild ID from ;leave (guild id), you'll have to cut out the second part using something like .split().
// When split, the result is [";leave", "guild-id"]. You can access the
// guild ID with [1] (the second item in the array).
var targetGuild = message.content.split(" ")[1];
!message.author.id will convert the author ID (in this case, your bot ID) into a boolean, which results to false (since the ID is set and is not a falsy value). I'm assuming that you mean to have this run only if it the author is not the bot itself, and in that case, you're most likely aiming for this:
// You're supposed to use strings for snowflakes. Don't use numbers.
if (message.author.id == "740603220279164939") return;
And now, you just have to use the guild ID that you got from the message content and use that to leave the guild. To do that, just grab the Guild from your bot cache, and then call .leave(). All in all, your code should now look like this:
// Get the guild ID
var targetGuild = message.content.split(" ")[1];
if (!targetGuild) // targetGuild is undefined if an ID was not supplied
return message.reply("You must supply a Guild ID");
if (message.author.id == "740603220279164939") // Don't listen to self.
return;
client.guilds.cache.get(targetGuild) // Grab the guild
.leave() // Leave
.then(g => console.log(`I left ${g}`)) // Give confirmation after leaving
.catch(console.error);

How to keep track of the number of times a user has been mentioned?

In my bot, I have a message counter that stores the number of times a user sent a message in the server.
I was trying to count how many times a user got mentioned in the server. Does anyone know how could I do it?
You can use message.mentions.members (or message.mentions.users) to see the mentions in a message. You can store the number of mentions for every user: every time they are mentioned, you increase the count.
var mention_count = {};
client.on('message', message => {
for (let id of message.mentions.users.keyArray()) {
if (!mention_count[id]) mention_count[id] = 1;
else mention_count[id]++;
}
});
Please note that mention_count will be reset every time you restart your bot, so remember to store it in a file or in a database to avoid losing it.
Edit: below you can see your code applied to mentions: every time there's a mention to count, it gets stored in the level value of the score.
client.on('message', message => {
if (!message.guild) return;
for (let id of message.mentions.users.keyArray()) if (id != message.author.id) {
let score = client.getScore.get(id, message.guild.id);
if (!score) score = {
id: `${message.guild.id}-${id}`,
user: id,
guild: message.guild.id,
points: 0,
level: 0
};
score.level++;
client.setScore.run(score);
}
});

Resources