Home > OS >  How to delete all messages that have URLs that are not www.youtube.com or www.twitter.com
How to delete all messages that have URLs that are not www.youtube.com or www.twitter.com

Time:10-26

I am new here, and recently I have been facing a big problem with Discord Scam Links in my Discord server, I tried that:

if(message.content.includes("discordscam.com")) {
   message.delete()
   }

But this is a very bad way to fight scams since it will only delete one specific URL and not other ones, I realized that I should use RegExp, but, unfortunately, I don't understand how.

CodePudding user response:

Because contents may include multiple urls, you'll need to check each word. First filter words to just any urls. Then from there check if any of the urls aren't twitter or youtube.

First regex is for url /^(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()!@:%_\ .~#?&\/\/=]*)/

Next regex is for allowed urls (youtube|twitter).com

// split contents by word, check each word
function shouldDelete(contents){
   
    let urlFilter = contents.split(' ').map(word => {
        let t = word.match(/^(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()!@:%_\ .~#?&\/\/=]*)/)
        return t?.length > 0 ? t[0] : null
    }).filter(url=>{
        if(!url || /(youtube|twitter).com/g.test(url)) return
        else
          return url
    })
    if(urlFilter.length > 0){
        return `"${contents}" should delete`
    }else{
        return `"${contents}" shouldn't delete`
    }
}

let sampleContents=[
  'twitter.com',
  'youtube.com',
  'discordscam.com',
  'discordscam.com and youtube.com',
  'https://www.youtube.com/watch?time_continue=2&v=dQw4w9WgXcQ&feature=emb_logo'
]

sampleContents.forEach(item=>{
    console.log(shouldDelete(item))
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Hopefully this helps point you in the right direction!

I have a regular expression that is validating based on the string either having youtube or twitter, followed by .com and can not have any more periods afterwards.

const urlTest = str => 
  /^.*(youtube|twitter)\.com[^.]*$/.test(str);
  
console.log(`
  testing "youtube.com"
  good? ${urlTest("youtube.com")}
  
  testing "twitter.com"
  good? ${urlTest("twitter.com")}
  
  testing "youtube.com.net"
  good? ${urlTest("youtube.com.net")}
  
  testing "https://somesite.com/nothing"
  good? ${urlTest("https://somesite.com/nothing")}
  
  testing "https://youtube.com/somethingelse"
  good? ${urlTest("https://youtube.com/somethingelse")}
`);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related