recently I made a discord bot that bans new members automaticly when someone who created their account less then 30 days ago joins.The problem is that when someone joins nothing happens and neither the log shows anything.Wondering what could be the problem.thanks!!
`const { Client, Intents,GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: GatewayIntentBits.Guilds
});
client.on('guildMemberAdd', member => {
console.log(`${member.user.username} csatlakozott a szerverhez.`);
const currentTime = Date.now();
const creationTime = member.user.createdAt.getTime();
const ageInMs = currentTime - creationTime;
const ageInDays = ageInMs / 1000 / 60 / 60 / 24;
if (ageInDays < 30) {
console.log(`${member.user.username} fiókja egy hónapnál fiatalabb. Bannolás és üzenet küldése...`);
member.ban({ reason: 'Fiók létrehozási dátuma egy hónapnál fiatalabb' });
member.send('Sajnáljuk, de a fiókod egy hónapnál fiatalabb, így nem tudsz csatlakozni a szerverhez.')
.then(() => console.log(`Üzenet elküldve ${member.user.username}-nek.`))
.catch(error => console.error(`Hiba történt az üzenet küldése közben: ${error}`));
}
});
client.login('token')
.then(() => console.log('Bot bejelentkezve.'))
.catch(error => console.error(`Hiba történt a bejelentkezés közben: ${error}`));
`
tried:
Joining several servers, the log should of show the join, and automaticly ban the member.
According to this link https://discordjs.guide/popular-topics/intents.html#enabling-intents
If you want your bot to post welcome messages for new members (GUILD_MEMBER_ADD - "guildMemberAdd" in discord.js), you need the GuildMembers privileged intent, and so on.
change this
const client = new Client({
intents: GatewayIntentBits.Guilds
});
for this
const client = new Client({
intents: [
GatewayIntentBits.GuildMembers
]
})
This should also work (although I did not try it)
const client = new Client({ ws: { intents: ['GUILD_MEMBER_ADD'] } });
Restart your bot and it should work. I managed to test it and ban a new account (I did not test if your bot also ban older accounts)
You can find the list of intents here https://discord.com/developers/docs/topics/gateway#list-of-intents
Related
the code says invalid bitfield and has no idea how to fix it, the intents are fine I think and I think everything should be normal. i have tried to combine code from a bot from a snippet someone sent, maybe thats why this doesnt work
code :
const { Client, Intents, Message} = require('discord.js');
const util = require('minecraft-server-util');
const {EmbedBuilder} = require('discord.js');
const options = {
timeout: 1000 * 5,
enableSRV: true
};
const prefix = "!mcstatus";
const client = new Client({
intents: [
"Guilds",
"GuildMessages",
"MessageContent"
]
});
client.on('ready', () => {
console.log('bot started');
client.user.setPresence({ activities: [{ name: `${server_ip}`, type: 'WATCHING' }], status: 'active' });
});
const server_ip = "mc.hypixel.net";
const server_port = 25565;
client.on('messageCreate', (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
if(message.content.startsWith(prefix)){
util.status(server_ip, server_port, options)
.then((result) => {
const embed = new EmbedBuilder()
let args = message.content.split(" "); // Splitting with a blank space.
args = args.slice(1); // Remove the first argument which would be the command itself.
const server_port = 25565; // Leave the default port for MC servers.
if (args.length < 1) return message.reply("Didn't provide arguments.")
// Run a forEach loop for every argument.
args.forEach((arg) => {
util
.status(arg, server_port, options)
.then((result) => {
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("Results")
.setDescription(
`This will show the status and info about the minecraft server \n **Server ip:** ${arg} \n **Server port:** ${server_port}`
)
.addFields(
{ name: "Server Version", value: `${result.version.name}` },
{
name: "Server Protocol Version",
value: `${result.version.protocol}`,
},
{ name: "Players Online", value: `${result.players.online}` },
{ name: "Max Players", value: `${result.players.max}` },
{
name: "MOTD (May Not Display Accurately)",
value: `${result.motd.clean}`,
},
{ name: "Latency", value: `${result.roundTripLatency}` }
)
.setTimestamp();
message.channel.send({ embeds: [embed] });
})
.catch((error) => {
const embed = new EmbedBuilder()
.setColor("#808080")
.setTitle("Error")
.setDescription(
`${arg} was unable to be pinged or you mis-typed the info`
)
.setTimestamp();
message.channel.send({ embeds: [embed] });
});
});
message.channel.send({embeds: [embed]})
})}});
log i have tried to google things but i couldnt find anything that helps my thing
RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number: Guilds.
at Intents.resolve (C:\Users\jason\Desktop\discord minecraft bot test 2\node_modules\discord.js\src\util\BitField.js:152:11)
at C:\Users\jason\Desktop\discord minecraft bot test 2\node_modules\discord.js\src\util\BitField.js:147:54
at Array.map (<anonymous>)
at Intents.resolve (C:\Users\jason\Desktop\discord minecraft bot test 2\node_modules\discord.js\src\util\BitField.js:147:40)
at Client._validateOptions (C:\Users\jason\Desktop\discord minecraft bot test 2\node_modules\discord.js\src\client\Client.js:550:33)
at new Client (C:\Users\jason\Desktop\discord minecraft bot test 2\node_modules\discord.js\src\client\Client.js:76:10)
at Object.<anonymous> (C:\Users\jason\Desktop\discord minecraft bot test 2\index.js:9:16)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32) {
[Symbol(code)]: 'BITFIELD_INVALID'
}
Node.js v18.12.1
PS C:\Users\jason\Desktop\discord minecraft bot test 2>
First of all, please see the guide on how to use intents. (It's really useful!)
This doesn't look like DJSv14 code either. v14 snippets can be found in the guide as well.
To fix your issue you can change the way you define your intents when instantiating your new client like so;
const { GatewayIntentBits } = require('discord.js');
// ...
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
],
});
OT: Newer D.JS versions have application commands, I highly recommend you use those instead of prefix commands!
I'm trying to make my bot in discord on javascript, the bot goes online, shows in the console, but does not respond to messages
const Discord = require("discord.js")
const TOKEN = "MY TOKEN"
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages"
]
})
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
client.on("message", message => {
if (message.content.includes('ping'))
if (userCooldown[message.author.id]) {
userCooldown[message.author.id] = false;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = true;
}, 5000) // 5 sec
}
})
client.login(TOKEN)
Alright, there are a few issues at play here. Before I start, I should say that discord bots are moving away from reading message content and towards slash commands. If you have the opportunity to, please move towards slash commands. If you're looking for an up-to-date tutorial check out https://discordjs.guide.
With that being said, let me go through each issue one by one.
You're not asking for the MessageContent intent. You will not be able to check if the user's message contains ping
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages",
"MessageContent"
]
})
I don't know if this is because this code has been shortened or not, but you're not defining userCooldown anywhere.
const userCooldown = {}
message doesn't exist as an event anymore. Use messageCreate instead
Your cooldown logic doesn't really work. I would flip the boolean around
client.on("messageCreate", message => {
if (message.content.includes('ping')) {
if (!userCooldown[message.author.id]) {
userCooldown[message.author.id] = true;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000) // 5 sec
}
}
})
You might have forgotten to enable this in the discord developer portal.
The complete code I used to make it work is below. I wish you luck on your discord developer journey.
const Discord = require("discord.js")
const TOKEN = "TOKEN_HERE"
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages",
"MessageContent"
]
})
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
const userCooldown = {}
client.on("messageCreate", message => {
if (message.content.includes('ping')) {
if (!userCooldown[message.author.id]) {
userCooldown[message.author.id] = true;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000) // 5 sec
}
}
})
client.login(TOKEN)
I am creating a discord BOT that sends news to discord, the data is taken from the API, I want every time the API returns new data, the BOT will send a message to the sever
const {
Client,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
})
const fetch = require("node-fetch")
const moment = require("moment")
const delay = require("delay")
//function fetch news from API
function getNews() {
return fetch("https://vnwallstreet.com/api/inter/newsFlash/page?important=1&limit=1&start=0&status=-1&uid=-1&time_=1645354313863&sign_=D7CA264A553C671A02DDA0FAA891EE8E")
.then(res => {
return res.json()
})
.then(data => {
return moment(data.data[0]["createtime"]).format("lll") + " - " + data.data[0]["content"]
}
})
}
client.login("TOKEN")
async function main() {
while (true) {
client.on("ready", () => {
client.channels.fetch('944915134315397123')
.then(channel => {
getNews().then(quote => channel.send(quote))
})
console.log(`Logged in as ${client.user.tag}!`)
})
await delay(60 * 1000)
}
}
main()
I am facing 2 problems:
I can't check when the API returns new data because I just want to send new data to the discord channel
When I use 'delay' once every 1 min in main function, it gives the following error:
(node:244) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 ready listeners added to [Client]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
You can't just listen to the ready event every minute. That's gonna cause a memory leak as the warning says.
Make sure the client is ready and fetch the API every 1 minute after that rather than listening to the event again and again, then send the payload to the channel, you don't have to fetch the channel every time either, it's already in the cache.
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
client.on('ready', async () => {
const channel = await client.channels.fetch('id')
setInterval(() => {
fetchDataSomehow().then((data) => {
channel.send(data)
})
}, 60 * 1000) // runs every 60000ms (60s)
})
const Discord = require("discord.js");
const Bot = new Discord.Client({Intents:[Discord.Intents.FLAGS.GUILD_MEMBERS, Discord.Intents.FLAGS.GUILDS]})
Bot.on('ready', () => {
console.log("The bot is online")
let commands = Bot.application.commands;
commands.create({
name: "hello" ,
description: "reply hello to the user",
options: [
{
name: "person",
description: "The user you want to say hello to",
require: true,
type: Discord.Constants.ApplicationCommandOptionTypes.USER
}
]
})
})
Bot.on('interactionCreate', interaction => {
if(!interaction.isCommand()) return;
let name = interaction.commandName
let options = interaction.options;
if(name == "hello") {
interaction.reply({
content: "Hello",
ephemeral: false
})
}
if(name == "sayhello"){
let user = options.getUser('person');
interaction.reply({
content: 'Hello ${user.username}
})
}
})
bot.login("token")
The intents is option is lowercase, not capitalised. See ClientOptions.
Well actually since the new discord.js update you need to provide the intents to the bot. This might help
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
Since discord.js v13, you need to provide Intents when declaring the client. They were introduced by Discord so that developers can choose what type of data the bot will need to receive. All you have to do is add intents when declaring the client. The code might look something like this:
const { Client } = require('discord.js')
const client = new Client({
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES
]
})
And also, as pointed by #Richie Bendall, you have capitalised the I when declaring the intents. You can learn more about intents in here => Gateway Intents | Discord.js
I want to get all the users in my servers on ready of my discord bot so that I can add them to a database.
I have the discord privileged gateway intents all turned on. But I am only getting the id of a single user with the following code:
client.once('ready', () => {
client.guilds.cache.values().next().value.members.list().then((members) => {
members.each(member => {
console.log(member.id)
});
})
})
I am sure I have included all the intent that would be necessary while creating my client:
const client = new Client({ intents: ["GUILDS", "GUILD_MEMBERS", "GUILD_BANS", "GUILD_EMOJIS_AND_STICKERS",
"GUILD_INTEGRATIONS", "GUILD_WEBHOOKS", "GUILD_INVITES", "GUILD_VOICE_STATES", "GUILD_PRESENCES", "GUILD_MESSAGES",
"GUILD_MESSAGE_REACTIONS", "GUILD_MESSAGE_TYPING"]} )
I dont know why it is giving id of only 1 member (owner) while the test server has 3 members including the bot.
client.guilds.cache.get(guild_id).members.cache.map(member => member.id)