skip to Main Content

I want to create a discord invite with my discord bot and after getting the invite link I want to send it as an response and that invite should expire after 15 mins, so how can I do this and please tell me if there’s any limit to requests or not.

import express from "express";
import http from "http";
import { Client, GatewayIntentBits, Guild } from "discord.js";
import { DISCORD_BOT_TOKEN, DISCORD_SERVER_ID, PORT } from "./constants.js";

const app = express();
const server = http.createServer(app);

// Discord Client
const client = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});

app.get("/", () => {
  console.log("works");
});

app.get("/generate-invite", async (req, res) => {
  try {
    const server = client.guilds.cache.get(DISCORD_SERVER_ID);
    // Send the invite URL in the response
    // res.json({ inviteUrl: invite.url });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Failed to generate invite" });
  }
});

server.listen(PORT, () => {
  console.log(`Server started on ${PORT}`);
});

client.login(DISCORD_BOT_TOKEN);

I am failing to access that server object it says something like <ref *2> in my terminal tell me what’s this too and how to access this too.

2

Answers


  1. You can use the createInvite() method from on a text channel and specify the maxAge in the InviteCreateOptions.

    server.createInvite({ maxAge: 15 * 60 }).then((inviteLink) => {/* do whatever with the invite here */})
    
    Login or Signup to reply.
  2. You should use the createInvite() method from any GuildChannel. You will have to specifiy an InviteCreateOptions object with your expiration age.


    The code should look something like this:

    const server = client.guilds.cache.get(DISCORD_SERVER_ID); // put the guild ID
    const channel = server.channels.find(DISCORD_CHANNEL_ID); // put the channel ID
    
    channel.createInvite({ 
       maxAge: 15 * 60, // max age in seconds (15 minutes here)
       reason: "Generated via /generate-invite command" // (reason: optional)
    }).then((inviteURL) => {
       res.json({
          invite: {
             url: inviteURL
          }
       })
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search