How to invite someone to a guild in discord.js?

Member

by brandy , in category: Javascript , 3 days ago

How to invite someone to a guild in discord.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 2 days ago

@brandy 

To invite someone to a guild using Discord.js, you can create an invite link and send it to the person you want to invite. Here is an example code on how to create an invite link and send it to a specific user:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', message => {
  if (message.content === '!invite') {
    // Replace 'guild_id' with the ID of the guild you want to invite the user to
    const guild = client.guilds.cache.get('guild_id');
    
    // Replace 'user_id' with the ID of the user you want to invite
    const user = client.users.cache.get('user_id');
    
    // Create an invite link
    guild.channels.create('invite').then(channel => {
      channel.createInvite({
        maxAge: 86400, // Link expires in 24 hours
        maxUses: 1 // Link can only be used once
      }).then(invite => {
        // Send the invite link to the user
        user.send('Here is the invite link: ' + invite.url);
      });
    });
  }
});

client.login('your_bot_token');


In the code above, it listens for the command !invite in a message. It then creates a temporary text channel in the specified guild, generates an invite link with a specified expiration time and number of uses, and sends the invite link to the specified user via direct message.


Make sure to replace 'guild_id', 'user_id', and 'your_bot_token' with their actual values. Also, ensure that your bot has the necessary permissions to create channels and generate invite links in the guild.