I’m working on a Discord bot and I want it to send a PDF file to new members when they join the server. I’m using discord.js and Node.js. Here’s what I’ve tried:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildMemberAdd', async newMember => {
try {
await newMember.send('Welcome to our server!');
await newMember.send({ files: ['./welcome_guide.pdf'] });
} catch (error) {
console.error('Failed to send DM:', error);
}
});
client.login('MY_BOT_TOKEN');
This code doesn’t work as expected. The welcome message sends fine, but the PDF doesn’t. I’ve also tried getting the user’s ID, but newMember.userId
and newMember.guild.id
both return undefined.
How can I fix this to successfully send a PDF to new members? Is there a different way to handle file attachments in DMs for the guildMemberAdd event? Any help would be awesome!
As someone who’s built a few Discord bots, I can tell you that sending PDFs can be tricky. One thing that worked for me was using a buffer instead of a file path. Here’s what I did:
const fs = require('fs');
const buffer = fs.readFileSync('./welcome_guide.pdf');
const attachment = new Discord.MessageAttachment(buffer, 'welcome_guide.pdf');
await newMember.send({ files: [attachment] });
This approach solved my issues with file sending. Also, make sure your PDF isn’t too large - Discord has file size limits for bots. If it’s still not working, you might want to check your bot’s permissions or try uploading the PDF to a file hosting service and sending the link instead. That’s a reliable fallback method I’ve used before.
I’ve encountered similar issues when working with Discord bots. The problem might be related to file path resolution. Try using an absolute path instead of a relative one for your PDF file. You can use __dirname
to get the current directory:
const path = require('path');
const pdfPath = path.join(__dirname, 'welcome_guide.pdf');
await newMember.send({ files: [pdfPath] });
Also, make sure your bot has the necessary permissions to send files in DMs. You might need to enable the ‘ATTACH_FILES’ intent when creating your client:
const client = new Discord.Client({ intents: ['GUILDS', 'GUILD_MEMBERS', 'DIRECT_MESSAGES', 'ATTACH_FILES'] });
If you’re still having trouble, consider using a readable stream instead of a file path:
const fs = require('fs');
const attachment = new Discord.MessageAttachment(fs.createReadStream(pdfPath), 'welcome_guide.pdf');
await newMember.send({ files: [attachment] });
Hope this helps!
hey mate, i had a similar issue. try using the attachement method instead:
const attachment = new Discord.MessageAttachment('./welcome_guide.pdf');
await newMember.send({ files: [attachment] });
also double check ur file path is correct. good luck!