How to send a direct message to a user using Discord.js? [duplicate] - discord

I am trying to code a Discord bot for my personal server. I am using Discord.js and I have been following the discord.js guide.
I have now an event handler but when I add a file for another event, the code of this module is not executing. The event I am trying to trigger is the join of a new member in my server.
I have 2 important files : index.js which runs the corpse of my code and guildMemberAdd.js which is my event module for when a new member joins the server.
index.js:
// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// Log in to Discord with your client's token
client.login(token);
guildMemberAdd.js:
const { Events } = require('discord.js');
module.exports = {
name: Events.GuildMemberAdd,
async execute(member) {
console.log(member);
},
};

If you only have the GatewayIntentBits.Guilds intent enabled, the GuildMemberAdd event won't fire. You'll need to add the GatewayIntentBits.GuildMembers (and probably GatewayIntentBits.GuildPresences) too:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildPresences,
],
});
In discord.js v13, it should be:
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_PRESENCES,
],
});

Related

TypeError when trying to create a discord bot

I'm trying to build a discord bot that sends data to an airtable. This one sends user info when they join my server. I have the following code, but every time I try to run it, I get the following error:
TypeError: Cannot read properties of undefined (reading 'GUILDS')at Object.
This is the code:
const { Intents } = require('discord.js');
const Discord = require('discord.js');
const Airtable = require('airtable');
const client = new Discord.Client({
token: 'TOKEN_ID',
intents: [Intents.GUILDS, Intents.GUILD_MEMBERS]
});
Airtable.configure({ apiKey: 'API_KEY' });
const base = Airtable.base('BASE_ID');
client.on('guildMemberAdd', member => {
base('New Members').create({
'Username': member.user.username,
'Time Joined': new Date().toISOString()
}, function(err, record) {
if (err) {
console.error(err);
return;
}
console.log(`Added new record with ID ${record.getId()}`);
});
});
client.login();
Using Discord.js v14, the way to declare intents is as follows:
import { Client, GatewayIntentBits } from "discord.js";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers
]
});
and your token should be put in client.login
client.login("your-bot-token");

Permission Error Nickname Change Command discord js

There is no permission error when using code a, but there is a permission error whenever using code b. Is there a solution?
module.exports = {
name: "NICK",
async execute(message, args, client) {
//A: const member = message.mentions.members.first();
//B: const member = await message.guild.members.cache.get(message.author.id)
console.log(message.author.id)
if (!member) return message.reply("target error");
const arguments = args.shift(1)
if (!arguments) return message.reply("name error");
try {
const arguments = args.shift(1)
member.setNickname(arguments);
}catch (error) {
console.error(error);
}
},
};
I currently have these intents
const { Client, GatewayIntentBits, Collection, MembershipScreeningFieldType, ClientUser, User, time, GuildChannel, GuildManager, MessageManager, GuildMemberManager, GuildBanManager, GuildBan, GuildStickerManager, PermissionsBitField, PermissionOverwriteManager, MessageFlagsBitField, GuildMemberRoleManager, gu } = require('discord.js');
const { record } = require('../config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildBans] });
Checking code B I could say a few things:
You don't need to await a cache.get() call;
If you are the owner of the guild, then the bot needs to have a role above your highest role to change your nickname.

discord.js v13 SlashCommandBuilder Reaction Roles

So i need help with the assign roles part - so if someone click on the reaction(emojiID) it should give the user who clicked on it the role(roleID)..
My code below sends the embed in the channel with my title & description and the emoji, but nothing happend if someone clicked on the emoji!
I use SlashCommandBuilder :
const { SlashCommandBuilder } = require('#discordjs/builders');
const fs = require('fs');
const { Client, Intents, MessageEmbed, MessageReaction } = require('discord.js');
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
],
partials: ["MESSAGE", "CHANNEL", "REACTION"]
});
module.exports = {
data: new SlashCommandBuilder()
.setName('reaction')
.setDescription('Create reaction messages')
.addChannelOption((option) => {
return option
.setName('channel')
.setDescription('Choose a channel')
.setRequired(true)
})
...
async execute(interaction, client) {
const channelID = interaction.options.getChannel('channel');
const titleID = interaction.options.getString('title');
const descID = interaction.options.getString('desc');
const emojiID = interaction.options.getString('emoji');
const roleID = interaction.options.getRole('role');
let embed = new MessageEmbed()
.setTitle(titleID)
.setDescription(descID)
channelID.send({ embeds: [embed] }).then((sentMessage) => {
sentMessage.react(emojiID);
The code above is the working part - for the roles - I tried something like
async (reaction, user) => {
if(reaction.interaction.partial) await reaction.interaction.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.interaction.guild) return;
if(reaction.interaction.channel.id === channelID) {
if(reaction.emoji.id === emojiID) {
reaction.interaction.guild.members.cache.get(user.id).roles.add(roleID)
}
}
};
but this is not working, please help :)

My discord bot is not responding even though there is no error

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const config = require('./config.json');
client.once('ready', () => {
console.log("go");
})
client.on('message', (message) => {
if(message.content == "ping"){
message.channel.send("pong");
}
})
client.login(config.token);
There is no error in the code, but when I type ping, the bot does not respond, does anyone know why?
It's because you don't have the GUILD_MESSAGES intent enabled !
Replace that line :
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
with
const client = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES] });
As you can see from the official documentation :
GUILD_MESSAGES intent let us have events and one of them is MESSAGE_CREATE (emits when a message is created (sent))
Since after the new update of discord.js, providing intents is an integral part of Disocrd bots.
const {Client, Intents, Collection} = require('discord.js')
const client = new Client({intents:[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]})

Welcome message in a specific channel when a user joins the server. (guildMemberAdd, discord.js)

How do I make it so that my bot sends a message in a specific channel when a user joins?
When I do this, it logs nothing: (Also here are my bot settings)
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const { MessageEmbed } = require('discord.js');
client.on("ready", () => {
console.log("Cloud Shield has been activated.")
});
client.on("guildMemberAdd", async (member) => {
console.log(member);
});
client.login(process.env.token)
This is because you are not requesting the GUILD_MEMBERS intent.
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MEMBERS"] });
const { MessageEmbed } = require('discord.js');
client.on("ready", () => {
console.log("Cloud Shield has been activated.")
});
client.on("guildMemberAdd", async (member) => {
console.log(member);
});
client.login(process.env.token)

Resources