Cannot get bot to autoban new accounts on Discord - javascript

The bot is very simple and will ultimately not require any input from me. What I want the bot to do is to check the age of an account that joins and then ban them if they are a new account made within the past 10 minutes. The part that I'm stuck on is calculating the time I think. The bot isn't giving any errors, it's just not banning the new account that I made. For testing purpose, I put the bot onto a new server I"m making that doesn't have anyone else on it and also changed the amount of time to 14400 seconds so that it's within 10 days and should give me enough time to figure out what's wrong.
Here's my code as it stands:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", (member) => {
if (Date.now() - member.user.createdAt <= 14400) {
guildMember.ban({ days: 14, reason: 'New account' })
}
});
client.login("Token");
member.client.user.createdAt is the section that I think I'm having a problem with. When I run a debug on Date.now() that works fine but I can't seem to get it to calculate the age of an account that joins.
I'm pretty sure that this is the property I need but I must be calling it incorrectly. Please forgive any ignorance, I'm super new to js.
https://discord.js.org/#/docs/main/master/class/User?scrollTo=createdAt
I would love to know what I'm doing wrong. Thanks!

Finally figured out the problem. The issue is actually multi-part here. The first issue is that I thought it was calculating in seconds, but instead it's actually calculating in milliseconds so the if statement was never true. Once I made that true by increasing the time to 10 days in milliseconds, I got an error on the guildMember since it wasn't defined. I changed that to member and then got an error on the days that it can't be more than 7. Here's the final working code.
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", (member) => {
if (Date.now() - member.user.createdAt <= 864000000) {
member.ban({ days: 7, reason: 'New account' })
}
});
client.login("Token");

You need to put the "async" for it to work
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", async member => {
if (Date.now() - member.user.createdAt <= 1209600000) {
member.ban({ days: 14, reason: 'New account' })
}
});
client.login("Token");

Related

How to implement a 1-hour cooldown in a Discord hack command?

I have a command that costs a lot memory usage, so I want to implement a 1-hour cooldown. I have used this, but it isn't working:
const Discord = require('discord.js');
module.exports = {
run: async(client, message, args) => {
const cooldown = new Set();
if(cooldown.has(message.author.id)) {
message.reply('Please Wait For 1 hour')
} else {
message.channel.send('text')
cooldown.add(message.author.id);
setTimeout(() => {
cooldown.delete(message.author.id)
}, 3600000)}
}
}
How can I get this working?
Currently, a new set is created at each run, so it will always be empty.
You should make your cooldown set in a global scope. Try to instantiate the set before the module.export

Bot reacting to emojis

So, I got my code and it works just as I want it to. the message pops up changes everything, it's perfect.
Now I want to add so the bot knows when I react to its message and then does something else. What I mean is: bot sends a message with reacts, and whenever some user clicks the reaction something happens, but I have no idea how to do that.
I've tried many things like if (reaction.emoji.name === ':bomb:'), but multiple errors popped out and I didn't know how to fix that. Here's the code:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
var lastbuffer;
lastbuffer = 0;
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if(message.content.startsWith(`${prefix}start`)){
message.delete()
setInterval(function(){
lastbuffer++;
const Buffer = new Discord.MessageEmbed()
.setColor('#8300FF')
.setTitle("**It's time to check buffers!**")
.setDescription("**It's been **" + "`" + lastbuffer + " Hour" + "`" + "** since last buffercheck, <#&675688526460878848>**." + " **Check now!**")
.setThumbnail('https://art.pixilart.com/88534e2f28b65a4.png')
.setFooter('WEEEEEWOOOOO')
.setTimestamp();
client.channels.cache.get("700296799482675230").send(Buffer).then(msg => {
msg.react('✅');
msg.react('💣');
msg.delete({timeout: 4000})
});
}, 5000)
}
});
client.login(token);
You are going to have to use a ReactionCollector using the createReactionCollector() method.
You can follow this guide to under ReactionCollectors better
You need to use a reaction collector.
client.channels.cache.get("700296799482675230").send(Buffer).then(async msg => {
// I'm using await here so the emojis react in the right order
await msg.react('✅');
await msg.react('💣');
msg.awaitReactions(
// Discord.js v12:
/* ({emoji}, user) => ['✅', '💣'].includes(emoji.name) && user.id === message.author.id,
{max: 1, time: 4000, errors: ['time']} */
// Discord.js v13:
{
// only collect the emojis from the message author
filter: ({emoji}, user) => ['✅', '💣'].includes(emoji.name) && user.id === message.author.id,
// stop collecting when 1 reaction has been collected or throw an error after 4 seconds
max: 1,
time: 4000,
errors: ['time']
}
)
.then(collected => {
const reaction = collected.first()
// do something
})
.catch(() => {
// I'm assuming you want to delete the message if the user didn't react in time
msg.delete()
})
What this code does:
Sends the embed (Buffer) to the channel with the id 700296799482675230
Reacts with the ✅ and then the 💣 emojis on the message with the embed
Waits for a ✅ or 💣 reaction from the author of the original message
If the user reacts within 4 seconds, runs the // do something part
If the user does not react within 4 seconds, deletes the message with the embed

Discord.js fired several times

The code that I made is fired several times, I have tried to add returns but it doesn't matter. I'm running the code with a raspberry pi 3.
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!')
})
client.on('error', console.error);
client.on('message', message =>{
if (message.channel.id == '...........') {
console.log(message.content);
}
if (message.content.startsWith(`${prefix}ping`)) {
if (message.member.roles.some(role => role.name === '⚙️ | Manager'))
{message.channel.send('Pong!');} else {
message.channel.send('Not enough rights! :no_entry:');
}}
if (message.content.startsWith(`${prefix}test`)) {
if (message.author.id == '.........') {
const role = message.guild.roles.find('name', 'test');
message.member.addRole(role);
message.channel.send('test');
}}});
client.login(token);
I expect it to output it onces, but I don't get it to work.
This is the output:
I want him to do it only once.
Yeah I've had that problem before, simply turn off the bot from everything you're hosting it on, you were probably logged in on it multiple times, that might be because you're running it on a raspberry pi and did not properly shut it.

Discord.js const guild = member.guild;

Hello Programmers I Have Problem With Discord.js I Made Bot Which Is Says Hello #user But It Doesn't Work
Here Is My Code:
Javascript
const Discord = require("discord.js");
const TOKEN = "private";
const PREFIX = "!";
const newUser = new Discord.Collection();
const talkedRecently = new Set();
var bot = new Discord.Client();
var fortunes =
[
"Yes",
"No",
"Maybe",
"IDK"
];
bot.on("ready", () => {
});
client.on("guildMemberAdd", (member) => {
const guild = member.guild;
newUsers.set(member.id, member.user);
if (newUsers.size > 0) {
const defaultChannel = guild.channels.find(c=> c.permissionsFor(guild.me).has("SEND_MESSAGES"));
const userlist = newUsers.map(u => u.toString()).join(" ");
defaultChannel.send("Hello Creativistian!\n" + userlist);
newUsers.clear();
}
});
});
bot.login(TOKEN);
Does Anyone Know How To Fix It
Replace client.on("guildMemberAdd", (member) => { with this:
bot.on('guildMemberAdd', member => {
Note: as #Noobly387 said, you have an extra });, on line 15, please remove that.
Cheers
To fix your problem remove }); on line 15 just after bot.on("ready", () => {.
In the future, please provide more information on your issue.
Although, your error is that you have an extra unnecessary });.
In the future, be sure to state your question in the title so people can help you easier.
On line 15, you have an extra }); below your bot.on("ready", () => { code. This breaks the code because by ending the bot.on line, the rest of the code below will not work since it becomes just regular functions.
Also, as a side note, I would recommend for you to make your arrays single line if they are small (such as your fortunes array) and also don't space out your code too much or you won't be able to see the small problems such as the one that broke your code.
Replace client.on("guildMemberAdd", (member) => { with this :
bot.on('guildMemberAdd', member => {
PS: on line 15 you have an extra unnecessary });
Use that with ALL THE INTENTS ON.
bot.on("guildMemberAdd", member => {
// Code..
});
That work in discord.jsv12, to install type this command
npm install discord.js#v12

Discord.js setGame() not working anymore

I have been coding my Discord bot using Discord.JS for about 2 months now and I've just recently noticed that my bot isn't saying that it's playing what I'm telling it. When I first coded the bot up until recently it worked just fine. Now the 3 discord bots I have aren't showing their games.
This is the code I'm using:
const Discord = require("discord.js");
const bot = new Discord.Client();
bot.on("ready", () => {
console.log("Ready");
bot.user.setGame("Type !help");
}
.setGame() is deprecated now but you could use .setPresence() or you could use the .setActivity() which is the same thing and format as the .setGame().
Ex.
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.user.setActivity('YouTube', { type: 'WATCHING' });
Here is a link to the documentation in case you wanted to change 'Watching' to something else like 'Playing'.
setGame() is now deprecated, and discord.js asks you to use setActivity().
const Discord = require("discord.js");
const bot = new Discord.Client();
bot.on("ready", () => {
console.log("Ready");
bot.user.setActivity("Type !help");
})
Hope this helped.
The setGame() Method has stopped working, here's what you can do:
update to latest 11.1-dev or
use .setPresence({ game: { name: 'nameGoesHere', type: 0 } }); as a workaround instead
Source: https://github.com/hydrabolt/discord.js/issues/1807#issuecomment-323578919
Here's a short example of using the .setPresence that LW001 linked to:
var Discord = require('discord.js');
var bot = new Discord.Client();
bot.on('ready', () => {
bot.user.setStatus('available') // Can be 'available', 'idle', 'dnd', or 'invisible'
bot.user.setPresence({
game: {
name: 'Type !help',
type: 0
}
});
});
https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setGame
setgame is depreciated use setActivity instead
example:
client.user.setActivity('activity here')
Or:
client.user.setActivity('activity here', {type: "WATCHING"})
type can be WATCHING, LISTENING, PLAYING or STREAMING
if streaming you need to add this below the setActivity code
url: "twitch.tv/urtwitchusername",

Categories

Resources