Search code examples
javascriptdiscord.js

get an invite from message - discord.js


I'm making a discord bot in discord.js (v14.14.1) that checks a message for invites and if there isn't any it deletes the message, but if there is it checks that server's name

My problem is that I know how to get a guild from the invite, thought I don't know how to only get the invite from that message

The best solution I can think of is to just get a part of message that matches regex, and then extract the invite code from it, tho i have no idea how to find a part of msg that matches regex


Solution

  • The regex provided in the snippet can be used to capture standard Discord invite links while excluding Discord media or attachment links. To extract the invite from a message using this regex, you can use JavaScript's match() function with the regex pattern.

    function findDiscordInvites(message) {
      // Define the regex pattern
      const regex = /(https?:\/\/|http?:\/\/)?(www.)?(discord.gg|discord.io|discord.me|discord.li|discordapp.com\/invite|discord.com\/invite)\/[^\s\/]+?(?=\b)/g;
    
      // Use the RegExp to search for matches in the message
      const matches = message.match(regex);
      
      // Return an array of matches
      return matches;
    }
    
    // Examples
    const textWithInviteLink = "Check out this discord invite: https://discord.gg/abc123";
    console.log("Matches expected", findDiscordInvites(textWithInviteLink));
    
    const textWithoutInviteLink = "Check out this image! https://cdn.discordapp.com/attachments/abc123";
    console.log("No matches expected:", findDiscordInvites(textWithoutInviteLink));

    I hope this answers your question.