Search code examples
pythonescapingchatbotdiscord.py

How do I escape @everyone in discord.py?


I'm developing a Discord bot in Python which outputs text based on user input. I want to avoid users getting it to say @everyone (and @here) which would tag and annoy everyone.

I tried using \@everyone which in contrast to @everyone does not make the text itself blue, but it still triggers a ping and highlights the line in yellow. This does not only happen when I send a message with the bot but also if I use Discord directly.


Solution

  • The solution I've been using is to insert a zero-width space after the '@'. This will not change the text appearance ('zero-width') but the extra character prevents the ping. It has unicode codepoint 200b (in hex):

    message_str = message_str.replace('@', '@​\u200b') 
    

    More explicitly, the discord.py library itself has escape_mentions for that purpose:

    message_str = discord.utils.escape_mentions(message_str)
    

    which is implemented almost identically:

    def escape_mentions(text):
        return re.sub(r'@(everyone|here|[!&]?[0-9]{17,21})', '@\u200b\\1', text)