Skip to content

Instantly share code, notes, and snippets.

@drakantas
Last active May 26, 2022 17:28
Show Gist options
  • Save drakantas/ec2c524b95a688b1618d7cc810d490c4 to your computer and use it in GitHub Desktop.
Save drakantas/ec2c524b95a688b1618d7cc810d490c4 to your computer and use it in GitHub Desktop.
Get Discord invite links from a message using regex
from __future__ import print_function
import re
DISCORD_INVITE = r'discord(?:\.com|app\.com|\.gg)[\/invite\/]?(?:[a-zA-Z0-9\-]{2,32})'
messages = (
"Hey, join my guild and get awesome prizes. https://discord.gg/0cDvIgU2voWn4BaD",
"Yo. Don't join that dude's guild, these guilds are even more awesome https://discord.gg/discord-api "
"https://discord.gg/discord-developers",
"There's no invites in this message."
)
def main():
for message in messages:
print(message + '\nINVITES FOUND:', get_invites(message), '\n')
# Returns a tuple of invite links if there's any, or None in case there is not.
# No type annotations because I want this to run anywhere.
def get_invites(message):
regex = re.compile(DISCORD_INVITE)
invites = regex.findall(message)
return invites or None
if __name__ == '__main__':
main()
@kpodp0ra
Copy link

There's a bug in DISCORD_INVITE regex.
get_invites("https://discord.gg/cyberpunkgame") == "discord.gg/cyberpu" ;/

@drakantas
Copy link
Author

get_invites returns a List of str containing the invite links, not a string. @panklipcio

@kpodp0ra
Copy link

If invite code doesn't have any of this characters: Ii10OolL-, his ending will be cut off to 6 letters.
For example cyberpunk's invite is discord.gg/cyberpunkgame, and it's incorrectly matched in script.

Console log:

Hey, join my guild and get awesome prizes, https://discord.gg/cyberpunkgame
INVITES FOUND: ['discord.gg/cyberpu']

@drakantas
Copy link
Author

Ok.
Thanks for the report, the regex has been updated. @panklipcio

@GrJT
Copy link

GrJT commented Nov 4, 2020

I tried using this to detect invites in messages and deleting them if so. Worked fine until a member tried to send a meme video by its link and it kept getting deleted. The link was "https://cdn.discordapp.com/attachments/428187470929199125/771789217402454106/video0_2_1.mp4". I don't know if this will detect other links, so i stopped using it for now.
Could you do something about it, please?

@kpodp0ra
Copy link

kpodp0ra commented Nov 9, 2020

Hi @GrJT, please use my corrected regex: discord(?:\.com|app\.com|\.gg)/(?:invite/)?([a-zA-Z0-9\-]{2,32}).
I tested it and its actually works. (@drakantas you can update this gist with my regex too)

@XPMai
Copy link

XPMai commented Mar 6, 2021

Hi @GrJT, please use my corrected regex: discord(?:\.com|app\.com|\.gg)/(?:invite/)?([a-zA-Z0-9\-]{2,32}).
I tested it and its actually works. (@drakantas you can update this gist with my regex too)

"Your" regex wouldn't solve @GrJT's problem either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment