Discord.js | How to read a number in a message? - discord.js

I'm trying to make a game for my discord bot: bot chooses a random number and then, user tries to find number by guidance of the bot. I tried this thing but when I send a message (I send a number) it turns NaN. Why this happens and how can I fix it?
let randomNumber = (Math.floor( Math.random() * (100)))
let usersAnswer = parseInt(message.content)
if (!message.author.bot && message.content === "!pick number"){
message.reply("I kept! :check: ").then(j => {
message.channel.awaitMessages(( message, user) => (user.id === message.author.id && randomNumber < usersAnswer || randomNumber > usersAnswer),
{max: 1, time: 10000}).then(j => {
if (usersAnswer < randomNumber) {
message.reply("Increase! :arrow_up:" + usersAnswer) //I add usersAnswer to the bot's message because I want to see what it reads my message like in Discord
}
else {
message.reply("Decrease! :arrow_down:" + usersAnswer)
}
})
})
}

If you use parseInt() you need to set a radix before using this method. I took 10 as an example.
let usersAnswer = parseInt(message.content, 10)
if (!message.author.bot && message.content === "!pick number"){
message.reply("I kept! :check: ").then(j => {
message.channel.awaitMessages(( message, user) => (user.id === message.author.id && randomNumber < usersAnswer || randomNumber > usersAnswer),
{max: 1, time: 10000}).then(j => {
if (usersAnswer < randomNumber) {
message.reply("Increase! :arrow_up:" + usersAnswer) //I add usersAnswer to the bot's message because I want to see what it reads my message like in Discord
}
else {
message.reply("Decrease! :arrow_down:" + usersAnswer)
}
})
})
}
Or you could also simply use Number():
let usersAnswer = Number(message.content)
if (!message.author.bot && message.content === "!pick number"){
message.reply("I kept! :check: ").then(j => {
message.channel.awaitMessages(( message, user) => (user.id === message.author.id && randomNumber < usersAnswer || randomNumber > usersAnswer),
{max: 1, time: 10000}).then(j => {
if (usersAnswer < randomNumber) {
message.reply("Increase! :arrow_up:" + usersAnswer) //I add usersAnswer to the bot's message because I want to see what it reads my message like in Discord
}
else {
message.reply("Decrease! :arrow_down:" + usersAnswer)
}
})
})
}
If I were you I would add a check if the usersAnswer is even a Number otherwise the output could also be NaN.)
You could do this by simply adding the following line:
if (isNaN(usersAnswer)) return message.reply('This is not a number');

Related

time_amount says it is undefined even tho there are 2 arguments

when i execute the command with 2 agrumments it then sends in the channel "member gas been timed out for undefined seconds"
example command: !timeout #user 10
if (command === 'timeout'){
let { member, time_amount} = args
if (!args.length) {
return message.channel.send(`You didn't provide a amount of time or a member, ${message.author}!`);
} else {
if(args.length = 0){
message.channel.send(`there are only ${args.length} argument please add the right arguments`)
}
else{
if(args.length = 1){
console.log(time_amount)
if(isNaN(time_amount)){
if (message.member.roles.cache.find(r => r.name === 'owner')){
const member = message.mentions.members.first() || message.guild.members.cache.get(argument[0]) || message.guild.members.cache.find( x => x.user.username.toLocaleLowerCase() === argument.slice(0).join(" " || x.user.username === argument[0]));
member.timeout()
message.channel.send(`member has been timed out for `+ time_amount + ` seconds`)
setTimeout(function(){message.channel.send('the user <#' + member.id + '> is not in timeout anymore.')}, time_amount)
}
else{
message.channel.send('you dont have the right promitions <#' + message.author.id + '>.')
}
}
else{
message.channel.send(`time amount is not a number, <#${message.author.id}>`)
}
}
else{
message.channel.send(`there are to many agruments please add the right arguments`)
}
}
}
}
i want that time_amount stores the second argument so could somebody help me

How to check if user already sent message in channel?

I would like to block a user who want to send another message in a specific channel :
client.on("message", async message => {
if ((message.content === config.RUN) && message.member.roles.cache.has(config.ROLE_ID)) {
if (message.channel.type === 'DM') return;
let filter = m => !m.author.bot;
let destination = client.channels.cache.get(config.CHANNEL_ID);
message.author.createDM().then(dmchannel => {
dmchannel.send(textDM.FIRST_DM);
const collector = new discord.MessageCollector(dmchannel, filter);
collector.on('collect', (m, col) => {
console.log(m.content);
if (m.content.startsWith("ok")) { // here condition if user already sent msg
// Do something
}
You can use a variable to count the quantity of the message sent by the user. If it reaches 2, you can execute your desired code.
To use this for specific user, do:
var messageAmount = {}
var amount = 0
if (message.content.startsWith("ok")) {
const user = message.author.id
if(messageAmount[`${user}`] === 1) { // is 1 because it checks for 2 after it has been assigned, if(messageAmount = x-1)
// Do something
message.channel.send("You cannot say that again until (...) finishes")
// then reset it
messageAmount[`${user}`] = 0
amount = 0
} else {
++amount
messageAmount[`${user}`] = amount
}
}
To use this globally:
var messageAmount = 0
if (m.content.startsWith("ok")) {
++messageAmount
if(messageAmount === 2) {
// Do something
}
}

How to ban with Discord.js?

I have created a command to ban a user and I want it to prompt the user for a confirmation on whether or not they would like to ban the user, and then once they confirm, execute the ban.
I've tried to log where the problem is, but it gives me a blank error.
My code for the command:
const Discord = require('discord.js')
let target = arguments.shift()
let reason1 = arguments.join(" ");
const reason = reason1 || "Ohne Grund"
const banEmbed = new Discord.MessageEmbed()
.setTitle('🚫Ban')
.setDescription(`Bist du dir sicher, dass ${message.mentions.users.first()} gebannt werden soll?`)
.setColor('RED')
.addFields(
{ name: 'Reason', value: `${reason}`}
)
.setTimestamp()
.setFooter(message.guild.name, message.guild.iconURL())
message.channel.send(banEmbed).then(sentEmbed =>{
sentEmbed.react("βœ…")
sentEmbed.react("❌")
sentEmbed.awaitReactions((reaction, user) => user.id == message.author.id && (reaction.emoji.name == 'βœ…' || reaction.emoji.name == '❌'),
{ max: 1, time: 30000 }).then(collected => {
console.log(collected.first().emoji.name)
if (collected.first().emoji.name == 'βœ…') {
console.log(target)
console.log(reason)
target.ban({ days: 0, reason: reason })
message.reply('Member wird gebannt.');
}
if (collected.first().emoji.name == '❌') {
message.reply('Member wird nicht gebannt.');
}
}).catch(() => {
message.reply('timeout');
console.error();
});
});
and this is the part where it fails, everything else is okay:
sentEmbed.awaitReactions((reaction, user) => user.id == message.author.id && (reaction.emoji.name == 'βœ…' || reaction.emoji.name == '❌'),
{ max: 1, time: 30000 }).then(collected => {
console.log(collected.first().emoji.name)
if (collected.first().emoji.name == 'βœ…') {
console.log(target)
console.log(reason)
target.ban({ reason: reason })
message.reply('Member wird gebannt.');
}
Console Output:
The client is ready!
βœ…
<#!664493064336965634>
test
Please help!
What you are doing here won't work. Why? You are getting the first element of the array which is a string even if you mention someone it will look like <#4242424242424> which doesn't have the method .ban
let target = arguments.shift()
You should find that member in the guild either you can get it by the mentions property
let target = message.mentions.members.first() || message.guild.members.cache.get(arguments.shift());

SlowMode for one person is possible ? discord.js

I would like to know if it is possible to do some sort of "SlowMode" for a specific person on Discord.
The reason is that I have a "spammer" friend, and I would like to calm him down with a command that might slow him down when he speaks for "x" secondes.
So I would like to know if this is possible? and if yes, how?
Thank you for your kindness =) (and sorry for this english i use GoogleTraductor)
Here's how I'd do that.
let ratelimits = [];
client.on("message", (msg) => {
// APPLYING RATELIMITS
const appliedRatelimit = ratelimits.find(
(value) =>
value.user === msg.author.id && value.channel === msg.channel.id
);
if (appliedRatelimit) {
// Can they post the message?
const canPostMessage =
msg.createdAt.getTime() - appliedRatelimit.ratelimit >=
appliedRatelimit.lastMessage;
// They can
if (canPostMessage)
return (ratelimits[
ratelimits.indexOf(appliedRatelimit)
].lastMessage = msg.createdAt.getTime());
// They can't
msg.delete({ reason: "Enforcing ratelimit." });
}
// SET RATELIMIT
if (msg.content === "!ratelimit") {
// Checking it's you
if (msg.author.id !== "your id") return msg.reply("You can't do that.");
// You can change these values in function of the received message
const targetedUserId = "whatever id you want";
const targetedChannelId = msg.channel.id;
const msRateLimit = 2000; // 2 seconds
// Delete existant ratelimit if any for this user on this channel
ratelimits = ratelimits.filter(
(value) =>
!(
value.user === targetedUserId &&
value.channel === targetedChannelId
)
);
// Add ratelimit
ratelimits.push({
user: targetedUserId,
channel: targetedChannelId,
ratelimit: msRateLimit,
lastMessage: 0,
});
}
// CLEAR RATELIMITS
if (msg.content === "!clearRatelimits") {
// Checking it's you
if (msg.author.id !== "your id") return msg.reply("You can't do that.");
// Clearing all ratelimits
ratelimits = [];
}
});

I'm trying to make a second input into a bot

I'm trying to make a command where you input the command and the bot says: Are you sure? Then you type yes or no but I can't figure out how I can make it so the user can reply. Can someone help please?
have some ways to do that, the easier is to use MessageCollector to collect the user response.
Example:
message.channel.send("Are you sure?") // Ask the user
const filter = (m) => m.author.id === message.author.id && (m.content.toLowerCase() === "yes" || m.content.toLowerCase() === "no") // Create a filter, only accept messages from the user that used the command and the message includes "yes" or "no"
const collector = message.channel.createMessageCollector(filter, {time: 30000})
collector.once("collect", msg => {
if(msg.content.toLowerCase() === "yes") {
// User sent yes
} else {
// User sent "no"
}
})
collector.once("stop", (collected, reason) => {
if(reason === "time") {
// User took so long to anwser
}
})
You can use TextChannel.awaitMessages too, it returns a Promise with messages.
Example:
message.channel.send("Are you sure?")
const filter = (m) => m.author.id === message.author.id && (m.content.toLowerCase() === "yes" || m.content.toLowerCase() === "no") // Create a filter, only accept messages from the user that used the command and the message includes "yes" or "no"
message.channel.awaitMessages(filter, {max: 1, time: 30000})
.then(collected => {
const msg = collected.first()
if(msg.content.toLowerCase() === "yes") {
// User sent yes
} else {
// User sent "no"
}
})

Resources