Search code examples
pythonpython-3.xdiscord.pypython-re

How to find all Discord Invites in a message


How to find all Discord Server Invites in a message. I have asked a similar question before but it doesn't work for me somehow. So I came up here. I can find nothing more about this in the Internet. The "re" package could possibly work but what is the regex?

import re

inviteregex = re.compile(r'discord(.gg|.com/invite)/.{3,10}')
links = re.findall(inviteregex, 'here is the link discord.gg/gpDcZfF')
print(links)

Expected Comeout:

['discord.gg/gpDcZfF']

But the result is:

['.gg']

Solution

  • The regex for an invite is the next one:

    (?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?
    

    Applied to the on_message event

    async def on_message(message):
        invite_regex = re.compile("(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?")
        result = invite_regex.findall(message.content)
    
        print(result)